Files
term_portal/express/middleware/auth.js
T

239 lines
7.2 KiB
JavaScript

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const RememberMeStrategy =
require('../lib/passport-remember-me-extended').Strategy
const { Issuer, Strategy: OidcStrategy, custom } = require('openid-client')
const bcrypt = require('bcrypt')
const db = require('../models/db')
const User = require('../models/user')
const {
rememberMeCookieSettings,
REMEMBER_ME_DURATION_SQL
} = require('../config/settings')
const {
oidcUniLjClientId,
oidcUniLjClientSecret,
oidcUniLjDiscoveryUrl,
oidcUniLjAuthorizationExternalOrigin,
origin
} = require('../config/keys')
// Fail fast rather than hang a request indefinitely if the IdP is unreachable.
custom.setHttpOptionsDefaults({ timeout: 5000 })
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async (id, done) => {
try {
// TODO Consider storing this data in cache.
// TODO In that case, make sure to invalidate it at every (relevant) data change.
const user = await User.fetchDeserializedDataById(id)
// TODO Consider what to do if no user was found?
// TODO This is a current workaround until session invalidation is implemented.
if (user.status !== 'active') return done(null, false)
done(null, user)
} catch (error) {
done(error)
}
})
passport.use(
new LocalStrategy(
{ passReqToCallback: true, usernameField: 'usernameOrEmail' },
async (req, usernameOrEmail, password, done) => {
try {
const user = await User.fetchByUsernameOrEmail(usernameOrEmail)
if (!user) {
return done(null, false, {
message: req.t(
'Nepravilno uporabniško ime, elektronski naslov ali geslo.'
)
})
}
if (user.status !== 'active') {
return done(null, false, {
message: req.t(
'Uporabniški račun še ni aktiviran. Kliknite aktivacijsko povezavo, katero smo vam poslali po elektronski pošti.'
)
})
}
if (!user.bcrypt_hash) {
return done(null, false, {
message: 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 isCorrectPassword = await bcrypt.compare(
password,
user.bcrypt_hash
)
if (!isCorrectPassword) {
return done(null, false, {
message: req.t(
'Nepravilno uporabniško ime, elektronski naslov ali geslo.'
)
})
}
delete user.bcrypt_hash
done(null, user)
} catch (error) {
done(error)
}
}
)
)
passport.use(
new RememberMeStrategy(
{ cookie: rememberMeCookieSettings, signed: true },
async (token, done) => {
try {
const text = `
DELETE
FROM user_token_remember_me t
WHERE
t.token = $1
AND AGE(NOW(), t.time_created) < $2::INTERVAL
RETURNING (SELECT u.id FROM "user" u where u.id = t.user_id)
`
const values = [token, REMEMBER_ME_DURATION_SQL]
let {
rows: [user]
} = await db.query(text, values)
if (!user) return done(null, false)
user = await User.fetchDeserializedDataById(user.id)
done(null, user)
} catch (error) {
done(error)
}
},
async (user, done) => {
try {
const token = await User.generateRememberMeToken()
await User.saveRememberMeToken(user, token)
done(null, token)
} catch (error) {
done(error)
}
}
)
)
let cachedUniLjStrategy = null
// Lazily discovers + caches the University of Ljubljana OIDC client/Strategy. Deliberately NOT
// run at module load: `docker compose up` (default profile) never starts the dev Authentik
// stand-in (`--profile develop-idp`), and eager discovery here would hang/throw at express boot
// for every developer not touching SSO. Only ever called from an actual SSO login/callback
// request; failures are not cached, so the very next click retries (no restart needed once the
// IdP comes back up).
async function getUniLjStrategy() {
if (cachedUniLjStrategy) return cachedUniLjStrategy
const internalIssuer = await Issuer.discover(oidcUniLjDiscoveryUrl)
const metadata = internalIssuer.metadata
if (oidcUniLjAuthorizationExternalOrigin) {
const authUrl = new URL(metadata.authorization_endpoint)
const externalOrigin = new URL(oidcUniLjAuthorizationExternalOrigin)
authUrl.protocol = externalOrigin.protocol
authUrl.host = externalOrigin.host // includes port
metadata.authorization_endpoint = authUrl.href
}
const issuer = new Issuer(metadata)
const redirectUri = new URL('/users/oidc/callback', origin).href
const client = new issuer.Client({
client_id: oidcUniLjClientId,
client_secret: oidcUniLjClientSecret,
redirect_uris: [redirectUri],
response_types: ['code']
})
cachedUniLjStrategy = new OidcStrategy(
{
client,
params: { scope: 'openid email profile' },
passReqToCallback: true
},
verifyUniLj
)
passport.use('oidc-uni-lj', cachedUniLjStrategy)
return cachedUniLjStrategy
}
// The ID token's `claims` never carries given_name/family_name on the real University of
// Ljubljana/Entra IdP - only the standard /userinfo response does. The 4-arg verify-callback
// signature is required to get openid-client's Strategy to auto-fetch userinfo (see
// node_modules/openid-client/lib/passport_strategy.js's `loadUserinfo` check, which triggers on a
// 4-arg callback) - `userinfo` is a real data source here, not a debugging aid.
async function verifyUniLj(req, tokenset, userinfo, done) {
try {
const claims = tokenset.claims()
const subject = claims.sub
const linkedUser = await User.fetchByExternalIdentity('uni_lj', subject)
if (linkedUser) {
if (linkedUser.status !== 'active') {
return done(null, false, { action: 'account-inactive' })
}
return done(null, { id: linkedUser.id })
}
const parsedClaims = {
givenName: userinfo.given_name || '',
familyName: userinfo.family_name || '',
email: claims.email || '',
preferredUsername: claims.preferred_username || ''
}
// Both the create and convert flows below need a name to show/store - there's nothing to
// review or overwrite with otherwise. This is checked before the email-match lookup since it
// blocks both outcomes equally.
if (!parsedClaims.givenName || !parsedClaims.familyName) {
return done(null, false, { action: 'missing-required-data' })
}
if (parsedClaims.email) {
const matchedUser = await User.fetchActiveByEmail(parsedClaims.email)
if (matchedUser) {
return done(null, false, {
action: 'convert',
claims: parsedClaims,
subject,
matchedUserId: matchedUser.id
})
}
}
done(null, false, {
action: 'create-profile',
claims: parsedClaims,
subject
})
} catch (error) {
done(error)
}
}
module.exports = passport
module.exports.getUniLjStrategy = getUniLjStrategy