'use server' import { NewPasswordSchema } from '@/schemas' import { infer as zInfer } from 'zod' import bcrypt from 'bcryptjs' import { PASSWORD_SALT_LENGTH } from '@/config/validation' import { getPasswordResetTokenByToken } from '@/data/password-reset-token' import { getUserByEmail } from '@/data/user' import db from '@/lib/db' export const newPassword = async (values: zInfer, token?: string | null) => { if (!token) { return { error: 'auth.form.error.missing_token' } } const validatedFields = NewPasswordSchema.safeParse(values) if (!validatedFields.success) { return { error: 'auth.form.error.invalid_fields' } } const existingToken = await getPasswordResetTokenByToken(token) if (!existingToken) { return { error: 'auth.form.error.invalid_token' } } const hasExpired = new Date(existingToken.expires) < new Date() if (hasExpired) { return { error: 'auth.form.error.expired_token' } } const existingUser = await getUserByEmail(existingToken.email) if (!existingUser) { return { error: 'auth.form.error.invalid_email' } } const { password } = validatedFields.data const hashedPassword = await bcrypt.hash(password, PASSWORD_SALT_LENGTH) try { await db.user.update({ where: { id: existingUser.id }, data: { password: hashedPassword }, }) } catch (err) { console.error(err) return { error: 'db.error.update.user_password' } } try { await db.passwordResetToken.delete({ where: { id: existingToken.id }, }) return { success: 'db.success.update.password_updated' } } catch (err) { //TODO: Implement logging console.error(err) } return { error: 'db.error.common.something_wrong' } }