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 8 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 @@ -282,6 +282,7 @@ ALLOW_EMAIL_LOGIN=true
ALLOW_REGISTRATION=true
ALLOW_SOCIAL_LOGIN=false
ALLOW_SOCIAL_REGISTRATION=false
ALLOW_PASSWORD_RESET=false

SESSION_EXPIRY=1000 * 60 * 15
REFRESH_TOKEN_EXPIRY=(1000 * 60 * 60 * 24) * 7
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 @@ -14,6 +14,7 @@ const concurrentLimiter = require('./concurrentLimiter');
const validateMessageReq = require('./validateMessageReq');
const buildEndpointOption = require('./buildEndpointOption');
const validateRegistration = require('./validateRegistration');
const validatePasswordReset = require('./validatePasswordReset');
const validateImageRequest = require('./validateImageRequest');
const moderateText = require('./moderateText');
const noIndex = require('./noIndex');
Expand All @@ -34,6 +35,7 @@ module.exports = {
validateMessageReq,
buildEndpointOption,
validateRegistration,
validatePasswordReset,
validateImageRequest,
validateModel,
moderateText,
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;
});

//TODO: This works/passes locally but http request tests fail with 404 in CI. Need to figure out why.
Expand All @@ -50,6 +51,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';

const response = await request(app).get('/');

Expand All @@ -67,6 +69,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 @@ -14,6 +14,7 @@ const {
requireJwtAuth,
requireLocalAuth,
validateRegistration,
validatePasswordReset,
} = require('../middleware');

