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/38 account recovery #54

Merged
merged 6 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ NODE_ENV=
PINO_LOG_LEVEL=
JWT_ACCESS_SECRET=
JWT_REFRESH_SECRET=
JWT_TOKEN_FOR_ACTION_SECRET=
MASTER_OTP=
INITIAL_SETUP_DONE=

Expand Down
15 changes: 15 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@

- Define the default permissions for `admin` since super-admin have all the permission and we can't give all permission to admin. (e.g. super-admin is like a president and admin is like a PM)
- Find a mechanism to allow user to switch their role. (Low priority).

## Forget Password Schema

- Handle Rate Limiting for Token Generation and Use
- Handle Token Expiry and Auto-cleanup in Token Schema

## Secure OTP

- Add OTP Lock and Attempts Fields to User Schema
- Reset OTP Attempts After Successful Verification
- Log Failed OTP Attempts for Security Monitoring
- Temporarily Lock User After Exceeding OTP Attempts
- Unlock User Account Manually via Admin Control
- Handle OTP Abuse by Tracking Failed Attempts
- Implement OTP Cool down to Limit Requests per User
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"axios": "^1.7.4",
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"date-fns": "^3.6.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"helmet": "^7.1.0",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions src/api/v1/auth/__test__/forget-password.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {
expectBadRequestResponseForValidationError,
expectForgetPasswordSuccess,
expectUserNotFoundError,
forgetPassword,
} from '@/utils/test';
import { defaultUsers } from '@/constants';

describe('Forget Password', () => {
it('should throw error if email is not provided', async () => {
const res = await forgetPassword('');
expectBadRequestResponseForValidationError(res);
});

it('should throw error if email is invalid', async () => {
const res = await forgetPassword('a');
expectBadRequestResponseForValidationError(res);
});

it('should throw error if email is not registered', async () => {
const res = await forgetPassword('a@a.com');
expectUserNotFoundError(res);
});

it('should send forget password email', async () => {
const res = await forgetPassword(defaultUsers.email);
expectForgetPasswordSuccess(res);
});
});
87 changes: 87 additions & 0 deletions src/api/v1/auth/__test__/reset-password.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {
expectBadRequestResponseForValidationError,
expectFindUserByUsernameSuccess,
expectForgetPasswordSuccess,
expectLoginFailed,
expectLoginSuccess,
expectOTPVerificationSuccess,
expectResetPasswordSuccess,
expectSignUpSuccess,
findUserByUsername,
forgetPassword,
login,
resetPassword,
retrieveOTP,
signUp,
verifyAccount,
verifyOTP,
} from '@/utils/test';
import { Response } from 'supertest';
import { GetUser } from '../../user/user.validation';

const user = {
username: 'username',
email: 'validemail@example.com',
password: 'ValidPassword123!',
confirmPassword: 'ValidPassword123!',
};

