Fix 2FA
This commit is contained in:
@@ -8,8 +8,8 @@ import { HttpError } from '../middleware/errorHandler.js';
|
||||
import { sendMail, buildEmailHtml, getSmtpConfig } from '../utils/mailer.js';
|
||||
import { createRequire } from 'node:module';
|
||||
const _require = createRequire(import.meta.url);
|
||||
const { authenticator } = _require('otplib');
|
||||
const QRCode = _require('qrcode');
|
||||
import { generateSecret as totpGenerateSecret, generateURI as totpGenerateURI, verifySync as totpVerifySync } from 'otplib';
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -374,13 +374,13 @@ router.get('/2fa/setup', requireAuth, async (req, res, next) => {
|
||||
const user = db.prepare('SELECT id, email, totp_secret, totp_enabled FROM users WHERE id=?').get(req.user.id);
|
||||
|
||||
// Générer un nouveau secret (ou réutiliser si setup pas encore confirmé)
|
||||
const secret = (user.totp_enabled ? null : user.totp_secret) || authenticator.generateSecret();
|
||||
const secret = (user.totp_enabled ? null : user.totp_secret) || totpGenerateSecret();
|
||||
|
||||
if (!user.totp_enabled) {
|
||||
db.prepare("UPDATE users SET totp_secret=? WHERE id=?").run(secret, req.user.id);
|
||||
}
|
||||
|
||||
const uri = authenticator.keyuri(user.email, issuer, secret);
|
||||
const uri = totpGenerateURI({ issuer, label: user.email, secret });
|
||||
const qrCode = await QRCode.toDataURL(uri);
|
||||
|
||||
res.json({ secret, qrCode, issuer, email: user.email, totp_enabled: !!user.totp_enabled });
|
||||
@@ -394,9 +394,7 @@ router.post('/2fa/confirm-setup', requireAuth, async (req, res, next) => {
|
||||
const user = db.prepare('SELECT totp_secret, totp_enabled FROM users WHERE id=?').get(req.user.id);
|
||||
if (!user.totp_secret) throw new HttpError(400, 'Lancez d\'abord la configuration 2FA.');
|
||||
if (user.totp_enabled) throw new HttpError(400, 'Le 2FA est déjà activé.');
|
||||
|
||||
authenticator.options = { window: 1 };
|
||||
const valid = authenticator.verify({ token: code, secret: user.totp_secret });
|
||||
const valid = totpVerifySync({ token: code, secret: user.totp_secret, strategy: "totp" });
|
||||
if (!valid) throw new HttpError(400, 'Code invalide. Réessayez.');
|
||||
|
||||
db.prepare("UPDATE users SET totp_enabled=1 WHERE id=?").run(req.user.id);
|
||||
@@ -484,8 +482,7 @@ router.post('/2fa/verify', async (req, res, next) => {
|
||||
const user = db.prepare('SELECT id, email, display_name, role, totp_secret, totp_enabled FROM users WHERE id=?').get(sess.user_id);
|
||||
|
||||
if (method === 'totp') {
|
||||
authenticator.options = { window: 1 };
|
||||
const valid = authenticator.verify({ token: code, secret: user.totp_secret });
|
||||
const valid = totpVerifySync({ token: code, secret: user.totp_secret, strategy: "totp" });
|
||||
if (!valid) throw new HttpError(400, 'Code invalide.');
|
||||
} else {
|
||||
// Email OTP
|
||||
|
||||
Reference in New Issue
Block a user