Skip to content

Commit

Permalink
🚀 refactor: Remove Local Login Redundancies (#3002)
Browse files Browse the repository at this point in the history
  • Loading branch information
danny-avila authored Jun 7, 2024
1 parent 35f8053 commit 1da9211
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 30 deletions.
30 changes: 4 additions & 26 deletions api/server/controllers/auth/LoginController.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
const { setAuthTokens } = require('~/server/services/AuthService');
const { getUserById, updateUser } = require('~/models/userMethods');
const { isEnabled, checkEmailConfig } = require('~/server/utils');
const { logger } = require('~/config');

// Unix timestamp for 2024-06-07 15:20:18 Eastern Time
const verificationEnabledTimestamp = 1717788018;

const loginController = async (req, res) => {
try {
const user = await getUserById(req.user._id, '-password -__v');

// If user doesn't exist, return error
if (!user) {
if (!req.user) {
return res.status(400).json({ message: 'Invalid credentials' });
}

const emailEnabled = checkEmailConfig();
const userCreatedAtTimestamp = Math.floor(new Date(user.createdAt).getTime() / 1000);
const { password: _, __v, ...user } = req.user;
user.id = user._id.toString();

if (
!emailEnabled &&
!user.emailVerified &&
userCreatedAtTimestamp < verificationEnabledTimestamp
) {
await updateUser(user._id, { emailVerified: true });
user.emailVerified = true;
}

if (!user.emailVerified && !isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN)) {
return res.status(422).json({ message: 'Email not verified' });
}

const token = await setAuthTokens(user._id, res);
const token = await setAuthTokens(req.user._id, res);

return res.status(200).send({ token, user });
} catch (err) {
logger.error('[loginController]', err);

return res.status(500).json({ message: 'Something went wrong' });
}
};
Expand Down
2 changes: 1 addition & 1 deletion api/server/services/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ const resetPassword = async (userId, token, password) => {
/**
* Set Auth Tokens
*
* @param {String} userId
* @param {String | ObjectId} userId
* @param {Object} res
* @param {String} sessionId
* @returns
Expand Down
2 changes: 1 addition & 1 deletion api/strategies/jwtStrategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const jwtLogin = async () =>
},
async (payload, done) => {
try {
const user = await getUserById(payload?.id);
const user = await getUserById(payload?.id, '-password -__v');
user.id = user._id.toString();
if (user) {
done(null, user);
Expand Down
19 changes: 17 additions & 2 deletions api/strategies/localStrategy.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
const { errorsToString } = require('librechat-data-provider');
const { Strategy: PassportLocalStrategy } = require('passport-local');
const { findUser, comparePassword } = require('~/models');
const { findUser, comparePassword, updateUser } = require('~/models');
const { isEnabled, checkEmailConfig } = require('~/server/utils');
const { loginSchema } = require('./validators');
const { isEnabled } = require('~/server/utils');
const logger = require('~/utils/logger');

// Unix timestamp for 2024-06-07 15:20:18 Eastern Time
const verificationEnabledTimestamp = 1717788018;

async function validateLoginRequest(req) {
const { error } = loginSchema.safeParse(req.body);
return error ? errorsToString(error.errors) : null;
Expand Down Expand Up @@ -33,6 +36,18 @@ async function passportLogin(req, email, password, done) {
return done(null, false, { message: 'Incorrect password.' });
}

const emailEnabled = checkEmailConfig();
const userCreatedAtTimestamp = Math.floor(new Date(user.createdAt).getTime() / 1000);

if (
!emailEnabled &&
!user.emailVerified &&
userCreatedAtTimestamp < verificationEnabledTimestamp
) {
await updateUser(user._id, { emailVerified: true });
user.emailVerified = true;
}

if (!user.emailVerified && !isEnabled(process.env.ALLOW_UNVERIFIED_EMAIL_LOGIN)) {
logError('Passport Local Strategy - Email not verified', { email });
logger.error(`[Login] [Login failed] [Username: ${email}] [Request-IP: ${req.ip}]`);
Expand Down

0 comments on commit 1da9211

Please sign in to comment.