const router = express.Router();
Expand All @@ -23,7 +24,12 @@ router.post('/logout', requireJwtAuth, logoutController);
router.post('/login', loginLimiter, checkBan, requireLocalAuth, loginController);
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 @@ -38,6 +40,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
2 changes: 1 addition & 1 deletion api/server/services/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ const registerUser = async (user) => {
const requestPasswordReset = async (email) => {
const user = await User.findOne({ email }).lean();
if (!user) {
return new Error('Email does not exist');
return { link: 'noUserFound' };
}

let token = await Token.findOne({ userId: user._id });
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 font-medium text-green-500">
{localize('com_auth_password_forgot')}
</a>
{startupConfig.passwordResetEnabled && (
<a href="/forgot-password" className="text-sm font-medium text-green-500">
{localize('com_auth_password_forgot')}
</a>
)}
<div className="mt-6">
<button
aria-label="Sign in"
Expand Down
49 changes: 31 additions & 18 deletions client/src/components/Auth/RequestPasswordReset.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ function RequestPasswordReset() {
const onSubmit = (data: TRequestPasswordReset) => {
requestPasswordReset.mutate(data, {
onSuccess: (data: TRequestPasswordResetResponse) => {
console.log('emailEnabled: ', config.data?.emailEnabled);
if (data.link === 'noUserFound') {
setResetLink('noUserFound');
return;
}

if (!config.data?.emailEnabled) {
setResetLink(data.link);
}
Expand All @@ -40,25 +44,34 @@ function RequestPasswordReset() {
};

useEffect(() => {
if (requestPasswordReset.isSuccess) {
if (config.data?.emailEnabled) {
setHeaderText(localize('com_auth_reset_password_link_sent'));
setBodyText(localize('com_auth_reset_password_email_sent'));
} else {
setHeaderText(localize('com_auth_reset_password'));
setBodyText(
<span>
{localize('com_auth_click')}{' '}
<a className="font-medium text-green-500 hover:underline" href={resetLink}>
{localize('com_auth_here')}
</a>{' '}
{localize('com_auth_to_reset_your_password')}
</span>,
);
}
} else {
if (!requestPasswordReset.isSuccess) {
setHeaderText(localize('com_auth_reset_password'));
setBodyText(undefined);
return;
}

if (config.data?.emailEnabled) {
setHeaderText(localize('com_auth_reset_password_link_sent'));
setBodyText(localize('com_auth_reset_password_email_sent'));
return;
}

if (resetLink === 'noUserFound') {
setRequestError(true);
return;
}

if (resetLink) {
setHeaderText(localize('com_auth_reset_password'));
setBodyText(
<span>
{localize('com_auth_click')}{' '}
<a className="font-medium text-green-500 hover:underline" href={resetLink}>
{localize('com_auth_here')}
</a>{' '}
{localize('com_auth_to_reset_your_password')}
</span>,
);
}
}, [requestPasswordReset.isSuccess, config.data?.emailEnabled, resetLink, localize]);

Expand Down
5 changes: 3 additions & 2 deletions client/src/components/Auth/__tests__/Login.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const setup = ({
user: {},
},
},
useGetStartupCongfigReturnValue = {
useGetStartupConfigReturnValue = {
isLoading: false,
isError: false,
data: {
Expand All @@ -42,6 +42,7 @@ const setup = ({
registrationEnabled: true,
emailLoginEnabled: true,
socialLoginEnabled: true,
passwordResetEnabled: true,
serverDomain: 'mock-server',
},
},
Expand All @@ -57,7 +58,7 @@ 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
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
7 changes: 3 additions & 4 deletions client/src/localization/languages/Eng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,10 @@ export default {
com_auth_click: 'Click',
com_auth_here: 'HERE',
com_auth_to_reset_your_password: 'to reset your password.',
com_auth_reset_password_link_sent: 'Email Sent',
com_auth_reset_password_link_sent: 'Password Reset',
com_auth_reset_password_email_sent:
'An email has been sent to you with further instructions to reset your password.',
com_auth_error_reset_password:
'There was a problem resetting your password. There was no user found with the email address provided. Please try again.',
'If the user is registered, an email will be sent to the inbox.',
com_auth_error_reset_password: 'Something went wrong',
com_auth_reset_password_success: 'Password Reset Success',
com_auth_login_with_new_password: 'You may now login with your new password.',
com_auth_error_invalid_reset_token: 'This password reset token is no longer valid.',
Expand Down
4 changes: 3 additions & 1 deletion docs/install/configuration/dotenv.md
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,8 @@ see: **[User/Auth System](./user_auth_system.md)**
- `ALLOW_REGISTRATION`: Email registration of new users. Set to `true` or `false` to enable or disable Email registration.
- `ALLOW_SOCIAL_LOGIN`: Allow users to connect to LibreChat with various social networks, see below. Set to `true` or `false` to enable or disable.
- `ALLOW_SOCIAL_REGISTRATION`: Enable or disable registration of new user using various social network. Set to `true` or `false` to enable or disable.

- `ALLOW_PASSWORD_RESET`: Enable or disable password reset. Set to `true` or `false` to enable or disable.

> **Quick Tip:** Even with registration disabled, add users directly to the database using `npm run create-user`.
> **Quick Tip:** With registration disabled, you can delete a user with `npm run delete-user email@domain.com`.

Expand All @@ -737,6 +738,7 @@ ALLOW_EMAIL_LOGIN=true
ALLOW_REGISTRATION=true
ALLOW_SOCIAL_LOGIN=false
ALLOW_SOCIAL_REGISTRATION=false
ALLOW_PASSWORD_RESET=false
```

- Default values: session expiry: 15 minutes, refresh token expiry: 7 days
Expand Down
4 changes: 3 additions & 1 deletion docs/install/configuration/user_auth_system.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ Here's an overview of the general configuration, located in the `.env` file at t
- `ALLOW_REGISTRATION`: Email registration of new users. Set to `true` or `false` to enable or disable Email registration.
- `ALLOW_SOCIAL_LOGIN`: Allow users to connect to LibreChat with various social networks, see below. Set to `true` or `false` to enable or disable.
- `ALLOW_SOCIAL_REGISTRATION`: Enable or disable registration of new user using various social network. Set to `true` or `false` to enable or disable.

- `ALLOW_PASSWORD_RESET`: Enable or disable password reset. Set to `true` or `false` to enable or disable.

> **Note:** OpenID does not support the ability to disable only registration.

>> **Quick Tip:** Even with registration disabled, add users directly to the database using `npm run create-user`. If you can't get npm to work, try `sudo docker exec -ti LibreChat sh` first to "ssh" into the container.
Expand All @@ -39,6 +40,7 @@ ALLOW_EMAIL_LOGIN=true
ALLOW_REGISTRATION=true
ALLOW_SOCIAL_LOGIN=false
ALLOW_SOCIAL_REGISTRATION=false
ALLOW_PASSWORD_RESET=false
```

### Session Expiry and Refresh Token
Expand Down