2023-09-18 11:15:29 +00:00
|
|
|
import crypto from 'crypto';
|
|
|
|
|
|
|
|
|
|
import { prisma } from '@documenso/prisma';
|
2024-05-09 12:35:58 +05:30
|
|
|
import type { TForgotPasswordFormSchema } from '@documenso/trpc/server/profile-router/schema';
|
2023-09-18 11:15:29 +00:00
|
|
|
|
2023-09-19 13:34:54 +00:00
|
|
|
import { ONE_DAY, ONE_HOUR } from '../../constants/time';
|
2023-09-18 12:14:55 +00:00
|
|
|
import { sendForgotPassword } from '../auth/send-forgot-password';
|
|
|
|
|
|
2023-09-18 11:15:29 +00:00
|
|
|
export const forgotPassword = async ({ email }: TForgotPasswordFormSchema) => {
|
2023-09-19 13:34:54 +00:00
|
|
|
const user = await prisma.user.findFirst({
|
|
|
|
|
where: {
|
|
|
|
|
email: {
|
|
|
|
|
equals: email,
|
|
|
|
|
mode: 'insensitive',
|
2023-09-18 15:09:41 +00:00
|
|
|
},
|
2023-09-19 13:34:54 +00:00
|
|
|
},
|
|
|
|
|
});
|
2023-09-18 11:15:29 +00:00
|
|
|
|
|
|
|
|
if (!user) {
|
2023-09-19 13:34:54 +00:00
|
|
|
return;
|
2023-09-18 11:15:29 +00:00
|
|
|
}
|
|
|
|
|
|
2023-09-19 13:57:11 +00:00
|
|
|
// Find a token that was created in the last hour and hasn't expired
|
2023-09-18 11:15:29 +00:00
|
|
|
const existingToken = await prisma.passwordResetToken.findFirst({
|
|
|
|
|
where: {
|
|
|
|
|
userId: user.id,
|
2023-09-19 13:34:54 +00:00
|
|
|
expiry: {
|
2023-09-19 13:57:11 +00:00
|
|
|
gt: new Date(),
|
2023-09-19 13:34:54 +00:00
|
|
|
},
|
2023-09-18 11:15:29 +00:00
|
|
|
createdAt: {
|
2023-09-19 13:34:54 +00:00
|
|
|
gt: new Date(Date.now() - ONE_HOUR),
|
2023-09-18 11:15:29 +00:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (existingToken) {
|
2023-09-19 13:34:54 +00:00
|
|
|
return;
|
2023-09-18 11:15:29 +00:00
|
|
|
}
|
|
|
|
|
|
2023-09-19 13:34:54 +00:00
|
|
|
const token = crypto.randomBytes(18).toString('hex');
|
2023-09-18 11:15:29 +00:00
|
|
|
|
2023-09-19 13:34:54 +00:00
|
|
|
await prisma.passwordResetToken.create({
|
|
|
|
|
data: {
|
|
|
|
|
token,
|
|
|
|
|
expiry: new Date(Date.now() + ONE_DAY),
|
|
|
|
|
userId: user.id,
|
|
|
|
|
},
|
|
|
|
|
});
|
2023-09-18 11:15:29 +00:00
|
|
|
|
2023-09-19 13:34:54 +00:00
|
|
|
await sendForgotPassword({
|
2023-09-18 12:14:55 +00:00
|
|
|
userId: user.id,
|
2023-09-19 13:34:54 +00:00
|
|
|
}).catch((err) => console.error(err));
|
2023-09-18 11:15:29 +00:00
|
|
|
};
|