mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 08:50:15 +01:00
🔐 fix: Invalid Key Length in 2FA Encryption (#6432)
* 🚀 feat: Implement v3 encryption and decryption methods for TOTP secrets * 🚀 feat: Refactor Two-Factor Authentication methods and enhance 2FA verification process * 🚀 feat: Update encryption methods to use hex decoding for legacy keys and improve error handling for AES-256-CTR * 🚀 feat: Update import paths in TwoFactorController for consistency and clarity
This commit is contained in:
parent
692fba51d8
commit
e768a07738
5 changed files with 192 additions and 179 deletions
|
|
@ -8,7 +8,10 @@ const { setAuthTokens } = require('~/server/services/AuthService');
|
|||
const { getUserById } = require('~/models/userMethods');
|
||||
const { logger } = require('~/config');
|
||||
|
||||
const verify2FA = async (req, res) => {
|
||||
/**
|
||||
* Verifies the 2FA code during login using a temporary token.
|
||||
*/
|
||||
const verify2FAWithTempToken = async (req, res) => {
|
||||
try {
|
||||
const { tempToken, token, backupCode } = req.body;
|
||||
if (!tempToken) {
|
||||
|
|
@ -23,26 +26,23 @@ const verify2FA = async (req, res) => {
|
|||
}
|
||||
|
||||
const user = await getUserById(payload.userId);
|
||||
// Ensure that the user exists and has 2FA enabled
|
||||
if (!user || !user.twoFactorEnabled) {
|
||||
return res.status(400).json({ message: '2FA is not enabled for this user' });
|
||||
}
|
||||
|
||||
// Retrieve (and decrypt if necessary) the TOTP secret.
|
||||
const secret = await getTOTPSecret(user.totpSecret);
|
||||
|
||||
let verified = false;
|
||||
if (token && (await verifyTOTP(secret, token))) {
|
||||
verified = true;
|
||||
let isVerified = false;
|
||||
if (token) {
|
||||
isVerified = await verifyTOTP(secret, token);
|
||||
} else if (backupCode) {
|
||||
verified = await verifyBackupCode({ user, backupCode });
|
||||
isVerified = await verifyBackupCode({ user, backupCode });
|
||||
}
|
||||
|
||||
if (!verified) {
|
||||
if (!isVerified) {
|
||||
return res.status(401).json({ message: 'Invalid 2FA code or backup code' });
|
||||
}
|
||||
|
||||
// Prepare user data for response.
|
||||
// Prepare user data to return (omit sensitive fields).
|
||||
const userData = user.toObject ? user.toObject() : { ...user };
|
||||
delete userData.password;
|
||||
delete userData.__v;
|
||||
|
|
@ -52,9 +52,9 @@ const verify2FA = async (req, res) => {
|
|||
const authToken = await setAuthTokens(user._id, res);
|
||||
return res.status(200).json({ token: authToken, user: userData });
|
||||
} catch (err) {
|
||||
logger.error('[verify2FA]', err);
|
||||
logger.error('[verify2FAWithTempToken]', err);
|
||||
return res.status(500).json({ message: 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { verify2FA };
|
||||
module.exports = { verify2FAWithTempToken };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue