feat: add reset password functionality

This commit is contained in:
Aaron William Po
2023-11-23 20:59:46 -05:00
parent fae0b0793d
commit c3a991f938
17 changed files with 475 additions and 464 deletions

View File

@@ -1,7 +1,7 @@
import { BasicUserInfoSchema } from '@/config/auth/types';
import jwt from 'jsonwebtoken';
import jwt, { JsonWebTokenError } from 'jsonwebtoken';
import { z } from 'zod';
import { CONFIRMATION_TOKEN_SECRET } from '../env';
import { CONFIRMATION_TOKEN_SECRET, RESET_PASSWORD_TOKEN_SECRET } from '../env';
import ServerError from '../util/ServerError';
export const generateConfirmationToken = (user: z.infer<typeof BasicUserInfoSchema>) => {
@@ -30,3 +30,29 @@ export const verifyConfirmationToken = async (token: string) => {
throw new ServerError('Something went wrong', 500);
}
};
export const generateResetPasswordToken = (user: z.infer<typeof BasicUserInfoSchema>) => {
return jwt.sign(user, RESET_PASSWORD_TOKEN_SECRET, { expiresIn: '5m' });
};
export const verifyResetPasswordToken = async (token: string) => {
try {
const decoded = jwt.verify(token, RESET_PASSWORD_TOKEN_SECRET);
const parsed = BasicUserInfoSchema.safeParse(decoded);
if (!parsed.success) {
throw new Error('Invalid token');
}
return parsed.data;
} catch (error) {
if (error instanceof JsonWebTokenError) {
throw new ServerError(
'Your reset password token is invalid. Please generate a new one.',
401,
);
}
throw new ServerError('Something went wrong', 500);
}
};