Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔒 feat: password reset disable option; fix: account email error message #2327

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ ALLOW_EMAIL_LOGIN=true
ALLOW_REGISTRATION=true
ALLOW_SOCIAL_LOGIN=false
ALLOW_SOCIAL_REGISTRATION=false
ALLOW_PASSWORD_RESET=false
# ALLOW_ACCOUNT_DELETION=true # note: enabled by default if omitted/commented out

SESSION_EXPIRY=1000 * 60 * 15
Expand Down
2 changes: 2 additions & 0 deletions api/server/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const validateMessageReq = require('./validateMessageReq');
const buildEndpointOption = require('./buildEndpointOption');
const validateRegistration = require('./validateRegistration');
const validateImageRequest = require('./validateImageRequest');
const validatePasswordReset = require('./validatePasswordReset');
const moderateText = require('./moderateText');
const noIndex = require('./noIndex');
const importLimiters = require('./importLimiters');
Expand All @@ -40,6 +41,7 @@ module.exports = {
buildEndpointOption,
validateRegistration,
validateImageRequest,
validatePasswordReset,
validateModel,
moderateText,
noIndex,
Expand Down
11 changes: 11 additions & 0 deletions api/server/middleware/validatePasswordReset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const { isEnabled } = require('~/server/utils');

function validatePasswordReset(req, res, next) {
if (isEnabled(process.env.ALLOW_PASSWORD_RESET)) {
next();
} else {
res.status(403).send('Password reset is not allowed.');
}
}

module.exports = validatePasswordReset;
5 changes: 3 additions & 2 deletions api/server/middleware/validateRegistration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { isEnabled } = require('~/server/utils');

function validateRegistration(req, res, next) {
const setting = process.env.ALLOW_REGISTRATION?.toLowerCase();
if (setting === 'true') {
if (isEnabled(process.env.ALLOW_REGISTRATION)) {
next();
} else {
res.status(403).send('Registration is not allowed.');
Expand Down
3 changes: 3 additions & 0 deletions api/server/routes/__tests__/config.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ afterEach(() => {
delete process.env.DOMAIN_SERVER;
delete process.env.ALLOW_REGISTRATION;
delete process.env.ALLOW_SOCIAL_LOGIN;
delete process.env.ALLOW_PASSWORD_RESET;
delete process.env.LDAP_URL;
delete process.env.LDAP_BIND_DN;
delete process.env.LDAP_BIND_CREDENTIALS;
Expand Down Expand Up @@ -55,6 +56,7 @@ describe.skip('GET /', () => {
process.env.DOMAIN_SERVER = 'http://test-server.com';
process.env.ALLOW_REGISTRATION = 'true';
process.env.ALLOW_SOCIAL_LOGIN = 'true';
process.env.ALLOW_PASSWORD_RESET = 'true';
process.env.LDAP_URL = 'Test LDAP URL';
process.env.LDAP_BIND_DN = 'Test LDAP Bind DN';
process.env.LDAP_BIND_CREDENTIALS = 'Test LDAP Bind Credentials';
Expand All @@ -78,6 +80,7 @@ describe.skip('GET /', () => {
serverDomain: 'http://test-server.com',
emailLoginEnabled: 'true',
registrationEnabled: 'true',
passwordResetEnabled: 'true',
socialLoginEnabled: 'true',
});
});
Expand Down
10 changes: 8 additions & 2 deletions api/server/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
requireLdapAuth,
requireLocalAuth,
validateRegistration,
validatePasswordReset,
} = require('../middleware');

const router = express.Router();
Expand All @@ -32,7 +33,12 @@ router.post(
);
router.post('/refresh', refreshController);
router.post('/register', registerLimiter, checkBan, validateRegistration, registrationController);
router.post('/requestPasswordReset', resetPasswordRequestController);
router.post('/resetPassword', resetPasswordController);
router.post(
'/requestPasswordReset',
checkBan,
validatePasswordReset,
resetPasswordRequestController,
);
router.post('/resetPassword', checkBan, validatePasswordReset, resetPasswordController);

module.exports = router;
3 changes: 3 additions & 0 deletions api/server/routes/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const { logger } = require('~/config');
const router = express.Router();
const emailLoginEnabled =
process.env.ALLOW_EMAIL_LOGIN === undefined || isEnabled(process.env.ALLOW_EMAIL_LOGIN);
const passwordResetEnabled =
process.env.ALLOW_PASSWORD_RESET === undefined || isEnabled(process.env.ALLOW_PASSWORD_RESET);

router.get('/', async function (req, res) {
const isBirthday = () => {
Expand Down Expand Up @@ -42,6 +44,7 @@ router.get('/', async function (req, res) {
!!process.env.EMAIL_USERNAME &&
!!process.env.EMAIL_PASSWORD &&
!!process.env.EMAIL_FROM,
passwordResetEnabled,
checkBalance: isEnabled(process.env.CHECK_BALANCE),
showBirthdayIcon:
isBirthday() ||
Expand Down
20 changes: 13 additions & 7 deletions api/server/services/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,20 @@ const registerUser = async (user) => {
*/
const requestPasswordReset = async (email) => {
const user = await User.findOne({ email }).lean();

const emailEnabled =
(!!process.env.EMAIL_SERVICE || !!process.env.EMAIL_HOST) &&
!!process.env.EMAIL_USERNAME &&
!!process.env.EMAIL_PASSWORD &&
!!process.env.EMAIL_FROM;

if (!user && emailEnabled) {
logger.error(`[requestPasswordReset] [Email not found] [Email: ${email}]`);
return { link: '' };
}

if (!user) {
return new Error('Email does not exist');
return new Error('User not found');
}

let token = await Token.findOne({ userId: user._id });
Expand All @@ -140,12 +152,6 @@ const requestPasswordReset = async (email) => {

const link = `${domains.client}/reset-password?token=${resetToken}&userId=${user._id}`;

const emailEnabled =
(!!process.env.EMAIL_SERVICE || !!process.env.EMAIL_HOST) &&
!!process.env.EMAIL_USERNAME &&
!!process.env.EMAIL_PASSWORD &&
!!process.env.EMAIL_FROM;

if (emailEnabled) {
sendEmail(
user.email,
Expand Down
13 changes: 10 additions & 3 deletions client/src/components/Auth/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import { useForm } from 'react-hook-form';
import { useLocalize } from '~/hooks';
import { TLoginUser } from 'librechat-data-provider';
import { useGetStartupConfig } from 'librechat-data-provider/react-query';

type TLoginFormProps = {
onSubmit: (data: TLoginUser) => void;
Expand All @@ -14,6 +15,10 @@ const LoginForm: React.FC<TLoginFormProps> = ({ onSubmit }) => {
handleSubmit,
formState: { errors },
} = useForm<TLoginUser>();
const { data: startupConfig } = useGetStartupConfig();
if (!startupConfig) {
return null;
}

const renderError = (fieldName: string) => {
const errorMessage = errors[fieldName]?.message;
Expand Down Expand Up @@ -81,9 +86,11 @@ const LoginForm: React.FC<TLoginFormProps> = ({ onSubmit }) => {
</div>
{renderError('password')}
</div>
<a href="/forgot-password" className="text-sm text-green-500">
{localize('com_auth_password_forgot')}
</a>
{startupConfig.passwordResetEnabled && (
<a href="/forgot-password" className="text-sm text-green-500">
{localize('com_auth_password_forgot')}
</a>
)}
<div className="mt-6">
<button
aria-label="Sign in"
Expand Down
16 changes: 14 additions & 2 deletions client/src/components/Auth/RequestPasswordReset.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useForm } from 'react-hook-form';
import { useState, useEffect } from 'react';
import { useState, useEffect, ReactNode } from 'react';
import { useOutletContext } from 'react-router-dom';
import { useRequestPasswordResetMutation } from 'librechat-data-provider/react-query';
import type { TRequestPasswordReset, TRequestPasswordResetResponse } from 'librechat-data-provider';
Expand All @@ -14,14 +14,19 @@ function RequestPasswordReset() {
formState: { errors },
} = useForm<TRequestPasswordReset>();
const [resetLink, setResetLink] = useState<string | undefined>(undefined);
const [bodyText, setBodyText] = useState<React.ReactNode | undefined>(undefined);
const [bodyText, setBodyText] = useState<ReactNode | undefined>(undefined);
const { startupConfig, setError, setHeaderText } = useOutletContext<TLoginLayoutContext>();

const requestPasswordReset = useRequestPasswordResetMutation();

const onSubmit = (data: TRequestPasswordReset) => {
requestPasswordReset.mutate(data, {
onSuccess: (data: TRequestPasswordResetResponse) => {
if (data.link === 'User not found') {
setResetLink('User not found');
return;
}

if (!startupConfig?.emailEnabled) {
setResetLink(data.link);
}
Expand All @@ -39,6 +44,7 @@ function RequestPasswordReset() {
if (bodyText) {
return;
}

if (!requestPasswordReset.isSuccess) {
setHeaderText('com_auth_reset_password');
setBodyText(undefined);
Expand All @@ -51,6 +57,11 @@ function RequestPasswordReset() {
return;
}

if (resetLink === 'User not found') {
setError('com_auth_error_reset_password');
return;
}

setHeaderText('com_auth_reset_password');
setBodyText(
<span>
Expand All @@ -68,6 +79,7 @@ function RequestPasswordReset() {
localize,
setHeaderText,
bodyText,
setError,
]);

if (bodyText) {
Expand Down
12 changes: 6 additions & 6 deletions client/src/components/Auth/__tests__/Login.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const setup = ({
user: {},
},
},
useGetStartupCongfigReturnValue = mockStartupConfig,
useGetStartupConfigReturnValue = mockStartupConfig,
} = {}) => {
const mockUseLoginUser = jest
.spyOn(mockDataProvider, 'useLoginUserMutation')
Expand All @@ -64,18 +64,18 @@ const setup = ({
const mockUseGetStartupConfig = jest
.spyOn(mockDataProvider, 'useGetStartupConfig')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useGetStartupCongfigReturnValue);
.mockReturnValue(useGetStartupConfigReturnValue);
const mockUseRefreshTokenMutation = jest
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useRefreshTokenMutationReturnValue);
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
startupConfig: useGetStartupCongfigReturnValue.data,
startupConfig: useGetStartupConfigReturnValue.data,
});
const renderResult = render(
<AuthLayout
startupConfig={useGetStartupCongfigReturnValue.data as TStartupConfig}
isFetching={useGetStartupCongfigReturnValue.isFetching}
startupConfig={useGetStartupConfigReturnValue.data as TStartupConfig}
isFetching={useGetStartupConfigReturnValue.isFetching}
error={null}
startupConfigError={null}
header={'Welcome back'}
Expand Down Expand Up @@ -161,7 +161,7 @@ test('Navigates to / on successful login', async () => {
isError: false,
isSuccess: true,
},
useGetStartupCongfigReturnValue: {
useGetStartupConfigReturnValue: {
...mockStartupConfig,
data: {
...mockStartupConfig.data,
Expand Down
73 changes: 73 additions & 0 deletions client/src/components/Auth/__tests__/LoginForm.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,82 @@
import { render } from 'test/layout-test-utils';
import userEvent from '@testing-library/user-event';
import Login from '../LoginForm';
import * as mockDataProvider from 'librechat-data-provider/react-query';

jest.mock('librechat-data-provider/react-query');

const mockLogin = jest.fn();

const setup = ({
useGetUserQueryReturnValue = {
isLoading: false,
isError: false,
data: {},
},
useLoginUserReturnValue = {
isLoading: false,
isError: false,
mutate: jest.fn(),
data: {},
isSuccess: false,
},
useRefreshTokenMutationReturnValue = {
isLoading: false,
isError: false,
mutate: jest.fn(),
data: {
token: 'mock-token',
user: {},
},
},
useGetStartupConfigReturnValue = {
isLoading: false,
isError: false,
data: {
socialLogins: ['google', 'facebook', 'openid', 'github', 'discord'],
discordLoginEnabled: true,
facebookLoginEnabled: true,
githubLoginEnabled: true,
googleLoginEnabled: true,
openidLoginEnabled: true,
openidLabel: 'Test OpenID',
openidImageUrl: 'http://test-server.com',
registrationEnabled: true,
emailLoginEnabled: true,
socialLoginEnabled: true,
passwordResetEnabled: true,
serverDomain: 'mock-server',
},
},
} = {}) => {
const mockUseLoginUser = jest
.spyOn(mockDataProvider, 'useLoginUserMutation')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useLoginUserReturnValue);
const mockUseGetUserQuery = jest
.spyOn(mockDataProvider, 'useGetUserQuery')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useGetUserQueryReturnValue);
const mockUseGetStartupConfig = jest
.spyOn(mockDataProvider, 'useGetStartupConfig')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useGetStartupConfigReturnValue);
const mockUseRefreshTokenMutation = jest
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useRefreshTokenMutationReturnValue);
return {
mockUseLoginUser,
mockUseGetUserQuery,
mockUseGetStartupConfig,
mockUseRefreshTokenMutation,
};
};

beforeEach(() => {
setup();
});

test('renders login form', () => {
const { getByLabelText } = render(<Login onSubmit={mockLogin} />);
expect(getByLabelText(/email/i)).toBeInTheDocument();
Expand Down
10 changes: 5 additions & 5 deletions client/src/components/Auth/__tests__/Registration.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const setup = ({
user: {},
},
},
useGetStartupCongfigReturnValue = mockStartupConfig,
useGetStartupConfigReturnValue = mockStartupConfig,
} = {}) => {
const mockUseRegisterUserMutation = jest
.spyOn(mockDataProvider, 'useRegisterUserMutation')
Expand All @@ -63,18 +63,18 @@ const setup = ({
const mockUseGetStartupConfig = jest
.spyOn(mockDataProvider, 'useGetStartupConfig')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useGetStartupCongfigReturnValue);
.mockReturnValue(useGetStartupConfigReturnValue);
const mockUseRefreshTokenMutation = jest
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
.mockReturnValue(useRefreshTokenMutationReturnValue);
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
startupConfig: useGetStartupCongfigReturnValue.data,
startupConfig: useGetStartupConfigReturnValue.data,
});
const renderResult = render(
<AuthLayout
startupConfig={useGetStartupCongfigReturnValue.data as TStartupConfig}
isFetching={useGetStartupCongfigReturnValue.isFetching}
startupConfig={useGetStartupConfigReturnValue.data as TStartupConfig}
isFetching={useGetStartupConfigReturnValue.isFetching}
error={null}
startupConfigError={null}
header={'Create your account'}
Expand Down