CJVT updates August and September 2026

This commit is contained in:
Luka Romih
2026-10-01 00:49:26 +02:00
parent fd02e25719
commit 83f73aeb58
135 changed files with 6146 additions and 1970 deletions
@@ -499,15 +499,6 @@ async function consultancyRequestItems(
}
}
if (entry.timeCreated) {
// TODO i18n date format
const date = new Date(entry.timeCreated)
entry.formattedTimeCreated = `${date.getDate()}. ${
date.getMonth() + 1
}. ${date.getFullYear()}`
}
return entry
})
+84 -3
View File
@@ -1,8 +1,11 @@
const { rm } = require('fs/promises')
const { promisify } = require('util')
const user = require('../../../middleware/user')
const Dictionary = require('../../../models/dictionary')
const User = require('../../../models/user')
const Entry = require('../../../models/entry')
const Extraction = require('../../../models/extraction')
const email = require('../../../models/email')
const {
searchEntryIndex,
deleteEntryFromIndex,
@@ -11,11 +14,28 @@ const {
const genEditorAllQuery = require('../../../models/helpers/search/generate-query/editor/all')
const { prepareEditorEntries } = require('../../../models/helpers/search')
const { DEFAULT_HITS_PER_PAGE } = require('../../../config/settings')
const { minEntriesRequirementCheckAndAct } = require('../../helpers/dictionary')
const {
minEntriesRequirementCheckAndAct,
resolveDictionarySort,
parseDictionaryListFilters
} = require('../../helpers/dictionary')
const { getExportFilesPath } = require('../../../models/helpers/dictionary')
const dictionary = {}
dictionary.checkNameCollision = async (req, res) => {
const { nameSl, nameSlShort, nameEn, excludeDictionaryId } = req.query
const collision = await Dictionary.checkNameCollision({
nameSl: nameSl || null,
nameSlShort: nameSlShort || null,
nameEn: nameEn || null,
excludeDictionaryId: excludeDictionaryId || null
})
res.send({ collision })
}
dictionary.getEntry = async (req, res) => {
const entryId = req.query.id
const [entry, domainLabels] = await Promise.all([
@@ -133,6 +153,16 @@ dictionary.delete = async (req, res) => {
res.end()
}
dictionary.deleteExport = async (req, res) => {
const dictionaryId = +req.params.dictionaryId
const exportId = +req.params.exportId
await Dictionary.deleteExport(dictionaryId, exportId)
const exportFilePath = `${getExportFilesPath(dictionaryId)}/${exportId}`
await rm(exportFilePath, { force: true })
res.end()
}
dictionary.updateDomainLabels = [
(req, res, next) => {
req.dictionaryId = req.body.params.dictionaryId
@@ -166,17 +196,65 @@ dictionary.listDictionaries = async (req, res) => {
const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE
const page = +req.query.p > 0 ? +req.query.p : 1
const { sortBy, sortDir } = resolveDictionarySort(
req.query.sort,
req.query.dir
)
const filters = parseDictionaryListFilters(req.query)
const { pages_total: numberOfAllPages, results } =
await Dictionary.fetchAllAdminDictionaries(
req.determinedLanguage,
resultsPerPage,
page
page,
sortBy,
sortDir,
filters
)
res.send({ page, numberOfAllPages, results })
}
dictionary.contactDictionaryAuthors = async (req, res) => {
const { dictionaryId } = req.params
const { message } = req.body
const [name, recipients] = await Promise.all([
Dictionary.fetchName(dictionaryId, req.determinedLanguage),
User.fetchAllWithDictionaryRights(dictionaryId)
])
const renderAsync = promisify(req.app.render.bind(req.app))
const senderName = `${req.user.firstName} ${req.user.lastName}`
const emailSubject = req.t('Sporočilo o slovarju "{{name}}"', { name })
await Promise.all(
recipients.map(async recipient => {
const emailHtml = await renderAsync(
`email/dictionary-contact-authors_${recipient.language}`,
{
senderName,
senderEmail: req.user.email,
dictionaryName: name,
message
}
)
await email.send({
to: recipient.email,
subject: emailSubject,
html: emailHtml,
replyTo: req.user.email
})
})
)
// eslint-disable-next-line no-console
console.log(
`Sent email to ${recipients.map(r => r.email)} (subject: ${emailSubject})`
)
res.status(201).send()
}
dictionary.listDomainLabels = async (req, res) => {
const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE
const { dictionaryId } = req.params
@@ -312,7 +390,10 @@ dictionary.exportBegin = async (req, res) => {
req.body.isLanguageReviewedFilter === 'on'
? undefined
: req.body.isLanguageReviewedFilter,
exportFileFormat: req.body.exportFileFormat
exportFileFormat: req.body.exportFileFormat,
timeZone: Intl.supportedValuesOf('timeZone').includes(req.body.timeZone)
? req.body.timeZone
: 'UTC'
}
const exportId = await Dictionary.beginExport(dictionaryId, exportParams)
+17
View File
@@ -34,6 +34,17 @@ users.updateHitsPerPage = async (req, res) => {
}
users.updateBasicData = async (req, res) => {
if (req.user.isSso) {
const err = Error(
req.t(
'Ta uporabniški račun je bil ustvarjen prek prijave z Univerzo v Ljubljani, zato osebnih podatkov ni mogoče spreminjati na portalu.'
)
)
err.status = 403
err.displayInProd = true
throw err
}
const { firstName, lastName, email: newEmail } = req.body
// TODO Validation (valid email format, ...).
@@ -121,6 +132,12 @@ users.updatePassword = async (req, res) => {
}
users.deleteCurrent = [
// TODO This permanently anonymizes/closes the account with no re-authentication step - the
// client-side confirmation modal (public/javascripts/profile-scripts.js) is the only gate, and
// it's identical for local and SSO accounts (no password re-entry, no IdP reauth). Anyone with
// an active/hijacked session (e.g. an unattended logged-in browser) can delete the account
// outright. Consider requiring password re-entry for local accounts, and an equivalent reauth
// step for SSO accounts, before calling closeAccount.
async (req, res, next) => {
await User.closeAccount(req.user.id)
next()
+16 -12
View File
@@ -181,11 +181,19 @@ consultancyAdmin.statistics = async (req, res) => {
res.render('pages/consultancy/admin/statistics')
}
// Maps a consultancy entry's status to the sidebar item it should highlight
// and the URL slug that list page lives at (used as a fallback "back" link
// target when the page wasn't reached via that list page's own link).
const STATUS_META = {
new: { new: true, slug: 'novo' },
rejected: { rejected: true, slug: 'zavrnjeno' },
'in progress': { inProgress: true, slug: 'v-delu' },
review: { prepared: true, slug: 'pripravljeno' },
published: { published: true, slug: 'objavljeno' }
}
consultancyAdmin.edit = async (req, res) => {
const { id } = req.params
const key = req.query.sentFrom
const sentFrom = {}
sentFrom[key] = true
const moderator = await ConsultancyEntry.getModerator(id)
// TODO i18n TIME FORMAT
@@ -197,9 +205,13 @@ consultancyAdmin.edit = async (req, res) => {
const isPublished = entry.status === 'published'
const { slug, ...meta } = STATUS_META[entry.status] ?? STATUS_META.new
const sentFrom = req.query.sentFrom || slug
res.render('pages/consultancy/admin/edit', {
id,
sentFrom: key,
sentFrom,
meta,
entry: entry,
allPrimaryDomains,
moderator,
@@ -392,14 +404,6 @@ async function consultancyRequest(
}
}
if (entry.timeCreated) {
const date = new Date(entry.timeCreated)
entry.formattedTimeCreated = `${date.getDate()}. ${
date.getMonth() + 1
}. ${date.getFullYear()}`
}
return entry
})
+153 -22
View File
@@ -15,7 +15,10 @@ const { getExportFilesPath } = require('../models/helpers/dictionary')
const { DEFAULT_HITS_PER_PAGE, DATA_FILES_PATH } = require('../config/settings')
const {
statusChangeCheckAndAct,
determineNewStatus
determineNewStatus,
resolveDictionarySort,
parseDictionaryListFilters,
DICTIONARY_STATUSES
} = require('./helpers/dictionary')
const SFDSuggestionImporter = require('./helpers/search-filter-data-suggestion-importer')
const Extraction = require('../models/extraction')
@@ -26,7 +29,7 @@ const importFileBodyParser = multer({
dest: `${DATA_FILES_PATH}/dict_import_temp`,
limits: {
fieldNameSize: 21,
fieldSize: 9,
fieldSize: 64,
fields: 3,
fileSize: 1000 * 1000 * 1000, // 1GB
headerPairs: 500
@@ -99,11 +102,9 @@ dictionary.updateDescription = async (req, res) => {
const { dictionaryId } = req.params
const { body } = req
// TODO Consider using a transaction.
await Promise.all([
Dictionary.updateDescription(dictionaryId, body),
Dictionary.deleteSecondaryDomains(dictionaryId, body),
Dictionary.updateSecondaryDomains(dictionaryId, body)
Dictionary.updateSecondaryDomainAssociations(dictionaryId, body)
])
res.redirect(303, 'back')
@@ -205,11 +206,9 @@ dictionary.updateStructure = async (req, res) => {
const { body } = req
const { dictionaryId } = req.params
// TODO Consider using a transaction.
await Promise.all([
Dictionary.updateStructure(dictionaryId, body),
Dictionary.deleteLanguages(dictionaryId),
Dictionary.updateLanguages(dictionaryId, body)
Dictionary.updateLanguageAssociations(dictionaryId, body)
])
res.redirect(303, 'back')
}
@@ -294,18 +293,57 @@ dictionary.showImportFromFileForm = async (req, res) => {
dictionary.listAdminDictionaries = async (req, res) => {
const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE
const page = +req.query.p > 0 ? +req.query.p : 1
const { sortBy, sortDir } = resolveDictionarySort(
req.query.sort,
req.query.dir
)
const filters = parseDictionaryListFilters(req.query)
const statusLabels = {
closed: req.t('zaprt'),
reviewed: req.t('v predogledu'),
published: req.t('odprt')
}
const { pages_total: numberOfAllPages, results } =
await Dictionary.fetchAllAdminDictionaries(
const [
{ pages_total: numberOfAllPages, results },
allPrimaryDomains,
allSecondaryDomains,
allLanguages
] = await Promise.all([
Dictionary.fetchAllAdminDictionaries(
req.determinedLanguage,
resultsPerPage,
1
)
page,
sortBy,
sortDir,
filters
),
Dictionary.fetchAllPrimaryDomains(req.determinedLanguage),
Dictionary.fetchAllSecondaryDomainsUnfiltered(req.determinedLanguage),
Dictionary.fetchAllLanguages(req.determinedLanguage, false)
])
const allStatuses = DICTIONARY_STATUSES.map(value => ({
value,
label: statusLabels[value]
}))
res.render('pages/admin/dictionaries-list', {
title: req.t('Seznam slovarjev'),
numberOfAllPages,
results
results,
page,
sortBy,
sortDir,
q: filters.nameQuery,
pd: filters.primaryDomainIds || [],
sd: filters.secondaryDomainIds || [],
lang: filters.languageIds || [],
status: filters.statuses || [],
allPrimaryDomains,
allSecondaryDomains,
allLanguages,
allStatuses
})
}
@@ -335,6 +373,85 @@ dictionary.adminEditDescription = async (req, res) => {
})
}
dictionary.listViewableDictionaries = async (req, res) => {
const resultsPerPage = req.user?.hitsPerPage || DEFAULT_HITS_PER_PAGE
const page = +req.query.p > 0 ? +req.query.p : 1
const { sortBy, sortDir } = resolveDictionarySort(
req.query.sort,
req.query.dir
)
const filters = parseDictionaryListFilters(req.query)
const statusLabels = {
closed: req.t('zaprt'),
reviewed: req.t('v predogledu'),
published: req.t('odprt')
}
const [
{ pages_total: numberOfAllPages, results },
allPrimaryDomains,
allSecondaryDomains,
allLanguages
] = await Promise.all([
Dictionary.fetchAllAdminDictionaries(
req.determinedLanguage,
resultsPerPage,
page,
sortBy,
sortDir,
filters
),
Dictionary.fetchAllPrimaryDomains(req.determinedLanguage),
Dictionary.fetchAllSecondaryDomainsUnfiltered(req.determinedLanguage),
Dictionary.fetchAllLanguages(req.determinedLanguage, false)
])
const allStatuses = DICTIONARY_STATUSES.map(value => ({
value,
label: statusLabels[value]
}))
res.render('pages/view-resources/list', {
title: req.t('Seznam slovarjev'),
numberOfAllPages,
results,
page,
sortBy,
sortDir,
q: filters.nameQuery,
pd: filters.primaryDomainIds || [],
sd: filters.secondaryDomainIds || [],
lang: filters.languageIds || [],
status: filters.statuses || [],
allPrimaryDomains,
allSecondaryDomains,
allLanguages,
allStatuses
})
}
dictionary.viewDictionaryDetails = async (req, res) => {
const { dictionaryId } = req.params
const [
allPrimaryDomains,
dictionaryData,
associatedSecondaryDomains,
status
] = await Promise.all([
Dictionary.fetchAllPrimaryDomains(req.determinedLanguage),
Dictionary.fetchEditDescription(dictionaryId),
Dictionary.fetchSecondaryDomains(dictionaryId),
Dictionary.fetchStatus(dictionaryId)
])
res.render('pages/view-resources/dictionary-details', {
title: req.t('Osnovni podatki'),
allPrimaryDomains,
dictionary: dictionaryData,
associatedSecondaryDomains,
status
})
}
dictionary.updateAdminDescription = async (req, res) => {
// TODO Due to reindexing of all of dictionary entries on status change, this operation might take a while.
// TODO Stress test and consider either a notification to user or alteast a progress indicator while they wait.
@@ -344,11 +461,9 @@ dictionary.updateAdminDescription = async (req, res) => {
const oldDictStatus = await Dictionary.fetchStatus(dictionaryId)
// TODO Consider using a transaction.
await Promise.all([
Dictionary.updateDescription(dictionaryId, body),
Dictionary.deleteSecondaryDomains(dictionaryId, body),
Dictionary.updateSecondaryDomains(dictionaryId, body),
Dictionary.updateSecondaryDomainAssociations(dictionaryId, body),
Dictionary.updateStatus(dictionaryId, body)
])
@@ -674,6 +789,7 @@ dictionary.dictionaryDetails = async (req, res) => {
}
dictionary.importFromFile = async (req, res) => {
let jobId
try {
await parseImportFileBody(req, res)
// TODO return JSON error response rather then delegate to express.
@@ -684,7 +800,7 @@ dictionary.importFromFile = async (req, res) => {
const importFilePath = req.file.path
const { deleteExistingEntries, entryStatus, importFileFormat } = req.body
await Dictionary.openImportFileJob(
jobId = await Dictionary.openImportFileJob(
dictionaryId,
deleteExistingEntries,
importFileFormat
@@ -695,26 +811,41 @@ dictionary.importFromFile = async (req, res) => {
await Entry.deleteAll(dictionaryId)
}
await Dictionary.importFromFile(
const { totalCount, validCount } = await Dictionary.importFromFile(
req.user.id,
dictionaryId,
importFilePath,
entryStatus
entryStatus,
importFileFormat
)
// TODO Rather then waiting for success/failure, return immediately and continue processing in the background.
// TODO Also add API endpoint for getting progress.
await Dictionary.closeImportFileJob(
jobId,
'done',
validCount,
totalCount - validCount
)
await Dictionary.indexIntoSearchEngine(dictionaryId)
// TODO Error --> import job status: (indexing) error --> User manually triggers reindex.
debug('IMPORT SUCCESSFUL')
const importProcessId = 'DUMMY ID' // TODO You'll get it from DB.
res.status(202).send(importProcessId)
res.status(202).send({ jobId })
} catch (error) {
// TODO Consider writing a property on req and add an extra error handler for API errors.
debug('IMPORT FAILED')
debug(error)
if (jobId) {
try {
await Dictionary.closeImportFileJob(jobId, 'error', 0, 0)
} catch (closeError) {
debug('ERROR CLOSING IMPORT FILE JOB:')
debug(closeError)
}
}
res.status(400).send(error)
} finally {
try {
@@ -756,7 +887,7 @@ dictionary.exportDownload = [
]
function importFileFilter(req, file, cb) {
if (file.mimetype !== 'text/xml') {
if (!['text/xml', 'application/json'].includes(file.mimetype)) {
const customError = Error('Invalid file type')
customError.displayInProd = true
return cb(customError)
+48 -1
View File
@@ -1,6 +1,6 @@
/* global __ */
const { getInstanceSetting } = require('../../models/helpers')
const { getInstanceSetting, intoDbArray } = require('../../models/helpers')
const Dictionary = require('../../models/dictionary')
const cache = require('../../models/cache')
const { promisify } = require('util')
@@ -194,6 +194,53 @@ exports.statusChangeCheckAndAct = {
}
}
// Whitelist of admin dictionary-list sortable columns, keeping req.query
// values from ever reaching raw SQL - see models/dictionary.js
// fetchAllAdminDictionaries.
const DICTIONARY_LIST_SORT_COLUMNS = [
'id',
'name',
'status',
'timeCreated',
'timeModified'
]
// Resolves the admin dictionary-list sort params from a request query,
// defaulting to id/desc when absent or invalid.
exports.resolveDictionarySort = (querySort, queryDir) => ({
sortBy: DICTIONARY_LIST_SORT_COLUMNS.includes(querySort) ? querySort : 'id',
sortDir: queryDir === 'asc' ? 'asc' : 'desc'
})
const DICTIONARY_STATUSES = ['closed', 'reviewed', 'published']
exports.DICTIONARY_STATUSES = DICTIONARY_STATUSES
// Keeps only numeric-looking id strings, matching the option values the
// admin filter selects render (real DB smallint ids) - drops anything else
// rather than letting it reach a ::smallint[] cast in SQL.
const toNumericIdArray = ids => {
if (!ids) return null
const numericIds = ids.filter(id => /^\d+$/.test(id))
return numericIds.length > 0 ? numericIds : null
}
// Parses/whitelists the admin dictionary-list search+filter params from a
// request query. A filter category left unselected resolves to null ("no
// filter"), never an empty array (which would match zero rows in SQL).
exports.parseDictionaryListFilters = query => {
const rawStatuses = intoDbArray(query.status)
const statuses = rawStatuses
? rawStatuses.filter(value => DICTIONARY_STATUSES.includes(value))
: null
return {
nameQuery: typeof query.q === 'string' ? query.q.trim() : '',
primaryDomainIds: toNumericIdArray(intoDbArray(query.pd)),
secondaryDomainIds: toNumericIdArray(intoDbArray(query.sd)),
languageIds: toNumericIdArray(intoDbArray(query.lang)),
statuses: statuses && statuses.length > 0 ? statuses : null
}
}
// Helper function used by statusChangeCheckAndAct methods.
async function renderAndSendStatusChangeEmails(
appRef,
@@ -18,7 +18,7 @@ helper.initialize = async determinedLanguage => {
l => l.id !== 32
)
initializers.allDictionaryNames = await Dictionary.fetchAll(
initializers.allDictionaryNames = await Dictionary.fetchAllPublished(
determinedLanguage
)
+4
View File
@@ -495,6 +495,10 @@ exports.deleteProfile = async (req, res) => {
}
exports.changePassword = async (req, res) => {
// SSO accounts have no local password to change - this page doesn't apply to them (the sidebar
// link is also hidden for them, but this covers direct navigation to the URL).
if (req.user.isSso) return res.redirect(303, '/moj-racun')
res.render('pages/profile/change-password', {
title: req.t('Spremeni geslo')
})
+272
View File
@@ -0,0 +1,272 @@
const { promisify } = require('util')
const bcrypt = require('bcrypt')
const passport = require('../middleware/auth')
const User = require('../models/user')
const { rememberMeCookieSettings } = require('../config/settings')
const universityDomainAbbreviations = require('../config/university-domains')
const STRATEGY_NAME = 'oidc-uni-lj'
const oidc = {}
// Lazily discovers/registers the University of Ljubljana strategy on first use. Returns false
// (and has already flashed+redirected) if the IdP couldn't be reached - e.g. the dev Authentik
// stand-in isn't running.
async function ensureStrategyOrBail(req, res) {
try {
await passport.getUniLjStrategy()
return true
} catch (error) {
// eslint-disable-next-line no-console
console.error(
'University of Ljubljana OIDC discovery/bootstrap failed:',
error
)
req.flash(
'info',
req.t(
'Prijava prek Univerze v Ljubljani trenutno ni na voljo. Poskusite kasneje.'
)
)
res.redirect(303, '/')
return false
}
}
async function issueRememberMe(res, user) {
const rememberMeToken = await User.generateRememberMeToken()
await User.saveRememberMeToken(user, rememberMeToken)
res.cookie('remember_me', rememberMeToken, rememberMeCookieSettings)
}
// Derives the username used for both a brand-new SSO account and an SSO account conversion, from
// IdP-provided claims only. Shared by createProfileForm (display) and createProfileSubmit/
// convertAccountSubmit (the authoritative value actually persisted) so the two never disagree.
function deriveSuggestedUsername({ givenName, familyName, preferredUsername, email }) {
const usernameLocalPart =
preferredUsername && preferredUsername.includes('@')
? preferredUsername.slice(0, preferredUsername.indexOf('@'))
: null
const emailDomain =
email && email.includes('@') ? email.slice(email.indexOf('@') + 1) : null
const domainAbbreviation = emailDomain
? universityDomainAbbreviations[emailDomain] || emailDomain
: null
return givenName && familyName && usernameLocalPart && domainAbbreviation
? `${givenName} ${familyName} (${usernameLocalPart}, ${domainAbbreviation})`
: preferredUsername
}
// GET /users/oidc/login
oidc.login = async (req, res, next) => {
if (req.isAuthenticated()) return res.redirect(303, '/')
if (!(await ensureStrategyOrBail(req, res))) return
passport.authenticate(STRATEGY_NAME)(req, res, next)
}
// GET /users/oidc/callback
oidc.callback = async (req, res, next) => {
if (!(await ensureStrategyOrBail(req, res))) return
passport.authenticate(STRATEGY_NAME, async (err, user, info) => {
if (err) {
// Covers tampered/missing `state`, expired authorization code, IdP-side errors, etc.
// eslint-disable-next-line no-console
console.error('University of Ljubljana OIDC callback failed:', err)
req.flash(
'info',
req.t('Prijava prek Univerze v Ljubljani ni uspela. Poskusite znova.')
)
return res.redirect(303, '/')
}
if (user) {
// Returning user with an already-linked external identity.
const loginAsync = promisify(req.login.bind(req))
await loginAsync(user)
await issueRememberMe(res, user)
req.flash(
'info',
req.t('Uspešno ste se prijavili prek Univerze v Ljubljani.')
)
return res.redirect(303, '/')
}
if (info && info.action === 'account-inactive') {
req.flash(
'info',
req.t(
'Vaš uporabniški račun ni aktiven. Za pomoč se obrnite na skrbnika portala.'
)
)
return res.redirect(303, '/')
}
if (info && info.action === 'missing-required-data') {
// Nothing to review or overwrite with - there's no create/convert page to send them to.
req.flash(
'info',
req.t(
'Vaš račun pri Univerzi v Ljubljani ne vsebuje vseh podatkov (imena in priimka), potrebnih za ustvarjanje profila na portalu. Za pomoč se obrnite na skrbnika portala.'
)
)
return res.redirect(303, '/')
}
if (info && info.action === 'convert') {
req.session.pendingOidcAuth = {
authProvider: 'uni_lj',
subject: info.subject,
claims: info.claims,
matchedUserId: info.matchedUserId
}
return res.redirect(303, '/users/convert-account')
}
if (info && info.action === 'create-profile') {
req.session.pendingOidcAuth = {
authProvider: 'uni_lj',
subject: info.subject,
claims: info.claims
}
return res.redirect(303, '/users/create-profile')
}
req.flash('info', req.t('Prijava prek Univerze v Ljubljani ni uspela.'))
res.redirect(303, '/')
})(req, res, next)
}
// GET /users/create-profile
oidc.createProfileForm = (req, res) => {
if (req.isAuthenticated()) return res.redirect(303, '/')
const pending = req.session.pendingOidcAuth
if (!pending) return res.redirect(303, '/')
res.render('pages/oidc/create-profile', {
title: req.t('Ustvarite svoj profil'),
claims: pending.claims,
suggestedUsername: deriveSuggestedUsername(pending.claims)
})
}
// POST /api/v1/users/create-profile (AJAX, mirrors register/reset-password's plain-text response
// convention). Every field is derived from the session-stored, server-side IdP claims - `req.body`
// is intentionally never read here, since the review page has no editable fields for the user to
// legitimately submit (this is what actually stops a tampered/direct API call from creating an
// account with attacker-chosen name/username - the disabled inputs in the view are only a UX
// signal, not the enforcement).
oidc.createProfileSubmit = async (req, res) => {
const pending = req.session.pendingOidcAuth
if (req.isAuthenticated() || !pending) {
const err = Error(req.t('Seja je potekla. Poskusite znova.'))
err.status = 400
err.displayInProd = true
throw err
}
const { givenName, familyName, email } = pending.claims
const username = deriveSuggestedUsername(pending.claims)
const userId = await User.createFromExternalIdentity(
pending.authProvider,
pending.subject,
{
username,
firstName: givenName,
lastName: familyName,
email,
language: req.session.language
},
req.t
)
delete req.session.pendingOidcAuth
delete req.session.language
const loginAsync = promisify(req.login.bind(req))
await loginAsync({ id: userId })
await issueRememberMe(res, { id: userId })
res.send(
req.t(
'Uspešno ste ustvarili račun prek Univerze v Ljubljani in se prijavili.'
)
)
}
// GET /users/convert-account
oidc.convertAccountForm = async (req, res) => {
if (req.isAuthenticated()) return res.redirect(303, '/')
const pending = req.session.pendingOidcAuth
if (!pending || !pending.matchedUserId) return res.redirect(303, '/')
const existingUser = await User.fetchByUsernameOrEmail(pending.claims.email)
res.render('pages/oidc/convert-account', {
title: req.t('Pretvorite svoj račun'),
claims: pending.claims,
suggestedUsername: deriveSuggestedUsername(pending.claims),
existingUsername: existingUser?.username
})
}
// POST /api/v1/users/convert-account (AJAX). Password is the only field the client actually
// supplies and the only one that's meaningful to trust here - it confirms ownership of the
// matched local account. Every other written field (username/first/last name, and the removal of
// the local password) comes from the session-stored IdP claims, same as createProfileSubmit,
// never from `req.body`.
oidc.convertAccountSubmit = async (req, res) => {
const pending = req.session.pendingOidcAuth
if (req.isAuthenticated() || !pending || !pending.matchedUserId) {
const err = Error(req.t('Seja je potekla. Poskusite znova.'))
err.status = 400
err.displayInProd = true
throw err
}
const { password } = req.body
const existingUser = await User.fetchByUsernameOrEmail(pending.claims.email)
const isValid =
existingUser &&
existingUser.status === 'active' &&
existingUser.bcrypt_hash &&
(await bcrypt.compare(password || '', existingUser.bcrypt_hash))
if (!isValid) {
const err = Error(req.t('Nepravilno geslo.'))
err.status = 403
err.displayInProd = true
throw err
}
const { givenName, familyName } = pending.claims
await User.convertToExternalIdentity(
pending.authProvider,
pending.subject,
existingUser.id,
{
username: deriveSuggestedUsername(pending.claims),
firstName: givenName,
lastName: familyName
},
req.t
)
delete req.session.pendingOidcAuth
const loginAsync = promisify(req.login.bind(req))
await loginAsync({ id: existingUser.id })
await issueRememberMe(res, { id: existingUser.id })
res.send(
req.t(
'Vaš račun je bil uspešno pretvorjen v prijavo prek Univerze v Ljubljani. Odslej se lahko prijavite le še prek tega načina.'
)
)
}
module.exports = oidc
+10
View File
@@ -130,6 +130,16 @@ user.generateResetPasswordToken = async (req, res) => {
)
}
if (!user.bcrypt_hash) {
return res
.status(400)
.send(
req.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.'
)
)
}
const resetPasswordToken = (await RandomBytesAsync(32)).toString('hex')
await User.saveResetPasswordToken(user.id, resetPasswordToken)
const { email: userEmail, username } = user