r2
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
'use strict';
|
||||
|
||||
const bcrypt = require('bcryptjs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const crypto = require('crypto');
|
||||
const { AppError } = require('../../core/errors');
|
||||
const { log: auditLog } = require('../../core/audit');
|
||||
|
||||
// Per-username brute force tracking (process memory)
|
||||
const failureMap = new Map(); // username → { count, resetAt }
|
||||
const MAX_FAILURES = 10;
|
||||
const LOCKOUT_MS = 15 * 60 * 1000;
|
||||
|
||||
function checkLockout(username) {
|
||||
const entry = failureMap.get(username);
|
||||
if (!entry) return;
|
||||
if (Date.now() > entry.resetAt) { failureMap.delete(username); return; }
|
||||
if (entry.count >= MAX_FAILURES) {
|
||||
throw new AppError('LOGIN_FAILED', 'Invalid username or password.', 401);
|
||||
}
|
||||
}
|
||||
|
||||
function recordFailure(username) {
|
||||
const entry = failureMap.get(username) || { count: 0, resetAt: Date.now() + LOCKOUT_MS };
|
||||
entry.count++;
|
||||
failureMap.set(username, entry);
|
||||
}
|
||||
|
||||
function clearFailures(username) {
|
||||
failureMap.delete(username);
|
||||
}
|
||||
|
||||
function signJwt(user) {
|
||||
return jwt.sign(
|
||||
{ id: user.id, username: user.username, role: user.role, organizationId: user.organizationId },
|
||||
process.env.JWT_SECRET,
|
||||
{ algorithm: 'HS256', expiresIn: '7d' }
|
||||
);
|
||||
}
|
||||
|
||||
function hashToken(rawToken) {
|
||||
return crypto.createHash('sha256').update(rawToken).digest('hex');
|
||||
}
|
||||
|
||||
async function createDeviceToken(models, userId, orgId, deviceName, deviceType) {
|
||||
const rawToken = crypto.randomBytes(32).toString('hex');
|
||||
const ttlDays = deviceType === 'kiosk' ? 90 : 30;
|
||||
const expiresAt = new Date(Date.now() + ttlDays * 24 * 60 * 60 * 1000);
|
||||
|
||||
const record = await models.DeviceToken.create({
|
||||
userId,
|
||||
organizationId: orgId,
|
||||
token: hashToken(rawToken),
|
||||
deviceName: deviceName || 'Unknown device',
|
||||
deviceType: deviceType || 'personal',
|
||||
expiresAt,
|
||||
lastUsedAt: new Date(),
|
||||
});
|
||||
|
||||
return { rawToken, record };
|
||||
}
|
||||
|
||||
async function login(models, req, { username, password, rememberDevice, deviceName, deviceType }) {
|
||||
checkLockout(username);
|
||||
|
||||
const user = await models.User.findOne({
|
||||
where: { username },
|
||||
attributes: ['id', 'username', 'email', 'role', 'organizationId', 'isActive', 'password'],
|
||||
});
|
||||
|
||||
const valid = user && user.isActive && await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!valid) {
|
||||
recordFailure(username);
|
||||
throw new AppError('LOGIN_FAILED', 'Invalid username or password.', 401);
|
||||
}
|
||||
|
||||
clearFailures(username);
|
||||
|
||||
await user.update({ lastLoginAt: new Date() });
|
||||
|
||||
const token = signJwt(user);
|
||||
let deviceToken;
|
||||
|
||||
if (rememberDevice) {
|
||||
const { rawToken } = await createDeviceToken(models, user.id, user.organizationId, deviceName, deviceType);
|
||||
deviceToken = rawToken;
|
||||
}
|
||||
|
||||
const userPublic = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId };
|
||||
|
||||
await auditLog(req, 'auth.login.success', 'user', user.id, { username });
|
||||
|
||||
return { jwt: token, user: userPublic, ...(deviceToken ? { deviceToken } : {}) };
|
||||
}
|
||||
|
||||
async function deviceLogin(models, req, rawToken) {
|
||||
const hash = hashToken(rawToken);
|
||||
const record = await models.DeviceToken.findOne({ where: { token: hash } });
|
||||
|
||||
if (!record || record.isRevoked || record.expiresAt < new Date()) {
|
||||
throw new AppError('AUTH_DEVICE_TOKEN_INVALID', 'Device token is invalid or expired.', 401);
|
||||
}
|
||||
|
||||
const user = await models.User.findByPk(record.userId, {
|
||||
attributes: ['id', 'username', 'role', 'organizationId', 'isActive'],
|
||||
});
|
||||
|
||||
if (!user || !user.isActive) {
|
||||
throw new AppError('AUTH_DEVICE_TOKEN_INVALID', 'Device token is invalid or expired.', 401);
|
||||
}
|
||||
|
||||
// Rotate token
|
||||
await record.update({ isRevoked: true });
|
||||
const { rawToken: newRaw } = await createDeviceToken(
|
||||
models, user.id, user.organizationId, record.deviceName, record.deviceType
|
||||
);
|
||||
|
||||
await user.update({ lastLoginAt: new Date() });
|
||||
|
||||
const token = signJwt(user);
|
||||
await auditLog(req, 'auth.token.refreshed', 'user', user.id, {});
|
||||
|
||||
const userPublic = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId };
|
||||
return { jwt: token, deviceToken: newRaw, user: userPublic };
|
||||
}
|
||||
|
||||
async function refreshToken(models, userId) {
|
||||
const user = await models.User.findByPk(userId, {
|
||||
attributes: ['id', 'username', 'role', 'organizationId', 'isActive'],
|
||||
});
|
||||
if (!user || !user.isActive) {
|
||||
throw new AppError('AUTH_INVALID', 'User not found.', 401);
|
||||
}
|
||||
return { jwt: signJwt(user) };
|
||||
}
|
||||
|
||||
module.exports = { login, deviceLogin, refreshToken };
|
||||
Reference in New Issue
Block a user