initial commit
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
237
src/routes/admin/totp.ts
Normal file
237
src/routes/admin/totp.ts
Normal file
@@ -0,0 +1,237 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import crypto from 'crypto';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import prisma from '../../config/database';
|
||||
import { requireAuth, requirePermission } from '../../middleware/auth';
|
||||
import { success, error } from '../../utils/response';
|
||||
import { encrypt } from '../../utils/encryption';
|
||||
import { OTPAuth } from '../../utils/totp';
|
||||
import * as OTPAuthLib from 'otpauth';
|
||||
import { logAudit } from '../../services/audit';
|
||||
|
||||
export default async function totpRoutes(fastify: FastifyInstance): Promise<void> {
|
||||
// GET - generate new TOTP secret
|
||||
fastify.get('/setup', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const secret = new OTPAuthLib.Secret();
|
||||
const totp = new OTPAuthLib.TOTP({
|
||||
issuer: 'BOHA Automation',
|
||||
label: request.authData!.email,
|
||||
secret,
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
});
|
||||
|
||||
return success(reply, {
|
||||
secret: secret.base32,
|
||||
uri: totp.toString(),
|
||||
});
|
||||
});
|
||||
|
||||
// POST - enable TOTP
|
||||
fastify.post('/enable', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const body = request.body as Record<string, unknown>;
|
||||
const { secret, code } = body;
|
||||
|
||||
if (!secret || !code) {
|
||||
return error(reply, 'Secret a kód jsou povinné', 400);
|
||||
}
|
||||
|
||||
// Verify the code first
|
||||
const totp = new OTPAuthLib.TOTP({
|
||||
secret: OTPAuthLib.Secret.fromBase32(String(secret)),
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
});
|
||||
|
||||
const delta = totp.validate({ token: String(code), window: 1 });
|
||||
if (delta === null) {
|
||||
return error(reply, 'Neplatný TOTP kód', 400);
|
||||
}
|
||||
|
||||
// Generate 8 backup codes
|
||||
const backupCodesPlain: string[] = [];
|
||||
const backupCodesHashed: string[] = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const code = crypto.randomBytes(4).toString('hex').toUpperCase();
|
||||
backupCodesPlain.push(code);
|
||||
backupCodesHashed.push(bcrypt.hashSync(code, 10));
|
||||
}
|
||||
|
||||
// Encrypt and store
|
||||
const encryptedSecret = encrypt(String(secret));
|
||||
await prisma.users.update({
|
||||
where: { id: request.authData!.userId },
|
||||
data: {
|
||||
totp_secret: encryptedSecret,
|
||||
totp_enabled: true,
|
||||
totp_backup_codes: JSON.stringify(backupCodesHashed),
|
||||
},
|
||||
});
|
||||
|
||||
await logAudit({ request, authData: request.authData, action: 'update', entityType: 'user', entityId: request.authData!.userId, description: '2FA aktivováno' });
|
||||
return success(reply, { backup_codes: backupCodesPlain }, 200, '2FA aktivováno');
|
||||
});
|
||||
|
||||
// PUT - disable TOTP
|
||||
fastify.put('/disable', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
if (!body.code) {
|
||||
return error(reply, 'TOTP kód je povinný pro deaktivaci', 400);
|
||||
}
|
||||
|
||||
const user = await prisma.users.findUnique({ where: { id: request.authData!.userId } });
|
||||
if (!user?.totp_secret) {
|
||||
return error(reply, '2FA není aktivní', 400);
|
||||
}
|
||||
|
||||
const isValid = OTPAuth.verify(user.totp_secret, String(body.code));
|
||||
if (!isValid) {
|
||||
return error(reply, 'Neplatný TOTP kód', 400);
|
||||
}
|
||||
|
||||
await prisma.users.update({
|
||||
where: { id: request.authData!.userId },
|
||||
data: { totp_secret: null, totp_enabled: false, totp_backup_codes: null },
|
||||
});
|
||||
|
||||
await logAudit({ request, authData: request.authData, action: 'update', entityType: 'user', entityId: request.authData!.userId, description: '2FA deaktivováno' });
|
||||
return success(reply, null, 200, '2FA deaktivováno');
|
||||
});
|
||||
|
||||
// GET - TOTP status for current user
|
||||
fastify.get('/status', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const user = await prisma.users.findUnique({
|
||||
where: { id: request.authData!.userId },
|
||||
select: { totp_enabled: true },
|
||||
});
|
||||
|
||||
return success(reply, { totp_enabled: user?.totp_enabled ?? false });
|
||||
});
|
||||
|
||||
// GET - check if 2FA is required company-wide
|
||||
fastify.get('/required', { preHandler: [requireAuth, requirePermission('settings.security')] }, async (request, reply) => {
|
||||
const settings = await prisma.company_settings.findFirst({
|
||||
select: { require_2fa: true },
|
||||
});
|
||||
|
||||
return success(reply, { require_2fa: settings?.require_2fa ?? false });
|
||||
});
|
||||
|
||||
// POST - toggle mandatory 2FA
|
||||
fastify.post('/required', { preHandler: [requireAuth, requirePermission('settings.security')] }, async (request, reply) => {
|
||||
const body = request.body as Record<string, unknown>;
|
||||
|
||||
const required = body.required === true || body.required === 1 || body.required === '1';
|
||||
await prisma.company_settings.updateMany({
|
||||
data: { require_2fa: required },
|
||||
});
|
||||
|
||||
const message = required
|
||||
? '2FA je nyní povinné pro všechny uživatele'
|
||||
: '2FA již není povinné';
|
||||
|
||||
return success(reply, null, 200, message);
|
||||
});
|
||||
|
||||
// POST - verify backup code (pre-auth, no requireAuth)
|
||||
fastify.post('/backup-verify', async (request, reply) => {
|
||||
const body = request.body as Record<string, unknown>;
|
||||
const { login_token, code } = body;
|
||||
|
||||
if (!login_token || !code) {
|
||||
return error(reply, 'Login token a záložní kód jsou povinné', 400);
|
||||
}
|
||||
|
||||
const tokenHash = crypto.createHash('sha256').update(String(login_token)).digest('hex');
|
||||
|
||||
const storedToken = await prisma.totp_login_tokens.findFirst({
|
||||
where: { token_hash: tokenHash },
|
||||
});
|
||||
|
||||
if (!storedToken || new Date(storedToken.expires_at) < new Date()) {
|
||||
return error(reply, 'Neplatný nebo expirovaný login token', 401);
|
||||
}
|
||||
|
||||
const user = await prisma.users.findUnique({
|
||||
where: { id: storedToken.user_id },
|
||||
include: { roles: true },
|
||||
});
|
||||
|
||||
if (!user || !user.totp_backup_codes) {
|
||||
return error(reply, 'Uživatel nenalezen', 401);
|
||||
}
|
||||
|
||||
const backupCodes: string[] = JSON.parse(user.totp_backup_codes as string);
|
||||
let matchIndex = -1;
|
||||
|
||||
for (let i = 0; i < backupCodes.length; i++) {
|
||||
const isMatch = await bcrypt.compare(String(code), backupCodes[i]);
|
||||
if (isMatch) {
|
||||
matchIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (matchIndex === -1) {
|
||||
return error(reply, 'Neplatný záložní kód', 401);
|
||||
}
|
||||
|
||||
// Remove used backup code
|
||||
backupCodes.splice(matchIndex, 1);
|
||||
await prisma.users.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
totp_backup_codes: JSON.stringify(backupCodes),
|
||||
failed_login_attempts: 0,
|
||||
locked_until: null,
|
||||
last_login: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
// Delete used login token
|
||||
await prisma.totp_login_tokens.delete({ where: { id: storedToken.id } });
|
||||
|
||||
// Create tokens (same as /login/totp flow)
|
||||
const { loadAuthData } = await import('../../services/auth');
|
||||
const authData = await loadAuthData(user.id);
|
||||
if (!authData) {
|
||||
return error(reply, 'Chyba načítání uživatele', 500);
|
||||
}
|
||||
|
||||
const jwt = await import('jsonwebtoken');
|
||||
const { config } = await import('../../config/env');
|
||||
|
||||
const accessToken = jwt.default.sign(
|
||||
{ sub: user.id, username: user.username, role: user.roles?.name ?? null },
|
||||
config.jwt.secret,
|
||||
{ expiresIn: config.jwt.accessTokenExpiry },
|
||||
);
|
||||
|
||||
const refreshTokenRaw = crypto.randomBytes(32).toString('hex');
|
||||
const refreshTokenHash = crypto.createHash('sha256').update(refreshTokenRaw).digest('hex');
|
||||
|
||||
await prisma.refresh_tokens.create({
|
||||
data: {
|
||||
user_id: user.id,
|
||||
token_hash: refreshTokenHash,
|
||||
expires_at: new Date(Date.now() + config.jwt.refreshTokenSessionExpiry * 1000),
|
||||
remember_me: false,
|
||||
ip_address: request.ip,
|
||||
user_agent: request.headers['user-agent'] ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
reply.setCookie('refresh_token', refreshTokenRaw, {
|
||||
httpOnly: true,
|
||||
secure: config.isProduction,
|
||||
sameSite: 'strict',
|
||||
path: '/api/admin',
|
||||
maxAge: config.jwt.refreshTokenSessionExpiry,
|
||||
});
|
||||
|
||||
return success(reply, { access_token: accessToken, user: authData });
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user