372 lines
20 KiB
JavaScript
372 lines
20 KiB
JavaScript
// Authentication route registration for the web app.
|
|
|
|
const { normalizeReturnToPath, getRequestOrigin } = require('../../lib/auth/session');
|
|
const { fetchAppSettings } = require('#src/data/app-settings');
|
|
const { renderAccountEmailTemplate } = require('#src/data/account-email-templates');
|
|
|
|
module.exports = function registerAuthRoutes(app, deps) {
|
|
const pool = deps.pool;
|
|
const pages = deps.pages;
|
|
const createUserSession = deps.createUserSession;
|
|
const setSessionCookie = deps.setSessionCookie;
|
|
const getSessionMaxAgeMs = deps.getSessionMaxAgeMs;
|
|
const clearSessionCookie = deps.clearSessionCookie;
|
|
const parseCookies = deps.parseCookies;
|
|
const consumeAuthMessageCookie = deps.consumeAuthMessageCookie;
|
|
const setAuthMessageCookie = deps.setAuthMessageCookie;
|
|
const hashSessionToken = deps.hashSessionToken;
|
|
const verifyPassword = deps.verifyPassword;
|
|
const sessionCookieName = deps.sessionCookieName;
|
|
const recordRequestAuditEvent = deps.recordRequestAuditEvent;
|
|
const sendAccountEmail = deps.sendAccountEmail;
|
|
const createOneTimeToken = deps.createOneTimeToken;
|
|
const getConnection = deps.getConnection;
|
|
const rbacData = deps.rbacData;
|
|
|
|
function getReturnTo(req) {
|
|
return normalizeReturnToPath(req && (req.query && req.query.returnTo || req.body && req.body.returnTo), getRequestOrigin(req));
|
|
}
|
|
|
|
function buildLoginRedirect(returnTo, username) {
|
|
const query = [];
|
|
if (returnTo) query.push('returnTo=' + encodeURIComponent(returnTo));
|
|
if (username) query.push('username=' + encodeURIComponent(username));
|
|
return query.length ? '/login?' + query.join('&') : '/login';
|
|
}
|
|
|
|
function getClientAddress(req) {
|
|
const forwardedAddress = String(req && req.headers && req.headers['x-forwarded-for'] || '').split(',')[0].trim();
|
|
return forwardedAddress || String(req && req.ip || req && req.socket && req.socket.remoteAddress || 'unknown').trim() || 'unknown';
|
|
}
|
|
|
|
function getRateLimitKey(username, address, scope) {
|
|
if (scope === 'username') return 'username:' + username;
|
|
if (scope === 'ip') return 'ip:' + address;
|
|
return 'both:' + JSON.stringify([username, address]);
|
|
}
|
|
|
|
async function getLoginRateLimitSettings() {
|
|
const settings = await fetchAppSettings(pool);
|
|
return {
|
|
maxAttempts: Number(settings['security.login_max_attempts']) || 5,
|
|
lockoutMinutes: Number(settings['security.login_lockout_minutes']) || 15,
|
|
scope: String(settings['security.login_rate_limit_scope'] || 'both')
|
|
};
|
|
}
|
|
|
|
async function getLoginRateLimitStatus(rateKey) {
|
|
const [rows] = await pool.query('SELECT locked_until FROM a_login_attempts WHERE rate_key = ? LIMIT 1', [rateKey]);
|
|
const lockedUntil = rows && rows[0] && rows[0].locked_until ? new Date(rows[0].locked_until).getTime() : 0;
|
|
return {
|
|
limited: lockedUntil > Date.now(),
|
|
remainingMinutes: Math.max(1, Math.ceil((lockedUntil - Date.now()) / 60000))
|
|
};
|
|
}
|
|
|
|
async function recordFailedLogin(rateKey, settings) {
|
|
const [rows] = await pool.query('SELECT failed_count, locked_until FROM a_login_attempts WHERE rate_key = ? LIMIT 1', [rateKey]);
|
|
const existing = rows && rows[0] ? rows[0] : null;
|
|
const existingLockedUntil = existing && existing.locked_until ? new Date(existing.locked_until).getTime() : 0;
|
|
const currentCount = existingLockedUntil && existingLockedUntil <= Date.now() ? 0 : Number(existing && existing.failed_count) || 0;
|
|
const failedCount = currentCount + 1;
|
|
const lockedUntil = failedCount >= settings.maxAttempts ? new Date(Date.now() + settings.lockoutMinutes * 60 * 1000) : null;
|
|
if (existing) {
|
|
await pool.query('UPDATE a_login_attempts SET failed_count = ?, last_failed_at = ?, locked_until = ? WHERE rate_key = ?', [failedCount, new Date(), lockedUntil, rateKey]);
|
|
return lockedUntil ? { remainingMinutes: Math.max(1, Math.ceil((lockedUntil.getTime() - Date.now()) / 60000)) } : null;
|
|
}
|
|
await pool.query('INSERT INTO a_login_attempts (rate_key, failed_count, last_failed_at, locked_until) VALUES (?, ?, ?, ?)', [rateKey, failedCount, new Date(), lockedUntil]);
|
|
return lockedUntil ? { remainingMinutes: Math.max(1, Math.ceil((lockedUntil.getTime() - Date.now()) / 60000)) } : null;
|
|
}
|
|
|
|
async function clearFailedLogins(rateKey) {
|
|
await pool.query('DELETE FROM a_login_attempts WHERE rate_key = ?', [rateKey]);
|
|
}
|
|
|
|
async function getPasswordRequirements() {
|
|
const settings = await fetchAppSettings(pool);
|
|
return {
|
|
minimumLength: settings['security.password_min_length'],
|
|
minimumCategories: settings['security.password_min_categories'],
|
|
requireLowercase: settings['security.password_require_lowercase'],
|
|
requireUppercase: settings['security.password_require_uppercase'],
|
|
requireNumber: settings['security.password_require_number'],
|
|
requireSymbol: settings['security.password_require_symbol']
|
|
};
|
|
}
|
|
|
|
app.get('/accept-invite', async function (req, res, next) {
|
|
try {
|
|
const token = String(req.query.token || '').trim();
|
|
const [rows] = await pool.query('SELECT email, name FROM a_user_invitations WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1', [hashSessionToken(token)]);
|
|
const invitation = rows[0] || null;
|
|
if (!invitation) return res.status(400).send(pages.renderAcceptInvitePage('This invitation is invalid or has expired.', token, '', '', await getPasswordRequirements(), false));
|
|
res.send(pages.renderAcceptInvitePage('', token, invitation.email, invitation.name, await getPasswordRequirements(), true));
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.post('/accept-invite', async function (req, res, next) {
|
|
const connection = typeof getConnection === 'function' ? await getConnection() : pool;
|
|
try {
|
|
const token = String(req.body.token || '').trim();
|
|
const username = String(req.body.username || '').trim();
|
|
const name = String(req.body.name || '').trim();
|
|
const password = String(req.body.password || '');
|
|
const confirmPassword = String(req.body.confirm_password || '');
|
|
const [rows] = await connection.query('SELECT id, email, name, role_ids_json FROM a_user_invitations WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1', [hashSessionToken(token)]);
|
|
const invitation = rows[0] || null;
|
|
const requirements = await getPasswordRequirements();
|
|
const renderError = function (message) { return res.status(400).send(pages.renderAcceptInvitePage(message, token, invitation ? invitation.email : '', name || (invitation && invitation.name) || '', requirements, Boolean(invitation))); };
|
|
if (!invitation) return renderError('This invitation is invalid or has expired.');
|
|
if (!username) return renderError('Username is required.');
|
|
if (!name) return renderError('Name is required.');
|
|
const [existingUsers] = await connection.query('SELECT id FROM a_users WHERE username = ? LIMIT 1', [username]);
|
|
if (existingUsers.length) return renderError('That username already exists.');
|
|
const strengthMessage = deps.validatePasswordStrength(password, requirements);
|
|
if (strengthMessage) return renderError(strengthMessage);
|
|
if (password !== confirmPassword) return renderError('Passwords do not match.');
|
|
const passwordRecord = deps.hashPassword(password);
|
|
const roleIds = JSON.parse(invitation.role_ids_json || '[]');
|
|
await connection.beginTransaction();
|
|
const [result] = await connection.query('INSERT INTO a_users (name, username, email, email_verified_at, password_hash, password_salt, password_iterations, created_by, modified_by) VALUES (?, ?, ?, NOW(), ?, ?, ?, NULL, NULL)', [name, username, invitation.email, passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations]);
|
|
if (rbacData && typeof rbacData.syncUserRoles === 'function') await rbacData.syncUserRoles(connection, result.insertId, roleIds);
|
|
await connection.query('UPDATE a_user_invitations SET used_at = NOW() WHERE id = ? AND used_at IS NULL', [invitation.id]);
|
|
await connection.commit();
|
|
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.invitation_accepted', targetType: 'user', targetId: result.insertId, targetLabel: username, details: { invitationId: invitation.id } });
|
|
res.redirect('/login?message=' + encodeURIComponent('Account created. You can now sign in.'));
|
|
} catch (error) {
|
|
try { await connection.rollback(); } catch (_rollbackError) {}
|
|
next(error);
|
|
} finally {
|
|
if (connection !== pool && connection && typeof connection.release === 'function') connection.release();
|
|
}
|
|
});
|
|
|
|
app.get('/forgot-password', function (req, res) {
|
|
res.send(pages.renderForgotPasswordPage(''));
|
|
});
|
|
|
|
app.post('/forgot-password', async function (req, res, next) {
|
|
try {
|
|
const identity = String(req.body.identity || '').trim();
|
|
const genericMessage = 'If that account has a verified email address, a reset link has been sent.';
|
|
const [rows] = await pool.query('SELECT id, name, username, email FROM a_users WHERE username = ? OR (email = ? AND email_verified_at IS NOT NULL) LIMIT 1', [identity, identity.toLowerCase()]);
|
|
const user = rows[0] || null;
|
|
const settings = await fetchAppSettings(pool);
|
|
if (user && user.email && user.email_verified_at && typeof sendAccountEmail === 'function' && typeof createOneTimeToken === 'function') {
|
|
const token = createOneTimeToken();
|
|
await pool.query('DELETE FROM a_account_tokens WHERE user_id = ? AND token_type = ?', [user.id, 'password-reset']);
|
|
await pool.query('INSERT INTO a_account_tokens (user_id, token_type, token_hash, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 30 MINUTE))', [user.id, 'password-reset', hashSessionToken(token)]);
|
|
const resetUrl = getRequestOrigin(req) + '/reset-password?token=' + encodeURIComponent(token);
|
|
try {
|
|
await sendAccountEmail(settings, Object.assign({ to: user.email }, renderAccountEmailTemplate(settings['email.reset_subject'], settings['email.reset_body'], { url: resetUrl, username: user.username, display_name: user.name, email: user.email, action_alignment: settings['email.reset_button_alignment'], action_label: settings['email.reset_button_text'] })));
|
|
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'password.reset_requested', targetType: 'user', targetId: user.id, targetLabel: user.username });
|
|
} catch (_mailError) {
|
|
await pool.query('DELETE FROM a_account_tokens WHERE token_hash = ?', [hashSessionToken(token)]);
|
|
}
|
|
}
|
|
res.send(pages.renderForgotPasswordPage(genericMessage));
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.get('/reset-password', async function (req, res, next) {
|
|
try {
|
|
const token = String(req.query.token || '').trim();
|
|
if (!token) return res.redirect('/forgot-password');
|
|
res.send(pages.renderResetPasswordPage('', token, await getPasswordRequirements()));
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.post('/reset-password', async function (req, res, next) {
|
|
try {
|
|
const token = String(req.body.token || '');
|
|
const password = String(req.body.password || '');
|
|
const confirmPassword = String(req.body.confirm_password || '');
|
|
const [rows] = await pool.query('SELECT t.id AS token_id, t.user_id, u.username, u.email FROM a_account_tokens t JOIN a_users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.token_type = ? AND t.used_at IS NULL AND t.expires_at > NOW() LIMIT 1', [hashSessionToken(token), 'password-reset']);
|
|
const record = rows[0] || null;
|
|
if (!record) return res.status(400).send(pages.renderResetPasswordPage('This reset link is invalid or has expired.', token, await getPasswordRequirements()));
|
|
const strengthMessage = deps.validatePasswordStrength(password, await getPasswordRequirements());
|
|
if (strengthMessage || password !== confirmPassword) return res.status(400).send(pages.renderResetPasswordPage(strengthMessage || 'Passwords do not match.', token, await getPasswordRequirements()));
|
|
const passwordRecord = deps.hashPassword(password);
|
|
await pool.query('UPDATE a_users SET password_hash = ?, password_salt = ?, password_iterations = ?, must_change_password = 0, modified_at = CURRENT_TIMESTAMP WHERE id = ?', [passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations, record.user_id]);
|
|
await pool.query('UPDATE a_account_tokens SET used_at = NOW() WHERE id = ?', [record.token_id]);
|
|
await pool.query('DELETE FROM a_sessions WHERE user_id = ?', [record.user_id]);
|
|
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'password.reset', targetType: 'user', targetId: record.user_id, targetLabel: record.username, details: { source: 'email' } });
|
|
res.redirect('/login?message=' + encodeURIComponent('Password updated. You can now sign in.'));
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.get('/verify-email', async function (req, res, next) {
|
|
try {
|
|
const tokenHash = hashSessionToken(String(req.query.token || ''));
|
|
const [rows] = await pool.query('SELECT id FROM a_users WHERE pending_email_token_hash = ? AND pending_email_expires_at > NOW() LIMIT 1', [tokenHash]);
|
|
const user = rows[0] || null;
|
|
if (!user) return res.status(400).send(pages.renderEmailVerificationErrorPage('This email verification link is invalid or has expired.'));
|
|
await pool.query('UPDATE a_users SET email = pending_email, email_verified_at = NOW(), pending_email = NULL, pending_email_token_hash = NULL, pending_email_expires_at = NULL WHERE id = ?', [user.id]);
|
|
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'email.verification_completed', targetType: 'user', targetId: user.id });
|
|
res.send(pages.renderEmailVerifiedPage());
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.get('/', function (req, res) {
|
|
res.redirect(req.currentUser ? '/dashboard' : '/login');
|
|
});
|
|
|
|
app.get('/login', function (req, res) {
|
|
const returnTo = getReturnTo(req);
|
|
if (req.currentUser) {
|
|
return res.redirect(returnTo || '/dashboard');
|
|
}
|
|
|
|
const message = typeof consumeAuthMessageCookie === 'function'
|
|
? consumeAuthMessageCookie(req, res)
|
|
: (req.query.message ? String(req.query.message) : '');
|
|
fetchAppSettings(pool).then(function (settings) {
|
|
res.send(pages.renderLoginPage(message, returnTo, req.query.username ? String(req.query.username) : '', Boolean(settings['email.smtp_enabled'])));
|
|
}).catch(function (error) {
|
|
res.status(500).send(error.message || 'Unable to load login settings.');
|
|
});
|
|
});
|
|
|
|
app.post('/login', async function (req, res, next) {
|
|
try {
|
|
const username = String(req.body.username || '').trim();
|
|
const password = String(req.body.password || '');
|
|
if (!username || !password) {
|
|
return res.status(400).send('Username and password are required.');
|
|
}
|
|
|
|
const loginRateLimitSettings = await getLoginRateLimitSettings();
|
|
const rateKey = getRateLimitKey(username.toLowerCase(), getClientAddress(req), loginRateLimitSettings.scope);
|
|
const rateLimitStatus = await getLoginRateLimitStatus(rateKey);
|
|
if (rateLimitStatus.limited) {
|
|
if (typeof recordRequestAuditEvent === 'function') {
|
|
await recordRequestAuditEvent(pool, req, {
|
|
category: 'authentication',
|
|
eventType: 'login.locked_out',
|
|
targetType: 'user',
|
|
targetLabel: username,
|
|
details: { reason: 'rate_limit' }
|
|
});
|
|
}
|
|
const message = 'Too many failed login attempts. Try again in ' + rateLimitStatus.remainingMinutes + ' minute' + (rateLimitStatus.remainingMinutes === 1 ? '' : 's') + '.';
|
|
const returnTo = getReturnTo(req);
|
|
if (typeof setAuthMessageCookie === 'function') {
|
|
setAuthMessageCookie(res, message);
|
|
return res.redirect(buildLoginRedirect(returnTo, username));
|
|
}
|
|
return res.status(401).send(pages.renderLoginPage(message, returnTo, username));
|
|
}
|
|
|
|
const [usernameRows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE username = ? LIMIT 1', [username]);
|
|
let user = usernameRows[0] || null;
|
|
if (!user) {
|
|
const [emailRows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE email = ? AND email_verified_at IS NOT NULL LIMIT 1', [username.toLowerCase()]);
|
|
user = emailRows[0] || null;
|
|
}
|
|
if (user && user.account_locked) {
|
|
if (typeof recordRequestAuditEvent === 'function') {
|
|
await recordRequestAuditEvent(pool, req, {
|
|
category: 'security',
|
|
eventType: 'login.blocked_account_locked',
|
|
targetType: 'user',
|
|
targetId: user.id,
|
|
targetLabel: user.username
|
|
});
|
|
}
|
|
const returnTo = getReturnTo(req);
|
|
const message = 'This account is locked. Contact an administrator.';
|
|
if (typeof setAuthMessageCookie === 'function') {
|
|
setAuthMessageCookie(res, message);
|
|
return res.redirect(buildLoginRedirect(returnTo, username));
|
|
}
|
|
return res.status(401).send(pages.renderLoginPage(message, returnTo, username));
|
|
}
|
|
if (!user || !verifyPassword(password, user)) {
|
|
const lockout = await recordFailedLogin(rateKey, loginRateLimitSettings);
|
|
if (typeof recordRequestAuditEvent === 'function') {
|
|
await recordRequestAuditEvent(pool, req, {
|
|
category: 'authentication',
|
|
eventType: lockout ? 'login.lockout' : 'login.failed',
|
|
targetType: user ? 'user' : 'username',
|
|
targetId: user ? user.id : null,
|
|
targetLabel: user ? user.username : username,
|
|
details: { reason: user ? 'invalid_password' : 'unknown_username' }
|
|
});
|
|
}
|
|
const message = lockout
|
|
? 'Too many failed login attempts. Try again in ' + lockout.remainingMinutes + ' minute' + (lockout.remainingMinutes === 1 ? '' : 's') + '.'
|
|
: 'Invalid username or password.';
|
|
const returnTo = getReturnTo(req);
|
|
if (typeof setAuthMessageCookie === 'function') {
|
|
setAuthMessageCookie(res, message);
|
|
return res.redirect(buildLoginRedirect(returnTo, username));
|
|
}
|
|
|
|
return res.status(401).send(pages.renderLoginPage(message, returnTo, username));
|
|
}
|
|
|
|
await clearFailedLogins(rateKey);
|
|
const returnTo = getReturnTo(req);
|
|
const sessionMaxAgeMs = typeof getSessionMaxAgeMs === 'function' ? await getSessionMaxAgeMs() : undefined;
|
|
const token = await createUserSession(pool, user.id, sessionMaxAgeMs, {
|
|
ipAddress: getClientAddress(req),
|
|
userAgent: req.headers && req.headers['user-agent']
|
|
});
|
|
const rememberMe = req.body.remember_me === '1' || req.body.remember_me === 'true' || req.body.remember_me === true;
|
|
setSessionCookie(res, token, rememberMe ? sessionMaxAgeMs : null);
|
|
if (typeof recordRequestAuditEvent === 'function') {
|
|
await recordRequestAuditEvent(pool, req, {
|
|
category: 'authentication',
|
|
eventType: 'login.success',
|
|
actorUserId: user.id,
|
|
targetType: 'user',
|
|
targetId: user.id,
|
|
targetLabel: user.username,
|
|
details: { rememberMe: rememberMe }
|
|
});
|
|
}
|
|
res.redirect(returnTo || '/dashboard');
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
app.get('/logout', async function (req, res, next) {
|
|
try {
|
|
const cookies = parseCookies(req.headers.cookie || '');
|
|
const token = cookies[sessionCookieName];
|
|
if (token) {
|
|
await pool.query('DELETE FROM a_sessions WHERE session_hash = ?', [hashSessionToken(token)]);
|
|
}
|
|
if (typeof recordRequestAuditEvent === 'function' && req.currentUser) {
|
|
await recordRequestAuditEvent(pool, req, {
|
|
category: 'sessions',
|
|
eventType: 'session.logout',
|
|
actorUserId: req.currentUser.id,
|
|
targetType: 'user',
|
|
targetId: req.currentUser.id,
|
|
targetLabel: req.currentUser.username
|
|
});
|
|
}
|
|
clearSessionCookie(res);
|
|
if (typeof setAuthMessageCookie === 'function') {
|
|
setAuthMessageCookie(res, 'You have been signed out.');
|
|
return res.redirect('/login');
|
|
}
|
|
|
|
res.redirect('/login');
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
}; |