273 lines
8.8 KiB
JavaScript
273 lines
8.8 KiB
JavaScript
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
|