yo-next-auth/lib/tokens.ts

56 lines
1.3 KiB
TypeScript

import { v4 as uuidV4 } from 'uuid'
import {
VERIFICATION_TOKEN_EXPIRATION_DURATION,
} from '@/config/auth'
import db from '@/lib/db'
import { getVerificationTokenByEmail } from '@/data/verification-token'
import { getPasswordResetTokenByEmail } from '@/data/password-reset-token'
export const generatePasswordResetToken = async (email: string) => {
const token = uuidV4()
const expires = new Date(new Date().getTime() + VERIFICATION_TOKEN_EXPIRATION_DURATION)
const existingToken = await getPasswordResetTokenByEmail(email)
if (existingToken) {
await db.passwordResetToken.delete({
where: {
id: existingToken.id,
},
})
}
const passwordResetToken = await db.passwordResetToken.create({
data: {
email,
token,
expires,
},
})
return passwordResetToken
}
export const generateVerificationToken = async (email: string) => {
const token = uuidV4()
const expires = new Date(new Date().getTime() + VERIFICATION_TOKEN_EXPIRATION_DURATION)
const existingToken = await getVerificationTokenByEmail(email)
if (existingToken) {
await db.verificationToken.delete({
where: {
id: existingToken.id,
},
})
}
const verificationToken = await db.verificationToken.create({
data: {
email,
token,
expires,
},
})
return verificationToken
}