mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
feat: add reset password functionality
This commit is contained in:
12
src/config/env/index.ts
vendored
12
src/config/env/index.ts
vendored
@@ -14,6 +14,7 @@ const envSchema = z.object({
|
||||
CLOUDINARY_CLOUD_NAME: z.string(),
|
||||
CLOUDINARY_KEY: z.string(),
|
||||
CLOUDINARY_SECRET: z.string(),
|
||||
RESET_PASSWORD_TOKEN_SECRET: z.string(),
|
||||
CONFIRMATION_TOKEN_SECRET: z.string(),
|
||||
SESSION_SECRET: z.string(),
|
||||
SESSION_TOKEN_NAME: z.string(),
|
||||
@@ -87,6 +88,17 @@ export const CLOUDINARY_SECRET = parsed.data.CLOUDINARY_SECRET;
|
||||
*/
|
||||
export const CONFIRMATION_TOKEN_SECRET = parsed.data.CONFIRMATION_TOKEN_SECRET;
|
||||
|
||||
/**
|
||||
* Secret key for signing reset password tokens.
|
||||
*
|
||||
* @example
|
||||
* 'abcdefghijklmnopqrstuvwxyz123456';
|
||||
*
|
||||
* @see README.md for instructions on generating a secret key.
|
||||
*/
|
||||
|
||||
export const RESET_PASSWORD_TOKEN_SECRET = parsed.data.RESET_PASSWORD_TOKEN_SECRET;
|
||||
|
||||
/**
|
||||
* Secret key for signing session cookies.
|
||||
*
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user