describe('Reset Password', () => {
beforeAll(async () => {
const response = await signUp(user);
expectSignUpSuccess(response);

verifyAccount(user);
});

it('should throw error if token, password, confirmPassword is not provided', async () => {
const res = await resetPassword({ token: '', password: '', confirmPassword: '' });
expectBadRequestResponseForValidationError(res);
});

it('should throw error if token is invalid', async () => {
const res = await resetPassword({ token: 'a', password: 'a', confirmPassword: 'a' });
expectBadRequestResponseForValidationError(res);
});

it('should throw error if password and confirmPassword do not match', async () => {
const res = await resetPassword({ token: 'a', password: 'a', confirmPassword: 'b' });
expectBadRequestResponseForValidationError(res);
});

// Running these test twice to ensure that after user can successfully reset password
// should reset password again after isUsed flag is reset
for (let i = 0; i < 2; i++) {
let verifiedOTPResponse: Response;

it('should verify OTP successfully', async () => {
const res = await forgetPassword(user.email);
expectForgetPasswordSuccess(res);

const userResponse = await findUserByUsername(user.username);
expectFindUserByUsernameSuccess(userResponse, user);
const userDetails: GetUser = userResponse.body.user;

const otpData = await retrieveOTP(userDetails.id, 'sendForgetPasswordOTP');
verifiedOTPResponse = await verifyOTP(otpData, user.email);
expectOTPVerificationSuccess(verifiedOTPResponse);
});

it('should reset password successfully', async () => {
const { token } = verifiedOTPResponse.body;

const res = await resetPassword({ token, password: 'ValidPassword123@', confirmPassword: 'ValidPassword123@' });
expectResetPasswordSuccess(res);
});

it('should not login with old password', async () => {
const res = await login(user);
expectLoginFailed(res);
});

it('should login with new password', async () => {
const res = await login({ ...user, password: 'ValidPassword123@' });
expectLoginSuccess(res);
});
}
});
2 changes: 2 additions & 0 deletions src/api/v1/auth/auth.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ export const success = {
OTP_SENT: 'OTP sent',
OTP_VERIFIED: 'OTP verified',
TOKEN_VERIFIED: 'Access token is verified',
FORGET_PASSWORD_EMAIL_SENT: 'Forget password email sent',
PASSWORD_RESET_SUCCESSFULLY: 'Password reset successfully',
};
28 changes: 28 additions & 0 deletions src/api/v1/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export class AuthController {
const { accessToken, refreshToken } = await AuthService.signInWithGoogle(googleUser);

AuthController.setTokenCookies(res, accessToken, refreshToken);

// TODO: used action token instead of access token
res.cookie('access-token', accessToken, {
httpOnly: false,
secure: true,
Expand Down Expand Up @@ -108,4 +110,30 @@ export class AuthController {
next(error);
}
}

public static async forgetPassword(req: Request, res: Response, next: NextFunction) {
try {
await AuthService.forgetPassword(req.body.email);
sendResponse({
response: res,
message: success.FORGET_PASSWORD_EMAIL_SENT,
statusCode: STATUS_CODES.OK,
});
} catch (error) {
next(error);
}
}

public static async resetPassword(req: Request, res: Response, next: NextFunction) {
try {
await AuthService.resetPassword(req.body);
sendResponse({
response: res,
message: success.PASSWORD_RESET_SUCCESSFULLY,
statusCode: STATUS_CODES.OK,
});
} catch (error) {
next(error);
}
}
}
6 changes: 2 additions & 4 deletions src/api/v1/auth/auth.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@

router.post('/auth/sign-up', AuthController.signUp);
router.post('/auth/login', AuthController.signInWithEmailOrUsernameAndPassword);
router.post('/auth/logout', validateAccessToken, AuthController.logout);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
router.post('/auth/renew-token', validateRefreshToken, AuthController.renewToken);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
router.post('/auth/verify-token', validateAccessToken, AuthController.verifyToken);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
router.post('/auth/forget-password', AuthController.forgetPassword);
router.post('/auth/reset-password', AuthController.resetPassword);

router.get('/auth/google', signInWithGoogle);
router.get('/auth/google/callback', signInWithGoogleCallback, AuthController.signInWithGoogleCallback);

// router.post('/auth/send-reset-password-email', AuthController.sendResetPasswordEmail);
// router.post('/auth/reset-password', AuthController.resetPassword);
// router.post('/auth/verify-email', AuthController.verifyEmail);

export { router as authRoutes };
28 changes: 27 additions & 1 deletion src/api/v1/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@ import { ErrorTypeEnum } from '@/constants';
import { comparePassword, generateAccessToken, generateRefreshToken, validateObjectId } from '@/utils';
import { UserDAL } from '@/api/v1/user/user.dal';
import { UserService } from '@/api/v1/user/user.service';
import { CreateUser } from '@/api/v1/user/user.validation';
import {
CreateUser,
Email,
ResetPassword,
validateEmail,
validateResetPasswordSchema,
} from '@/api/v1/user/user.validation';
import { AuthDAL } from './auth.dal';
import { loginSchema, Login, AuthToken, Auth } from './auth.validation';
import { OtpService } from '@/api/v1/otp/otp.service';
import { GoogleUser } from '@/types/passport-google';
import { TokenAction, TokenService } from '@/api/v1/token';
import { notificationService } from '@/services';

export class AuthService {
public static async signUp(userData: CreateUser) {
Expand Down Expand Up @@ -81,6 +89,24 @@ export class AuthService {
return user;
}

public static async forgetPassword(email: Email) {
validateEmail(email);
await OtpService.sendOtp({ email, otpType: 'sendForgetPasswordOTP' });
}

public static async resetPassword(resetPassword: ResetPassword) {
const { password, token } = validateResetPasswordSchema(resetPassword);

const { userId } = await new TokenService().verifyActionToken(token, TokenAction.resetPassword);

const user = await UserService.updateUser(userId, { password });

notificationService.sendEmail({
to: user.email,
eventType: 'sendPasswordChangeConfirmation',
});
}

static async generateAccessAndRefreshToken(userId: string) {
validateObjectId(userId);

Expand Down
7 changes: 7 additions & 0 deletions src/api/v1/auth/auth.validation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { z } from 'zod';
import { userSchema } from '../user/user.validation';
import { otp } from '../otp/otp.validation';
import { tokenSchema } from '../token/token.validation';

const AuthSchema = z.object({
userId: z.string().regex(/^[a-f\d]{24}$/i, 'Invalid id'),
Expand All @@ -21,6 +22,11 @@ export const jwtRefreshTokenSchema = z.object({
id: z.string(),
});

export const jwtActionTokenSchema = z.object({
userId: z.string(),
action: tokenSchema.shape.action,
});

export const sendOtpSchema = z.object({
payload: userSchema.shape.email,
eventType: z.enum(['signUp', 'resetPassword', 'sendEmailVerificationOTP']),
Expand Down Expand Up @@ -53,6 +59,7 @@ export const eventTypes = z.enum(['sendEmailVerificationOTP', 'verifyPhoneNumber

export type JwtAccessToken = z.infer<typeof jwtAccessTokenSchema>;
export type JwtRefreshToken = z.infer<typeof jwtRefreshTokenSchema>;
export type JwtActionToken = z.infer<typeof jwtActionTokenSchema>;
export type Login = z.infer<typeof loginSchema>;
export type Auth = z.infer<typeof authenticateSchema>;
export type AuthToken = z.infer<typeof authToken>;
Expand Down
12 changes: 11 additions & 1 deletion src/api/v1/otp/otp.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,22 @@ export class OtpController {

public static async verifyOtp(req: Request, res: Response, next: NextFunction) {
try {
const { message } = await OtpService.verifyOtp(req.body);
const { message, token } = await OtpService.verifyOtp(req.body);

if (token != null) {
res.cookie('action-token', token, {
httpOnly: false,
secure: true,
sameSite: 'strict',
maxAge: 60000, // 1 minute
});
}

sendResponse({
response: res,
message: message,
statusCode: STATUS_CODES.OK,
payload: { token },
});
} catch (error) {
next(error);
Expand Down
4 changes: 2 additions & 2 deletions src/api/v1/otp/otp.dal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ export class OtpDAL {
return await newOtp.save();
}

static async getOtp(otpSchema: GetOtp): Promise<OtpSchema | null> {
return await OtpModel.findOne(otpSchema);
static async getOtpDetailsByUserId(otpSchema: GetOtp): Promise<OtpSchema[] | null> {
return await OtpModel.find(otpSchema);
}

static async deleteOtp(otpId: string) {
Expand Down
Loading
Loading