2025-03-14 09:06:19 +00:00
|
|
|
"use server";
|
|
|
|
|
|
|
|
import bcrypt from "bcrypt";
|
|
|
|
import prisma from "@/lib/prisma";
|
|
|
|
import { signIn } from "@/lib/auth";
|
|
|
|
import { authSchema } from "@/lib/zod";
|
2025-03-18 14:50:06 +00:00
|
|
|
import { CredentialsSignInFormValues } from "@/components/credentials-sign-in-form";
|
|
|
|
import { CredentialsSignUpFormValues } from "@/components/credentials-sign-up-form";
|
2025-03-14 09:06:19 +00:00
|
|
|
|
2025-03-14 09:15:38 +00:00
|
|
|
const saltRounds = 10;
|
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
export async function signInWithCredentials(formData: CredentialsSignInFormValues) {
|
|
|
|
try {
|
|
|
|
await signIn("credentials", {
|
|
|
|
...formData,
|
|
|
|
redirect: false,
|
|
|
|
});
|
|
|
|
return { success: true };
|
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof Error) {
|
2025-03-18 15:24:36 +00:00
|
|
|
return { error: "Invalid credentials" };
|
2025-03-18 14:50:06 +00:00
|
|
|
}
|
|
|
|
return { error: "Failed to sign in. Please try again." };
|
|
|
|
}
|
2025-03-14 09:06:19 +00:00
|
|
|
}
|
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
export async function signUpWithCredentials(formData: CredentialsSignUpFormValues) {
|
|
|
|
try {
|
|
|
|
const validatedData = await authSchema.parseAsync(formData);
|
|
|
|
const existingUser = await prisma.user.findUnique({
|
|
|
|
where: { email: validatedData.email },
|
|
|
|
});
|
2025-03-14 09:15:38 +00:00
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
if (existingUser) {
|
|
|
|
throw new Error("User already exists");
|
|
|
|
}
|
2025-03-14 09:06:19 +00:00
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
const pwHash = await bcrypt.hash(validatedData.password, saltRounds);
|
2025-03-14 09:06:19 +00:00
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
const user = await prisma.user.create({
|
|
|
|
data: {
|
|
|
|
email: validatedData.email,
|
|
|
|
password: pwHash,
|
|
|
|
},
|
2025-03-18 13:53:59 +00:00
|
|
|
});
|
|
|
|
|
2025-03-18 14:50:06 +00:00
|
|
|
const count = await prisma.user.count();
|
|
|
|
if (count === 1) {
|
|
|
|
await prisma.user.update({
|
|
|
|
where: { id: user.id },
|
|
|
|
data: { role: "ADMIN" },
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return { success: true };
|
|
|
|
} catch (error) {
|
|
|
|
if (error instanceof Error) {
|
|
|
|
return { error: error.message };
|
|
|
|
}
|
|
|
|
return { error: "Registration failed. Please try again." };
|
|
|
|
}
|
2025-03-14 09:06:19 +00:00
|
|
|
}
|