Release 2.8.0
This commit is contained in:
+147
-12
@@ -1,12 +1,14 @@
|
||||
// Authentication route registration for the web app.
|
||||
|
||||
const { normalizeReturnToPath, getRequestOrigin } = require('../../lib/auth/session');
|
||||
const { fetchAppSettings } = require('../../../data/app-settings');
|
||||
|
||||
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;
|
||||
@@ -14,13 +16,65 @@ module.exports = function registerAuthRoutes(app, deps) {
|
||||
const hashSessionToken = deps.hashSessionToken;
|
||||
const verifyPassword = deps.verifyPassword;
|
||||
const sessionCookieName = deps.sessionCookieName;
|
||||
const recordRequestAuditEvent = deps.recordRequestAuditEvent;
|
||||
|
||||
function getReturnTo(req) {
|
||||
return normalizeReturnToPath(req && (req.query && req.query.returnTo || req.body && req.body.returnTo), getRequestOrigin(req));
|
||||
}
|
||||
|
||||
function buildLoginRedirect(returnTo) {
|
||||
return returnTo ? '/login?returnTo=' + encodeURIComponent(returnTo) : '/login';
|
||||
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]);
|
||||
}
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
@@ -36,7 +90,7 @@ module.exports = function registerAuthRoutes(app, deps) {
|
||||
const message = typeof consumeAuthMessageCookie === 'function'
|
||||
? consumeAuthMessageCookie(req, res)
|
||||
: (req.query.message ? String(req.query.message) : '');
|
||||
res.send(pages.renderLoginPage(message, returnTo));
|
||||
res.send(pages.renderLoginPage(message, returnTo, req.query.username ? String(req.query.username) : ''));
|
||||
});
|
||||
|
||||
app.post('/login', async function (req, res, next) {
|
||||
@@ -47,21 +101,92 @@ module.exports = function registerAuthRoutes(app, deps) {
|
||||
return res.status(400).send('Username and password are required.');
|
||||
}
|
||||
|
||||
const [rows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations FROM a_users WHERE username = ? LIMIT 1', [username]);
|
||||
const user = rows[0] || null;
|
||||
if (!user || !verifyPassword(password, user)) {
|
||||
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, 'Invalid username or password.');
|
||||
return res.redirect(buildLoginRedirect(returnTo));
|
||||
setAuthMessageCookie(res, message);
|
||||
return res.redirect(buildLoginRedirect(returnTo, username));
|
||||
}
|
||||
|
||||
return res.status(401).send(pages.renderLoginPage('Invalid username or password.', returnTo));
|
||||
return res.status(401).send(pages.renderLoginPage(message, returnTo, username));
|
||||
}
|
||||
|
||||
const [rows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE username = ? LIMIT 1', [username]);
|
||||
const user = rows[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 token = await createUserSession(pool, user.id);
|
||||
setSessionCookie(res, token);
|
||||
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);
|
||||
@@ -75,6 +200,16 @@ module.exports = function registerAuthRoutes(app, deps) {
|
||||
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.');
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
const { renderView } = require('../../view');
|
||||
|
||||
module.exports = function renderLoginPage(message, returnTo) {
|
||||
module.exports = function renderLoginPage(message, returnTo, username) {
|
||||
return renderView('auth/login', {
|
||||
title: 'Sign in',
|
||||
authShell: true,
|
||||
bodyClass: 'login-page-body',
|
||||
message: message || '',
|
||||
returnTo: returnTo || '',
|
||||
username: username || '',
|
||||
messageVariant: 'warning'
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user