daphnis/app/(password-reset)/password-reset/[token]/token.ts

68 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-06-29 05:22:22 +00:00
"use server";
2024-06-29 06:37:50 +00:00
import { daphnis } from "@/lib/prisma";
2024-06-29 05:22:22 +00:00
import { redirect } from "next/navigation";
import { Argon2id } from "oslo/password";
export async function resetPassword(token: string, data: FormData) {
const password = data.get("password");
const confirmPassword = data.get("confirm");
if (
!password ||
typeof password !== "string" ||
password !== confirmPassword
) {
return {
error:
"The passwords did not match. Please try retyping them and submitting again.",
};
}
2024-06-29 06:37:50 +00:00
const passwordResetToken = await daphnis.passwordResetToken.findUnique({
2024-06-29 05:22:22 +00:00
where: {
token,
createdAt: { gt: new Date(Date.now() - 1000 * 60 * 60 * 4) },
resetAt: null,
},
});
if (!passwordResetToken) {
return {
error:
"Invalid token reset request. Please try resetting your password again.",
};
}
const argon2 = new Argon2id();
const encrypted = await argon2.hash(password);
2024-06-29 06:37:50 +00:00
const updateUser = daphnis.user.update({
2024-06-29 05:22:22 +00:00
where: { id: passwordResetToken.userId },
data: {
hashedPassword: encrypted,
},
});
2024-06-29 06:37:50 +00:00
const updateToken = daphnis.passwordResetToken.update({
2024-06-29 05:22:22 +00:00
where: {
id: passwordResetToken.id,
},
data: {
resetAt: new Date(),
},
});
try {
2024-06-29 06:37:50 +00:00
await daphnis.$transaction([updateUser, updateToken]);
2024-06-29 05:22:22 +00:00
} catch (err) {
console.error(err);
return {
error:
"An unexpected error occurred. Please try again and if the problem persists, contact support.",
};
}
redirect("/password-reset/success");
}