import express from 'express';
import cookieParser from 'cookie-parser';
import { readAuthConfig, hasProvider, clientConfig } from './config.js';
import { createOidcClient, OidcCallbackError } from './oidc.js';
import { issueSession, readSession, clearSession, setTx, takeTx, safeRedirect } from './session.js';
import { mapAccount } from './accountMapping.js';
import { renameGuard } from './rename.js';
export { readAuthConfig, clientConfig };
const esc = (s)=>String(s).replace(/[&<>"']/g, (c)=>({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c]));
const page = (title, body)=>`
${esc(title)}`
+ ``
+ ``
+ `${esc(title)}
${body}`;
const errorPage = (res, status, message, retryUrl = '/auth/oidc/login')=>{
res.status(status).type('html').send(page('Anmeldung fehlgeschlagen',
`${esc(message)}
Erneut anmelden
`));
};
// Account-Middleware: läuft direkt nach der Upstream-Middleware und setzt req.account neu (ADR 0001 §3)
export const accountMiddleware = (config)=>(req, res, next)=>{
const session = hasProvider(config, 'oidc') ? readSession(req, config) : null;
if(session) {
req.account = { username: session.username, uid: session.uid, provider: 'oidc' };
} else if(hasProvider(config, 'naturalcrit')) {
if(req.account) req.account = { ...req.account, provider: 'naturalcrit' };
} else {
req.account = undefined;
}
next();
};
/**
* @param {object} config Ergebnis von readAuthConfig()
* @param {{ getUsers: ()=>object, brewAuthorExists: (name:string)=>Promise, oidcClient?: object }} deps
*/
export const createAuthRouter = (config, deps = {})=>{
const router = express.Router();
const oidcEnabled = hasProvider(config, 'oidc');
const naturalcritEnabled = hasProvider(config, 'naturalcrit');
const parseCookies = cookieParser();
router.use((req, res, next)=>req.cookies ? next() : parseCookies(req, res, next));
// Upstream-Route absichern, bevor sie greift: OIDC gesperrt (A01), naturalcrit nur mit Nachweis (ADR 0001 §7)
router.put('/api/user/rename', renameGuard(config));
if(!naturalcritEnabled) {
router.post('/local/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
}
router.get('/auth/logout', async (req, res)=>{
const wasOidc = req.account?.provider === 'oidc';
clearSession(res, config);
if(wasOidc && oidcEnabled) {
try {
const url = await (deps.oidcClient ?? (deps.oidcClient = createOidcClient(config))).buildEndSessionUrl();
if(url) return res.redirect(url);
} catch (err) {
console.warn('OIDC end_session nicht möglich:', err?.message);
}
}
res.redirect('/');
});
if(!oidcEnabled) {
// Abgeschaltete Methode: Endpunkte gesperrt
router.all('/auth/oidc/*splat', (req, res)=>res.status(404).json({ error: 'OIDC-Login ist deaktiviert.' }));
router.get('/auth/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
return router;
}
const oidc = deps.oidcClient ?? (deps.oidcClient = createOidcClient(config));
// Auswahlseite, wenn beide Provider aktiv sind
router.get('/auth/login', (req, res)=>{
const redirect = safeRedirect(req.query.redirect);
if(!naturalcritEnabled) return res.redirect(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`);
const ncUrl = `https://www.naturalcrit.com/login?redirect=${encodeURIComponent(`${config.publicUrl}${redirect}`)}`;
res.type('html').send(page('Anmelden',
`${esc(config.oidc.label)}`
+ `NaturalCrit-Konto (Benutzername/Passwort, Google)`));
});
router.get('/auth/oidc/login', async (req, res)=>{
try {
const { url, tx } = await oidc.buildLogin(req.query.redirect);
setTx(res, config, tx);
res.redirect(url);
} catch (err) {
console.error('OIDC login:', err);
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
errorPage(res, 500, 'Anmeldung nicht möglich.');
}
});
router.get('/auth/oidc/callback', async (req, res)=>{
const tx = takeTx(req, res, config);
if(!tx) return errorPage(res, 400, 'Die Anmeldung ist abgelaufen oder wurde nicht von dieser Seite gestartet.');
if(req.query.state !== tx.state) return errorPage(res, 400, 'Ungültiger Anmeldezustand (state).');
try {
const identity = await oidc.handleCallback(tx, `${config.publicUrl}${req.originalUrl}`);
const users = deps.getUsers();
const user = await mapAccount(identity, {
users,
brewAuthorExists : deps.brewAuthorExists,
usernameClaim : config.oidc.usernameClaim,
linkByEmail : config.oidc.linkByEmail
});
issueSession(res, config, user, identity);
res.redirect(safeRedirect(tx.redirect));
} catch (err) {
console.error('OIDC callback:', err?.cause ?? err);
if(err instanceof OidcCallbackError) return errorPage(res, err.status, err.message);
errorPage(res, 500, 'Die Anmeldung ist fehlgeschlagen.');
}
});
return router;
};