CJVT updates August and September 2026
This commit is contained in:
@@ -27,9 +27,7 @@ class ConsultancyEntry {
|
||||
domain_primary_id: domainPrimaryId,
|
||||
first_name: firstName,
|
||||
last_name: lastName,
|
||||
is_moderator: isModerator,
|
||||
formatted_time_created: formattedTimeCreated,
|
||||
formatted_time_published: formattedTimePublished
|
||||
is_moderator: isModerator
|
||||
}) {
|
||||
this.id = id
|
||||
this.idExternal = idExternal
|
||||
@@ -51,8 +49,6 @@ class ConsultancyEntry {
|
||||
this.firstName = firstName
|
||||
this.lastName = lastName
|
||||
this.isModerator = isModerator
|
||||
this.formattedTimeCreated = formattedTimeCreated
|
||||
this.formattedTimePublished = formattedTimePublished
|
||||
}
|
||||
|
||||
// Fetch consultancy entry by ID
|
||||
@@ -65,7 +61,7 @@ class ConsultancyEntry {
|
||||
|
||||
id,
|
||||
id_external,
|
||||
to_char(time_created,'DD. MM. YYYY') time_created,
|
||||
time_created,
|
||||
status,
|
||||
author_id,
|
||||
institution,
|
||||
@@ -73,7 +69,7 @@ class ConsultancyEntry {
|
||||
domain_primary_id_initial,
|
||||
existing_solutions,
|
||||
examples_of_use,
|
||||
to_char(time_published,'DD. MM. YYYY') time_published,
|
||||
time_published,
|
||||
title,
|
||||
question,
|
||||
answer,
|
||||
@@ -96,7 +92,7 @@ class ConsultancyEntry {
|
||||
|
||||
id,
|
||||
id_external,
|
||||
to_char(time_created, 'DD. MM. YYYY') time_created,
|
||||
time_created,
|
||||
status,
|
||||
author_id,
|
||||
institution,
|
||||
@@ -104,7 +100,7 @@ class ConsultancyEntry {
|
||||
domain_primary_id_initial,
|
||||
existing_solutions,
|
||||
examples_of_use,
|
||||
to_char(time_published,'DD. MM. YYYY') time_published,
|
||||
time_published,
|
||||
title,
|
||||
question,
|
||||
answer,
|
||||
@@ -179,12 +175,12 @@ class ConsultancyEntry {
|
||||
static async fetchWithStatusById(status, id) {
|
||||
const sqlQuery = `
|
||||
SELECT ce.id,
|
||||
to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created,
|
||||
time_created,
|
||||
author_id,
|
||||
institution,
|
||||
description,
|
||||
domain_primary_id_initial,
|
||||
to_char(time_published, 'FMDD. FMMM. YYYY') time_published,
|
||||
time_published,
|
||||
title,
|
||||
question,
|
||||
answer,
|
||||
@@ -245,12 +241,12 @@ class ConsultancyEntry {
|
||||
static async fetchAllByStatusWithAuthorData(status) {
|
||||
const sqlQuery = `
|
||||
SELECT ce.id,
|
||||
to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created,
|
||||
time_created,
|
||||
author_id,
|
||||
institution,
|
||||
description,
|
||||
domain_primary_id_initial,
|
||||
to_char(time_published, 'FMDD. FMMM. YYYY') time_published,
|
||||
time_published,
|
||||
title,
|
||||
question,
|
||||
answer,
|
||||
@@ -303,12 +299,12 @@ class ConsultancyEntry {
|
||||
static async fetch5MostRecentPublished() {
|
||||
const sqlQuery = `
|
||||
SELECT ce.id,
|
||||
to_char(time_created, 'FMDD. FMMM. YYYY') formatted_time_created,
|
||||
time_created,
|
||||
author_id,
|
||||
institution,
|
||||
description,
|
||||
domain_primary_id_initial,
|
||||
to_char(time_published, 'FMDD. FMMM. YYYY') time_published,
|
||||
time_published,
|
||||
title,
|
||||
question,
|
||||
answer,
|
||||
|
||||
+228
-134
@@ -1,13 +1,19 @@
|
||||
const { mkdir, open, unlink } = require('fs/promises')
|
||||
const Cursor = require('pg-cursor')
|
||||
const db = require('./db')
|
||||
const { intoDbArray, getInstanceSetting } = require('./helpers')
|
||||
const {
|
||||
intoDbArray,
|
||||
getInstanceSetting,
|
||||
escapeLikePattern
|
||||
} = require('./helpers')
|
||||
const {
|
||||
deserialize,
|
||||
bulkIndex,
|
||||
getExportFilesPath
|
||||
getExportFilesPath,
|
||||
insertSuggestionEntry
|
||||
} = require('./helpers/dictionary')
|
||||
const { readFileIntoDb } = require('./helpers/dictionary/import-file')
|
||||
const { readJsonFileIntoDb } = require('./helpers/dictionary/import-json-file')
|
||||
const { transformAndAppend } = require('./helpers/dictionary/export-file')
|
||||
const { origin } = require('../config/keys')
|
||||
// const debug = require('debug')('termPortal:models/dictionary')
|
||||
@@ -35,8 +41,8 @@ class Dictionary {
|
||||
this.countComments = countComments
|
||||
}
|
||||
|
||||
// Fetch all dictionaries from DB.
|
||||
static async fetchAll(determinedLanguage) {
|
||||
// Fetch all published dictionaries from DB.
|
||||
static async fetchAllPublished(determinedLanguage) {
|
||||
// TODO Implement SQL stored procedures or functions.
|
||||
const { rows: fetchedDictionaries } = await db.query(`
|
||||
SELECT
|
||||
@@ -47,6 +53,7 @@ class Dictionary {
|
||||
count_entries,
|
||||
count_comments
|
||||
FROM dictionary
|
||||
WHERE status = 'published'
|
||||
ORDER BY time_modified DESC`)
|
||||
const deserializedDictionaries = fetchedDictionaries.map(
|
||||
dictionary => new this(dictionary)
|
||||
@@ -129,6 +136,16 @@ class Dictionary {
|
||||
return deserializedDomains
|
||||
}
|
||||
|
||||
// Fetch all secondary domains from DB, approved or not (for admin filtering).
|
||||
static async fetchAllSecondaryDomainsUnfiltered(determinedLanguage) {
|
||||
const { rows: fetchedDomains } = await db.query(`
|
||||
SELECT id, name_${determinedLanguage} name
|
||||
FROM domain_secondary
|
||||
ORDER BY name_${determinedLanguage}`)
|
||||
|
||||
return fetchedDomains
|
||||
}
|
||||
|
||||
// Fetch all languages from DB.
|
||||
static async fetchAllLanguages(determinedLanguage, excludeSlovene) {
|
||||
// TODO Implement SQL stored procedures or functions.
|
||||
@@ -223,6 +240,37 @@ class Dictionary {
|
||||
return deserializedSecondaryDomains
|
||||
}
|
||||
|
||||
// Soft-warning check: does any of the given (non-null) names collide with another own dictionary?
|
||||
static async checkNameCollision({
|
||||
nameSl,
|
||||
nameSlShort,
|
||||
nameEn,
|
||||
excludeDictionaryId
|
||||
}) {
|
||||
const values = [
|
||||
nameSl || null,
|
||||
nameSlShort || null,
|
||||
nameEn || null,
|
||||
excludeDictionaryId || null
|
||||
]
|
||||
const text = `
|
||||
SELECT id
|
||||
FROM dictionary
|
||||
WHERE
|
||||
count_comments IS NOT NULL AND
|
||||
($4::int IS NULL OR id <> $4) AND
|
||||
(
|
||||
($1::varchar IS NOT NULL AND name_sl = $1) OR
|
||||
($2::varchar IS NOT NULL AND name_sl_short = $2) OR
|
||||
($3::varchar IS NOT NULL AND name_en = $3)
|
||||
)
|
||||
LIMIT 1`
|
||||
|
||||
const { rows } = await db.query(text, values)
|
||||
|
||||
return rows.length > 0
|
||||
}
|
||||
|
||||
// Update single dictionary description in DB.
|
||||
static async updateDescription(dictionaryId, dictionary) {
|
||||
const values = [
|
||||
@@ -254,7 +302,7 @@ class Dictionary {
|
||||
}
|
||||
|
||||
// Delete secondary domain associations with a single dictionary from DB.
|
||||
static async deleteSecondaryDomains(dictionaryId, dictionary) {
|
||||
static async deleteSecondaryDomains(dictionaryId, dictionary, dbClient = db) {
|
||||
const value = [dictionaryId]
|
||||
|
||||
const text = `
|
||||
@@ -262,11 +310,11 @@ class Dictionary {
|
||||
dictionary_domain_secondary
|
||||
WHERE
|
||||
dictionary_id = $1`
|
||||
await db.query(text, value)
|
||||
await dbClient.query(text, value)
|
||||
}
|
||||
|
||||
// Insert new secondary domain associations with a single dictionary into DB.
|
||||
static async updateSecondaryDomains(dictionaryId, dictionary) {
|
||||
static async updateSecondaryDomains(dictionaryId, dictionary, dbClient = db) {
|
||||
const updatedSecondaryDomains = intoDbArray(
|
||||
dictionary.domainSecondary,
|
||||
'always'
|
||||
@@ -276,7 +324,15 @@ class Dictionary {
|
||||
const text = `
|
||||
INSERT INTO dictionary_domain_secondary (dictionary_id, domain_secondary_id)
|
||||
VALUES ($1, UNNEST($2::smallint[]))`
|
||||
await db.query(text, values)
|
||||
await dbClient.query(text, values)
|
||||
}
|
||||
|
||||
// Replace a dictionary's secondary domain associations atomically.
|
||||
static async updateSecondaryDomainAssociations(dictionaryId, dictionary) {
|
||||
await db.transaction(async dbClient => {
|
||||
await this.deleteSecondaryDomains(dictionaryId, dictionary, dbClient)
|
||||
await this.updateSecondaryDomains(dictionaryId, dictionary, dbClient)
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch single dictionary data for editing users from DB.
|
||||
@@ -395,7 +451,7 @@ class Dictionary {
|
||||
d.id,
|
||||
d.name_${determinedLanguage} dictionarysl,
|
||||
d.count_entries,
|
||||
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
|
||||
d.time_modified,
|
||||
d.issn,
|
||||
d.author,
|
||||
dp.name_${determinedLanguage} domain_primary,
|
||||
@@ -431,7 +487,7 @@ class Dictionary {
|
||||
distinct(d.id),
|
||||
${lang} dictionarysl,
|
||||
d.count_entries,
|
||||
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
|
||||
d.time_modified,
|
||||
d.issn,
|
||||
d.author,
|
||||
dp.name_sl domain_primary,
|
||||
@@ -452,73 +508,6 @@ class Dictionary {
|
||||
return rows
|
||||
}
|
||||
|
||||
// Fetch dictionary data for viewing details about it
|
||||
static async fetchBasicInfoPerPageFiltered(
|
||||
searchQuery,
|
||||
domainQuery,
|
||||
resultsPerPage,
|
||||
page
|
||||
) {
|
||||
let queryAppend = ''
|
||||
if (domainQuery.length > 0) {
|
||||
try {
|
||||
queryAppend = domainQuery.reduce((acc, e, i) => {
|
||||
if (i === 0) {
|
||||
let retstring = `( dp.id=${parseInt(e)}`
|
||||
|
||||
if (domainQuery.length - 1 === 0) {
|
||||
// if contains only one item -> "AND (dp.id=XXX)"
|
||||
retstring = `${retstring} )`
|
||||
}
|
||||
|
||||
// "AND [[( dp.id=XXX]]"
|
||||
return acc + retstring
|
||||
}
|
||||
if (i === domainQuery.length - 1) {
|
||||
return acc + ` OR dp.id=${parseInt(e)})`
|
||||
}
|
||||
|
||||
// "AND ( dp.id=XXX [[OR dp.id=YYY]]"
|
||||
return acc + ` OR dp.id=${parseInt(e)}`
|
||||
}, 'AND ')
|
||||
} catch (e) {
|
||||
queryAppend = ''
|
||||
}
|
||||
}
|
||||
|
||||
const isInEnglish = false
|
||||
const lang = isInEnglish ? 'name_en' : 'name_sl'
|
||||
const text = `
|
||||
SELECT
|
||||
distinct (d.id),
|
||||
d.${lang} dictionarysl,
|
||||
d.count_entries,
|
||||
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
|
||||
d.issn,
|
||||
d.author,
|
||||
dp.name_sl domain_primary,
|
||||
description,
|
||||
lp.name portalnamesl,
|
||||
lp.code portalcode
|
||||
FROM
|
||||
dictionary d
|
||||
FULL JOIN dictionary_language dl ON dl.dictionary_id = d.id
|
||||
INNER JOIN domain_primary dp ON d.domain_primary_id = dp.id
|
||||
LEFT JOIN linked_dictionary ld ON ld.target_dictionary_id = d.id
|
||||
LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id
|
||||
WHERE d.name_sl LIKE '%' || $1 || '%' ${queryAppend}
|
||||
LIMIT $2
|
||||
OFFSET $3`
|
||||
|
||||
const { rows } = await db.query(text, [
|
||||
searchQuery,
|
||||
resultsPerPage,
|
||||
resultsPerPage * (page - 1)
|
||||
])
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
// Fetch dictionary data for viewing details about it
|
||||
static async fetchBasicInfoPerPageFilteredWithOrdering(
|
||||
searchQuery,
|
||||
@@ -529,6 +518,10 @@ class Dictionary {
|
||||
orderIndex,
|
||||
determinedLanguage
|
||||
) {
|
||||
// Escaped so literal %/_ in a search term are matched as themselves,
|
||||
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
|
||||
const escapedSearchQuery = escapeLikePattern(searchQuery)
|
||||
|
||||
let queryAppend = ''
|
||||
if (domainQuery.length > 0) {
|
||||
try {
|
||||
@@ -567,7 +560,7 @@ class Dictionary {
|
||||
d.name_${determinedLanguage} dictionarysl,
|
||||
d.count_entries,
|
||||
d.count_comments,
|
||||
to_char(d.time_modified,'YYYY-MM-DD') time_modified,
|
||||
d.time_modified,
|
||||
d.issn,
|
||||
d.author,
|
||||
dp.name_${determinedLanguage} domain_primary,
|
||||
@@ -586,7 +579,7 @@ class Dictionary {
|
||||
OFFSET $3`
|
||||
|
||||
const { rows } = await db.query(text, [
|
||||
searchQuery,
|
||||
escapedSearchQuery,
|
||||
resultsPerPage,
|
||||
resultsPerPage * (page - 1)
|
||||
])
|
||||
@@ -596,6 +589,10 @@ class Dictionary {
|
||||
|
||||
// Fetch dictionary data for viewing details about it
|
||||
static async fetchFilteredCount(searchQuery, domainQuery) {
|
||||
// Escaped so literal %/_ in a search term are matched as themselves,
|
||||
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
|
||||
const escapedSearchQuery = escapeLikePattern(searchQuery)
|
||||
|
||||
let queryAppend = ''
|
||||
if (domainQuery.length > 0) {
|
||||
try {
|
||||
@@ -635,7 +632,7 @@ class Dictionary {
|
||||
LEFT JOIN linked_portal lp ON ld.linked_portal_id = lp.id
|
||||
WHERE d.status = 'published' AND d.name_sl LIKE '%' || $1 || '%' ${queryAppend}`
|
||||
|
||||
const { rows } = await db.query(text, [searchQuery])
|
||||
const { rows } = await db.query(text, [escapedSearchQuery])
|
||||
|
||||
return rows[0]
|
||||
}
|
||||
@@ -789,7 +786,7 @@ class Dictionary {
|
||||
}
|
||||
|
||||
// Delete language associations with a single dictionary from DB.
|
||||
static async deleteLanguages(dictionaryId) {
|
||||
static async deleteLanguages(dictionaryId, dbClient = db) {
|
||||
const value = [dictionaryId]
|
||||
|
||||
const text = `
|
||||
@@ -797,11 +794,11 @@ class Dictionary {
|
||||
dictionary_language
|
||||
WHERE
|
||||
dictionary_id = $1`
|
||||
await db.query(text, value)
|
||||
await dbClient.query(text, value)
|
||||
}
|
||||
|
||||
// Insert new language associations with a single dictionary into DB.
|
||||
static async updateLanguages(dictionaryId, dictionary) {
|
||||
static async updateLanguages(dictionaryId, dictionary, dbClient = db) {
|
||||
const updatedLanguages = intoDbArray(dictionary.language, 'always')
|
||||
const selectionOrder = updatedLanguages.map((language, index) => index + 1)
|
||||
const values = [dictionaryId, updatedLanguages, selectionOrder]
|
||||
@@ -809,15 +806,69 @@ class Dictionary {
|
||||
const text = `
|
||||
INSERT INTO dictionary_language (dictionary_id, language_id, selection_order)
|
||||
VALUES ($1, UNNEST($2::smallint[]), UNNEST($3::smallint[]))`
|
||||
await db.query(text, values)
|
||||
await dbClient.query(text, values)
|
||||
}
|
||||
|
||||
// Replace a dictionary's language associations atomically.
|
||||
static async updateLanguageAssociations(dictionaryId, dictionary) {
|
||||
await db.transaction(async dbClient => {
|
||||
await this.deleteLanguages(dictionaryId, dbClient)
|
||||
await this.updateLanguages(dictionaryId, dictionary, dbClient)
|
||||
})
|
||||
}
|
||||
|
||||
static async fetchAllAdminDictionaries(
|
||||
determinedLanguage,
|
||||
resultsPerPage,
|
||||
page
|
||||
page,
|
||||
sortBy,
|
||||
sortDir,
|
||||
filters = {}
|
||||
) {
|
||||
// TODO Implement SQL stored procedures or functions.
|
||||
// sortBy/sortDir must already be whitelisted by the caller (see
|
||||
// controllers/helpers/dictionary.js resolveDictionarySort) - this map is
|
||||
// a defense-in-depth fallback, never interpolate req.query values directly.
|
||||
const sortColumns = {
|
||||
id: 'id',
|
||||
name: `name_${determinedLanguage}`,
|
||||
status: 'status',
|
||||
timeCreated: 'time_created',
|
||||
timeModified: 'time_modified'
|
||||
}
|
||||
const sortColumn = sortColumns[sortBy] || 'id'
|
||||
const direction = sortDir === 'asc' ? 'ASC' : 'DESC'
|
||||
|
||||
// A category left unselected must be passed as null (not []) so the
|
||||
// "$n::type[] IS NULL" branch short-circuits it as "no filter" - an
|
||||
// empty array would instead match zero rows via "= ANY('{}')".
|
||||
const {
|
||||
nameQuery = '',
|
||||
primaryDomainIds = null,
|
||||
secondaryDomainIds = null,
|
||||
languageIds = null,
|
||||
statuses = null
|
||||
} = filters
|
||||
|
||||
// Escaped so literal %/_ in a search term (e.g. a dictionary named
|
||||
// "100%") are matched as themselves, not as LIKE wildcards - see
|
||||
// escapeLikePattern in models/helpers/index.js for wildcard-search notes.
|
||||
const escapedNameQuery = escapeLikePattern(nameQuery)
|
||||
|
||||
const whereClause = `
|
||||
WHERE count_comments IS NOT NULL
|
||||
AND ($3 = '' OR LOWER(name_${determinedLanguage}) LIKE '%' || LOWER($3) || '%')
|
||||
AND ($4::smallint[] IS NULL OR domain_primary_id = ANY($4::smallint[]))
|
||||
AND ($5::dictionary_status[] IS NULL OR status = ANY($5::dictionary_status[]))
|
||||
AND ($6::smallint[] IS NULL OR EXISTS (
|
||||
SELECT 1 FROM dictionary_domain_secondary dds
|
||||
WHERE dds.dictionary_id = dictionary.id AND dds.domain_secondary_id = ANY($6::smallint[])
|
||||
))
|
||||
AND ($7::smallint[] IS NULL OR EXISTS (
|
||||
SELECT 1 FROM dictionary_language dl
|
||||
WHERE dl.dictionary_id = dictionary.id AND dl.language_id = ANY($7::smallint[])
|
||||
))`
|
||||
|
||||
const {
|
||||
rows: [{ result }]
|
||||
} = await db.query(
|
||||
@@ -826,6 +877,7 @@ class Dictionary {
|
||||
'pages_total', (
|
||||
SELECT CEIL(COUNT(*) / $1::float)
|
||||
FROM dictionary
|
||||
${whereClause}
|
||||
),
|
||||
'results', ARRAY(
|
||||
SELECT jsonb_build_object(
|
||||
@@ -836,12 +888,21 @@ class Dictionary {
|
||||
'status', status
|
||||
)
|
||||
FROM dictionary
|
||||
WHERE count_comments IS NOT NULL
|
||||
${whereClause}
|
||||
ORDER BY ${sortColumn} ${direction}, id ${direction}
|
||||
LIMIT $1
|
||||
OFFSET $2
|
||||
)
|
||||
) result`,
|
||||
[resultsPerPage, resultsPerPage * (page - 1)]
|
||||
[
|
||||
resultsPerPage,
|
||||
resultsPerPage * (page - 1),
|
||||
escapedNameQuery,
|
||||
primaryDomainIds,
|
||||
statuses,
|
||||
secondaryDomainIds,
|
||||
languageIds
|
||||
]
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -959,7 +1020,31 @@ class Dictionary {
|
||||
delete_existing_entries,
|
||||
file_format
|
||||
)
|
||||
VALUES ($1, $2, $3)`
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id`
|
||||
|
||||
const {
|
||||
rows: [{ id }]
|
||||
} = await db.query(text, values)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
// Update import file job in DB with its final status and entry counts.
|
||||
static async closeImportFileJob(
|
||||
jobId,
|
||||
status,
|
||||
countValidEntries,
|
||||
countInvalidEntries
|
||||
) {
|
||||
const values = [jobId, status, countValidEntries, countInvalidEntries]
|
||||
const text = `
|
||||
UPDATE import_file_job
|
||||
SET
|
||||
status = $2,
|
||||
count_valid_entries = $3,
|
||||
count_invalid_entries = $4
|
||||
WHERE id = $1`
|
||||
|
||||
await db.query(text, values)
|
||||
}
|
||||
@@ -969,20 +1054,30 @@ class Dictionary {
|
||||
userId,
|
||||
dictionaryId,
|
||||
importFilePath,
|
||||
entryStatus
|
||||
entryStatus,
|
||||
importFileFormat
|
||||
) {
|
||||
const dbClient = await db.getClient()
|
||||
try {
|
||||
await dbClient.query('BEGIN')
|
||||
await readFileIntoDb(
|
||||
userId,
|
||||
dictionaryId,
|
||||
importFilePath,
|
||||
entryStatus,
|
||||
dbClient
|
||||
)
|
||||
const { totalCount, validCount } =
|
||||
importFileFormat === 'json_term_candidates'
|
||||
? await readJsonFileIntoDb(
|
||||
userId,
|
||||
dictionaryId,
|
||||
importFilePath,
|
||||
dbClient
|
||||
)
|
||||
: await readFileIntoDb(
|
||||
userId,
|
||||
dictionaryId,
|
||||
importFilePath,
|
||||
entryStatus,
|
||||
dbClient
|
||||
)
|
||||
await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient)
|
||||
await dbClient.query('COMMIT')
|
||||
return { totalCount, validCount }
|
||||
} catch (error) {
|
||||
await dbClient.query('ROLLBACK')
|
||||
throw error
|
||||
@@ -999,31 +1094,7 @@ class Dictionary {
|
||||
kanonicnaoblika: term,
|
||||
definicija: other
|
||||
} of termCandidates) {
|
||||
const values = [
|
||||
dictionaryId,
|
||||
false,
|
||||
'suggestion',
|
||||
term || null,
|
||||
userId,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
[],
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
[],
|
||||
other || null,
|
||||
[],
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
|
||||
const text = `SELECT entry_new (${db.genParamStr(values)})`
|
||||
|
||||
await dbClient.query(text, values)
|
||||
await insertSuggestionEntry(dbClient, dictionaryId, userId, term, other)
|
||||
}
|
||||
|
||||
await this.updateMetadataAfterModifyingEntries(dictionaryId, dbClient)
|
||||
@@ -1214,6 +1285,10 @@ class Dictionary {
|
||||
resultsPerPage,
|
||||
page
|
||||
) {
|
||||
// Escaped so literal %/_ in a search term are matched as themselves,
|
||||
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
|
||||
const escapedQuery = escapeLikePattern(query)
|
||||
|
||||
const {
|
||||
rows: [{ result }]
|
||||
} = await db.query(
|
||||
@@ -1237,7 +1312,7 @@ class Dictionary {
|
||||
OFFSET $4
|
||||
)
|
||||
) result`,
|
||||
[dictionaryId, query, resultsPerPage, resultsPerPage * (page - 1)]
|
||||
[dictionaryId, escapedQuery, resultsPerPage, resultsPerPage * (page - 1)]
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -1275,6 +1350,10 @@ class Dictionary {
|
||||
|
||||
// Fetch filtered secondary domains from DB.
|
||||
static async fetchFilteredSecondaryDomains(query, resultsPerPage, page) {
|
||||
// Escaped so literal %/_ in a search term are matched as themselves,
|
||||
// not as LIKE wildcards - see escapeLikePattern in models/helpers/index.js.
|
||||
const escapedQuery = escapeLikePattern(query)
|
||||
|
||||
const {
|
||||
rows: [{ result }]
|
||||
} = await db.query(
|
||||
@@ -1299,7 +1378,7 @@ class Dictionary {
|
||||
OFFSET $3
|
||||
)
|
||||
) result`,
|
||||
[query, resultsPerPage, resultsPerPage * (page - 1)]
|
||||
[escapedQuery, resultsPerPage, resultsPerPage * (page - 1)]
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -1501,10 +1580,11 @@ class Dictionary {
|
||||
'status', status,
|
||||
'delete_existing_entries', delete_existing_entries,
|
||||
'file_format', file_format,
|
||||
'count_valid_entries', count_valid_entries
|
||||
'count_entries', count_valid_entries + count_invalid_entries
|
||||
)
|
||||
FROM import_file_job
|
||||
WHERE dictionary_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT $2
|
||||
OFFSET $3
|
||||
)
|
||||
@@ -1572,6 +1652,7 @@ class Dictionary {
|
||||
)
|
||||
FROM dictionary_export
|
||||
WHERE dictionary_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT $2
|
||||
OFFSET $3
|
||||
)
|
||||
@@ -1590,9 +1671,10 @@ class Dictionary {
|
||||
is_terminology_reviewed_filter,
|
||||
is_language_reviewed_filter,
|
||||
status_filter,
|
||||
export_file_format
|
||||
export_file_format,
|
||||
time_zone
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
@@ -1603,7 +1685,8 @@ class Dictionary {
|
||||
exportParams.isTerminologyReviewedFilter,
|
||||
exportParams.isLanguageReviewedFilter,
|
||||
exportParams.statusFilter,
|
||||
exportParams.exportFileFormat
|
||||
exportParams.exportFileFormat,
|
||||
exportParams.timeZone
|
||||
]
|
||||
|
||||
const {
|
||||
@@ -1613,6 +1696,13 @@ class Dictionary {
|
||||
return id
|
||||
}
|
||||
|
||||
static async deleteExport(dictionaryId, exportId) {
|
||||
await db.query(
|
||||
'DELETE FROM dictionary_export WHERE id = $1 AND dictionary_id = $2',
|
||||
[exportId, dictionaryId]
|
||||
)
|
||||
}
|
||||
|
||||
static async processExport(exportId) {
|
||||
const dbClient = await db.getClient()
|
||||
let exportFilePath
|
||||
@@ -1631,7 +1721,8 @@ class Dictionary {
|
||||
is_terminology_reviewed_filter,
|
||||
is_language_reviewed_filter,
|
||||
status_filter,
|
||||
export_file_format
|
||||
export_file_format,
|
||||
COALESCE(time_zone, 'UTC') time_zone
|
||||
`
|
||||
|
||||
const exportQueryParams = [exportId]
|
||||
@@ -1645,7 +1736,8 @@ class Dictionary {
|
||||
is_terminology_reviewed_filter: isTerminologyReviewedFilter,
|
||||
is_language_reviewed_filter: isLanguageReviewedFilter,
|
||||
status_filter: statusFilter,
|
||||
export_file_format: exportFileFormat
|
||||
export_file_format: exportFileFormat,
|
||||
time_zone: timeZone
|
||||
}
|
||||
]
|
||||
} = await dbClient.query(exportQueryText, exportQueryParams)
|
||||
@@ -1865,17 +1957,17 @@ class Dictionary {
|
||||
name_sl,
|
||||
name_en,
|
||||
author,
|
||||
to_char(time_modified, 'YYYY-MM-DD') modified_date_string,
|
||||
to_char(time_modified AT TIME ZONE $3, 'YYYY-MM-DD') modified_date_string,
|
||||
status,
|
||||
(
|
||||
SELECT to_char(time_created, 'YYYY-MM-DD')
|
||||
SELECT to_char(time_created AT TIME ZONE $3, 'YYYY-MM-DD')
|
||||
FROM dictionary_export de
|
||||
WHERE de.id = $1
|
||||
) export_date_string
|
||||
FROM dictionary
|
||||
WHERE id = $2
|
||||
`,
|
||||
[exportId, dictionaryId]
|
||||
[exportId, dictionaryId, timeZone]
|
||||
)
|
||||
const portalName = await getInstanceSetting('portal_name_sl')
|
||||
const authorsString = tbxMetadata.author?.join(', ')
|
||||
@@ -1947,7 +2039,9 @@ class Dictionary {
|
||||
"UPDATE dictionary_export SET status = 'failed', time_finished = NOW() WHERE id = $1",
|
||||
[exportId]
|
||||
)
|
||||
await unlink(exportFilePath)
|
||||
if (exportFilePath) {
|
||||
await unlink(exportFilePath).catch(() => {})
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
dbClient.release()
|
||||
@@ -1964,7 +2058,7 @@ class Dictionary {
|
||||
e.status,
|
||||
e.dictionary_id,
|
||||
d.name_sl_short name_string,
|
||||
to_char(e.time_created, 'YYYYMMDDHH24MISS') time_string,
|
||||
to_char(e.time_created AT TIME ZONE COALESCE(e.time_zone, 'UTC'), 'YYYYMMDDHH24MISS') time_string,
|
||||
e.export_file_format
|
||||
FROM dictionary_export e
|
||||
LEFT JOIN dictionary d ON d.id = e.dictionary_id
|
||||
|
||||
@@ -140,6 +140,7 @@ Entry.fetchFull = async entryId => {
|
||||
)
|
||||
FROM entry_version_history
|
||||
WHERE entry_id = e.id
|
||||
ORDER BY version
|
||||
)
|
||||
)
|
||||
) entry
|
||||
@@ -223,6 +224,7 @@ Entry.fetchFullWithOrderedForeignLanguages = async entryId => {
|
||||
)
|
||||
FROM entry_version_history
|
||||
WHERE entry_id = e.id
|
||||
ORDER BY version
|
||||
)
|
||||
)
|
||||
) entry
|
||||
|
||||
@@ -14,6 +14,9 @@ const {
|
||||
} = require('./helpers/extraction')
|
||||
const { extractionApiOrigin } = require('../config/keys')
|
||||
|
||||
// Upper limit for each concordancer status-polling loop in Extraction.processOwn.
|
||||
const CONCORDANCER_POLL_TIMEOUT_SECONDS = 5 * 60
|
||||
|
||||
const Extraction = {}
|
||||
|
||||
// Fetch all extractions for a specific user.
|
||||
@@ -434,19 +437,12 @@ Extraction.processOwn = async function (extractionId, extractionName) {
|
||||
])
|
||||
|
||||
// Wait for creation of corpus.
|
||||
while (true) {
|
||||
console.log('SLEEP FOR 5 SECS')
|
||||
await sleep(5)
|
||||
const {
|
||||
data: { status }
|
||||
} = await axios.get(
|
||||
`http://concordancer:5000/dashboard/corpus/${corpusId}`
|
||||
)
|
||||
|
||||
if (status === 'Creating') continue
|
||||
if (status === 'Active') break
|
||||
throw Error('Error creating concorcander corpus')
|
||||
}
|
||||
await pollConcordancerStatus({
|
||||
url: `http://concordancer:5000/dashboard/corpus/${corpusId}`,
|
||||
inProgressStatuses: ['Creating'],
|
||||
label: `corpus ${corpusId}`,
|
||||
errorMessage: 'Error creating concorcander corpus'
|
||||
})
|
||||
console.log('CORPUS CREATED')
|
||||
|
||||
const inProgressStatusList = [
|
||||
@@ -471,19 +467,12 @@ Extraction.processOwn = async function (extractionId, extractionName) {
|
||||
)
|
||||
|
||||
// Wait for text ingestion.
|
||||
while (true) {
|
||||
console.log('SLEEP FOR 5 SECS')
|
||||
await sleep(5)
|
||||
const {
|
||||
data: { status }
|
||||
} = await axios.get(
|
||||
`http://concordancer:5000/dashboard/corpus/${corpusId}/text/${textId}`
|
||||
)
|
||||
|
||||
if (inProgressStatusList.includes(status)) continue
|
||||
if (status === 'Active') break
|
||||
throw Error('Error importing concorcander text')
|
||||
}
|
||||
await pollConcordancerStatus({
|
||||
url: `http://concordancer:5000/dashboard/corpus/${corpusId}/text/${textId}`,
|
||||
inProgressStatuses: inProgressStatusList,
|
||||
label: `text ${textId}`,
|
||||
errorMessage: 'Error importing concorcander text'
|
||||
})
|
||||
console.log('TEXT ADDED')
|
||||
}
|
||||
|
||||
@@ -501,19 +490,12 @@ Extraction.processOwn = async function (extractionId, extractionName) {
|
||||
)
|
||||
|
||||
// Wait for term list ingestion.
|
||||
while (true) {
|
||||
console.log('SLEEP FOR 5 SECS')
|
||||
await sleep(5)
|
||||
const {
|
||||
data: { status }
|
||||
} = await axios.get(
|
||||
`http://concordancer:5000/dashboard/corpus/${corpusId}/termList/${termListId}`
|
||||
)
|
||||
|
||||
if (inProgressStatusList.includes(status)) continue
|
||||
if (status === 'Active') break
|
||||
throw Error('Error importing concorcander text')
|
||||
}
|
||||
await pollConcordancerStatus({
|
||||
url: `http://concordancer:5000/dashboard/corpus/${corpusId}/termList/${termListId}`,
|
||||
inProgressStatuses: inProgressStatusList,
|
||||
label: `termList ${termListId}`,
|
||||
errorMessage: 'Error importing concorcander term list'
|
||||
})
|
||||
console.log('TERMS ADDED')
|
||||
|
||||
await db.query(
|
||||
@@ -654,6 +636,52 @@ function sleep(seconds) {
|
||||
return new Promise(resolve => setTimeout(resolve, seconds * 1000))
|
||||
}
|
||||
|
||||
// Polls a concordancer status endpoint every 5 seconds until it reports
|
||||
// 'Active', up to CONCORDANCER_POLL_TIMEOUT_SECONDS in total. The
|
||||
// concordancer can return HTTP 500 (XForbiddenException, thrown by its
|
||||
// CurrentContextInitializationDecorator) from these GET endpoints while
|
||||
// the entity isn't 'Active' yet, which is indistinguishable from "still
|
||||
// in progress", so a 500 is treated as such and the loop keeps retrying
|
||||
// until either the entity becomes 'Active' or the upper time limit is
|
||||
// reached.
|
||||
async function pollConcordancerStatus({
|
||||
url,
|
||||
inProgressStatuses,
|
||||
label,
|
||||
errorMessage
|
||||
}) {
|
||||
const startTime = Date.now()
|
||||
let attempt = 0
|
||||
/* eslint-disable no-console */
|
||||
while (true) {
|
||||
const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000)
|
||||
const remainingSeconds = CONCORDANCER_POLL_TIMEOUT_SECONDS - elapsedSeconds
|
||||
if (remainingSeconds <= 0) {
|
||||
throw Error(
|
||||
`Timed out polling ${label} after ${attempt} attempt(s) and ${elapsedSeconds}s (limit: ${CONCORDANCER_POLL_TIMEOUT_SECONDS}s)`
|
||||
)
|
||||
}
|
||||
attempt++
|
||||
console.log(
|
||||
`Polling ${label}: attempt ${attempt}, ${remainingSeconds}s left until timeout`
|
||||
)
|
||||
await sleep(5)
|
||||
let status
|
||||
try {
|
||||
;({
|
||||
data: { status }
|
||||
} = await axios.get(url))
|
||||
} catch (error) {
|
||||
if (error.response?.status === 500) continue
|
||||
throw error
|
||||
}
|
||||
if (inProgressStatuses.includes(status)) continue
|
||||
if (status === 'Active') return
|
||||
throw Error(errorMessage)
|
||||
}
|
||||
/* eslint-enable no-console */
|
||||
}
|
||||
|
||||
function logExtractionError(error, extractionId, jobType, filename) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
|
||||
@@ -193,7 +193,10 @@ function handleEntryXml(
|
||||
) {
|
||||
debug(`TOTAL ENTRIES: ${progress.totalCount}`)
|
||||
debug(`VALID ENTRIES: ${progress.validCount}`)
|
||||
resolve()
|
||||
resolve({
|
||||
totalCount: progress.totalCount,
|
||||
validCount: progress.validCount
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
const { readFile } = require('fs/promises')
|
||||
const { insertSuggestionEntry } = require('./index')
|
||||
|
||||
// Import given JSON export of extraction term candidates into given dictionary.
|
||||
exports.readJsonFileIntoDb = async (
|
||||
userId,
|
||||
dictionaryId,
|
||||
importFilePath,
|
||||
dbClient
|
||||
) => {
|
||||
const fileContent = await readFile(importFilePath, 'utf8')
|
||||
const { terminoloski_kandidati: termCandidates } = JSON.parse(fileContent)
|
||||
|
||||
if (!Array.isArray(termCandidates)) {
|
||||
throw Error('Invalid term candidates JSON: terminoloski_kandidati is not an array')
|
||||
}
|
||||
|
||||
for (const {
|
||||
kanonicnaoblika: term,
|
||||
definicija: other
|
||||
} of termCandidates) {
|
||||
await insertSuggestionEntry(dbClient, dictionaryId, userId, term, other)
|
||||
}
|
||||
|
||||
return { totalCount: termCandidates.length, validCount: 0 }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
const xss = require('xss')
|
||||
const db = require('../../db')
|
||||
const { removeHtmlTags } = require('../../helpers')
|
||||
const { searchEngineClient, ENTRY_INDEX } = require('../../search-engine')
|
||||
const { DATA_FILES_PATH } = require('../../../config/settings')
|
||||
@@ -353,3 +354,35 @@ exports.sanitizeField = {
|
||||
return sanitize(string, markupFilter.mixedOther)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert a single 'suggestion' status entry (as produced by extraction term
|
||||
// candidates, whether imported directly or from a JSON export of them).
|
||||
exports.insertSuggestionEntry = async (dbClient, dictionaryId, userId, term, other) => {
|
||||
term = term ? exports.sanitizeField.toText(term) : null
|
||||
other = other ? exports.sanitizeField.toText(other) : null
|
||||
|
||||
const values = [
|
||||
dictionaryId,
|
||||
false,
|
||||
'suggestion',
|
||||
term || null,
|
||||
userId,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
[],
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
[],
|
||||
other || null,
|
||||
[],
|
||||
null,
|
||||
null,
|
||||
null
|
||||
]
|
||||
const text = `SELECT entry_new (${db.genParamStr(values)})`
|
||||
|
||||
await dbClient.query(text, values)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,19 @@ exports.removeHtmlTags = text => {
|
||||
return tagFilter.process(text)
|
||||
}
|
||||
|
||||
// Escapes Postgres LIKE metacharacters (\, %, _) in a raw search string so
|
||||
// it's matched literally rather than as a LIKE pattern - e.g. a user
|
||||
// searching for a dictionary literally named "100%" gets that dictionary,
|
||||
// not every dictionary. Backslash must be escaped first, or the escapes
|
||||
// added for % and _ below would themselves get re-escaped.
|
||||
//
|
||||
// Wildcard search (*, ?), if ever added: translate user-facing '*' -> '%'
|
||||
// and '?' -> '_' AFTER calling this function, on its return value - that
|
||||
// way literal %, _, and \ in the search text stay literal while the
|
||||
// user's own * and ? become real SQL wildcards.
|
||||
exports.escapeLikePattern = value =>
|
||||
value.replace(/\\/g, '\\\\').replace(/%/g, '\\%').replace(/_/g, '\\_')
|
||||
|
||||
// Returns setting value by its name from table instance_settings.
|
||||
exports.getInstanceSetting = async settingName => {
|
||||
const settingCacheName = `${INSTANCE_SETTING_NAMESPACE}:${settingName}`
|
||||
|
||||
@@ -9,6 +9,7 @@ exports.deserialize = {
|
||||
status: user.status,
|
||||
hitsPerPage: user.hits_per_page,
|
||||
language: user.language,
|
||||
isSso: user.is_sso,
|
||||
userRoles: user.user_roles,
|
||||
assignedConsultancyEntries: user.assigned_consultancy_entries
|
||||
}
|
||||
@@ -34,7 +35,10 @@ exports.deserialize = {
|
||||
const deserializedRights = {
|
||||
id: userData.id,
|
||||
userName: userData.username,
|
||||
firstName: userData.first_name,
|
||||
lastName: userData.last_name,
|
||||
email: userData.email,
|
||||
language: userData.language,
|
||||
hasAdministration: userData.administration,
|
||||
hasEditing: userData.editing,
|
||||
hasTerminologyReview: userData.terminology_review,
|
||||
|
||||
+170
-3
@@ -26,6 +26,135 @@ User.isEmailAlreadyTaken = async email => {
|
||||
return isTaken
|
||||
}
|
||||
|
||||
// Check if a user with provided username already exists, optionally excluding one user id (used
|
||||
// when re-checking a username against its own current owner, e.g. during account conversion).
|
||||
User.isUsernameAlreadyTaken = async (username, excludeUserId) => {
|
||||
const { rows } = await db.query(
|
||||
`SELECT 1 FROM "user" WHERE username = $1 ${
|
||||
excludeUserId ? 'AND id <> $2' : ''
|
||||
}`,
|
||||
excludeUserId ? [username, excludeUserId] : [username]
|
||||
)
|
||||
|
||||
return rows.length > 0
|
||||
}
|
||||
|
||||
// Fetch the active user linked to a given external identity (auth_provider, subject), if any.
|
||||
User.fetchByExternalIdentity = async (authProvider, subject) => {
|
||||
const {
|
||||
rows: [user]
|
||||
} = await db.query(
|
||||
`SELECT u.id, u.status
|
||||
FROM user_external_identity uei
|
||||
JOIN "user" u ON u.id = uei.user_id
|
||||
WHERE uei.auth_provider = $1 AND uei.subject = $2`,
|
||||
[authProvider, subject]
|
||||
)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
// Fetch an active local user by email. Used to detect whether an SSO login's email claim
|
||||
// matches an existing local account, for the account-linking flow.
|
||||
User.fetchActiveByEmail = async email => {
|
||||
const {
|
||||
rows: [user]
|
||||
} = await db.query('SELECT id FROM "user" WHERE email = $1 AND status = $2', [
|
||||
email,
|
||||
'active'
|
||||
])
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
// Atomically create a brand-new SSO-only user (no bcrypt_hash) and link it to the given external
|
||||
// identity. Used the first time someone signs in via an external IdP with no matching account.
|
||||
User.createFromExternalIdentity = async (authProvider, subject, profile, t) => {
|
||||
let userId
|
||||
|
||||
await db.transaction(async dbClient => {
|
||||
if (await User.isEmailAlreadyTaken(profile.email)) {
|
||||
const err = Error(t('Elektronski naslov uporablja že drug uporabnik.'))
|
||||
err.status = 400
|
||||
err.displayInProd = true
|
||||
throw err
|
||||
}
|
||||
|
||||
if (await User.isUsernameAlreadyTaken(profile.username)) {
|
||||
const err = Error(
|
||||
t('Izbrano uporabniško ime uporablja že drug uporabnik.')
|
||||
)
|
||||
err.status = 400
|
||||
err.displayInProd = true
|
||||
throw err
|
||||
}
|
||||
|
||||
const values = [
|
||||
profile.username,
|
||||
profile.firstName,
|
||||
profile.lastName,
|
||||
profile.email
|
||||
]
|
||||
if (profile.language) values.push(profile.language)
|
||||
|
||||
// bcrypt_hash/status/time_activated are appended as fixed literals (not bound params) after
|
||||
// the dynamic column list, on both the column-list and VALUES-tuple side, so the two stay
|
||||
// positionally aligned regardless of whether the optional `language` column is included.
|
||||
const {
|
||||
rows: [user]
|
||||
} = await dbClient.query(
|
||||
`INSERT INTO "user" (
|
||||
username, first_name, last_name, email ${
|
||||
profile.language ? ', language' : ''
|
||||
},
|
||||
bcrypt_hash, status, time_activated
|
||||
)
|
||||
VALUES (${db.genParamStr(values)}, NULL, 'active', NOW())
|
||||
RETURNING id`,
|
||||
values
|
||||
)
|
||||
|
||||
userId = user.id
|
||||
|
||||
await dbClient.query(
|
||||
'INSERT INTO user_external_identity (auth_provider, subject, user_id) VALUES ($1, $2, $3)',
|
||||
[authProvider, subject, userId]
|
||||
)
|
||||
})
|
||||
|
||||
return userId
|
||||
}
|
||||
|
||||
// Permanently convert an existing local user into an SSO-only user: overwrite its
|
||||
// username/first/last name with the IdP-derived profile, remove its local password (from then on
|
||||
// it can only sign in via this external identity, exactly like a user created straight from the
|
||||
// IdP via createFromExternalIdentity), and link the external identity. Used once the user has
|
||||
// confirmed ownership of the matched local account (its password).
|
||||
User.convertToExternalIdentity = async (authProvider, subject, userId, profile, t) => {
|
||||
await db.transaction(async dbClient => {
|
||||
if (await User.isUsernameAlreadyTaken(profile.username, userId)) {
|
||||
const err = Error(
|
||||
t('Izbrano uporabniško ime uporablja že drug uporabnik.')
|
||||
)
|
||||
err.status = 400
|
||||
err.displayInProd = true
|
||||
throw err
|
||||
}
|
||||
|
||||
await dbClient.query(
|
||||
`UPDATE "user"
|
||||
SET username = $1, first_name = $2, last_name = $3, bcrypt_hash = NULL
|
||||
WHERE id = $4`,
|
||||
[profile.username, profile.firstName, profile.lastName, userId]
|
||||
)
|
||||
|
||||
await dbClient.query(
|
||||
'INSERT INTO user_external_identity (auth_provider, subject, user_id) VALUES ($1, $2, $3)',
|
||||
[authProvider, subject, userId]
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Create new user in DB.
|
||||
User.create = async (user, t) => {
|
||||
const {
|
||||
@@ -208,10 +337,25 @@ User.resetPasswordWithToken = async (token, password, t) => {
|
||||
;({
|
||||
rows: [user]
|
||||
} = await dbClient.query(
|
||||
'UPDATE "user" SET bcrypt_hash = $1 WHERE id = $2 RETURNING id, username, email',
|
||||
// Only ever overwrites an EXISTING local password - never sets an initial one for an
|
||||
// SSO-only account (bcrypt_hash IS NULL). Also guarded earlier, at token-issuance time
|
||||
// (generateResetPasswordToken); this is defense in depth for any already-issued token.
|
||||
`UPDATE "user" SET bcrypt_hash = $1 WHERE id = $2 AND bcrypt_hash IS NOT NULL RETURNING id, username, email`,
|
||||
[bcryptHash, userId]
|
||||
))
|
||||
|
||||
if (!user) {
|
||||
const err = Error(
|
||||
t(
|
||||
'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.'
|
||||
)
|
||||
)
|
||||
err.status = 403
|
||||
err.displayInProd = true
|
||||
|
||||
throw err
|
||||
}
|
||||
|
||||
await dbClient.query(
|
||||
'DELETE FROM user_token_reset_password WHERE token = $1',
|
||||
[token]
|
||||
@@ -298,6 +442,7 @@ User.fetchDeserializedDataById = async userId => {
|
||||
u.status,
|
||||
u.hits_per_page,
|
||||
u.language,
|
||||
u.bcrypt_hash IS NULL AS is_sso,
|
||||
ARRAY(
|
||||
SELECT jsonb_build_object(
|
||||
'roleName', r.role_name,
|
||||
@@ -540,7 +685,8 @@ User.fetchUserRoles = async userId => {
|
||||
|
||||
User.fetchAllWithDictionaryRights = async dictionaryId => {
|
||||
const text = `
|
||||
SELECT u.username,u.email, u.id, r.administration, r.editing, r.terminology_review, r.language_review
|
||||
SELECT u.username, u.email, u.id, u.first_name, u.last_name, u.language,
|
||||
r.administration, r.editing, r.terminology_review, r.language_review
|
||||
FROM user_role r
|
||||
INNER JOIN "user" u ON u.id = r.user_id
|
||||
WHERE dictionary_id = $1
|
||||
@@ -711,6 +857,18 @@ User.changePassword = async (userId, passwordOld, passwordNew, t) => {
|
||||
userId
|
||||
])
|
||||
|
||||
if (!bcryptHashOld) {
|
||||
const err = Error(
|
||||
t(
|
||||
'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani in nima gesla. Prijavite se prek gumba za prijavo z Univerzo v Ljubljani.'
|
||||
)
|
||||
)
|
||||
err.status = 403
|
||||
err.displayInProd = true
|
||||
|
||||
throw err
|
||||
}
|
||||
|
||||
const isOldPasswordCorrect = await bcrypt.compare(
|
||||
passwordOld,
|
||||
bcryptHashOld
|
||||
@@ -753,6 +911,7 @@ User.closeAccount = async userId => {
|
||||
first_name = $2,
|
||||
last_name = $3,
|
||||
email = $4,
|
||||
bcrypt_hash = NULL,
|
||||
status = 'closed',
|
||||
time_closed = NOW()
|
||||
WHERE id = $5`,
|
||||
@@ -776,7 +935,15 @@ User.closeAccount = async userId => {
|
||||
),
|
||||
dbClient.query('DELETE FROM user_token_change_email WHERE user_id = $1', [
|
||||
userId
|
||||
])
|
||||
]),
|
||||
dbClient.query('DELETE FROM user_external_identity WHERE user_id = $1', [
|
||||
userId
|
||||
]),
|
||||
dbClient.query('DELETE FROM user_role WHERE user_id = $1', [userId]),
|
||||
dbClient.query(
|
||||
'DELETE FROM consultancy_entry_consultant WHERE user_id = $1',
|
||||
[userId]
|
||||
)
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user