create-auth-js-boiler
Version:
Create a new auth-js-boiler project
77 lines (65 loc) • 1.88 kB
text/typescript
import crypto from "crypto";
import { v4 as uuid } from "uuid";
import { getVerificationTokenByEmail } from "./verification-token";
import { prisma } from "./prisma";
import { getTwoFactorTokenByEmail } from "./two-factor-token";
export const generateVerificationToken = async (email: string) => {
const token = uuid();
const expires = new Date(Date.now() + 60 * 10 * 1000); // 10 mins expiration
const existingToken = await getVerificationTokenByEmail(email);
if (existingToken) {
await prisma.verificationToken.delete({
where: {
id: existingToken.id,
},
});
}
const verificationToken = await prisma.verificationToken.create({
data: {
email,
token,
expires,
},
});
return verificationToken;
};
export const generatePasswordResetToken = async (email: string) => {
const token = uuid();
const expires = new Date(Date.now() + 60 * 10 * 1000); // 10 mins expiration
const existingToken = await getVerificationTokenByEmail(email);
if (existingToken) {
await prisma.verificationToken.delete({
where: {
id: existingToken.id,
},
});
}
const passwordResetToken = await prisma.passwordResetToken.create({
data: {
email,
token,
expires,
},
});
return passwordResetToken;
};
export const generateTwoFactorToken = async (email: string) => {
const token = crypto.randomInt(100_000, 1_000_000).toString();
const expires = new Date(new Date().getTime() + 10 * 60 * 1000); // 10 minutes
const existingToken = await getTwoFactorTokenByEmail(email);
if (existingToken) {
await prisma.twoFactorToken.delete({
where: {
id: existingToken.id,
},
});
}
const twoFactorToken = await prisma.twoFactorToken.create({
data: {
email,
token,
expires,
},
});
return twoFactorToken;
};