daphnis/lib/UpdatePassword.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-06-29 05:22:22 +00:00
"use server";
import { getAuth } from "@/auth/queries/getauth";
2024-06-29 06:37:50 +00:00
import { daphnis } from "@/lib/prisma";
2024-06-29 05:22:22 +00:00
import { Argon2id } from "oslo/password";
export const InApplicationPasswordReset = async (
currentPassword: string,
newPassword: string,
confirmNewPassword: string
) => {
// Check if new passwords match
if (newPassword !== confirmNewPassword) {
throw new Error("New passwords do not match");
}
const { user } = await getAuth();
if (!user) {
throw new Error("User not authenticated");
}
try {
// Fetch user from database
2024-06-29 06:37:50 +00:00
const existingUser = await daphnis.user.findUnique({
2024-06-29 05:22:22 +00:00
where: {
id: user.id,
},
});
if (!existingUser) {
throw new Error("User not found");
}
// Verify current password
const isPasswordValid = await new Argon2id().verify(
existingUser.hashedPassword,
currentPassword
);
if (!isPasswordValid) {
throw new Error("Current password is incorrect");
}
// Hash new password
const hashedPassword = await new Argon2id().hash(newPassword);
// Update user's password
2024-06-29 06:37:50 +00:00
await daphnis.user.update({
2024-06-29 05:22:22 +00:00
where: {
id: user.id,
},
data: {
hashedPassword,
},
});
} catch (error) {
throw new Error("Failed to update password");
}
};