|
| 1 | +"use server" |
| 2 | + |
| 3 | +import { signIn, signOut } from "~~/auth" |
| 4 | +import { hash } from "bcryptjs" |
| 5 | +import { AuthError } from "next-auth" |
| 6 | +import { getDb } from "~~/lib/mongodb" |
| 7 | + |
| 8 | +export async function registerUser(formData: { |
| 9 | + name: string |
| 10 | + email: string |
| 11 | + password: string |
| 12 | + role: "investor" | "realtor" |
| 13 | + phone?: string |
| 14 | + nin?: string |
| 15 | + businessName?: string |
| 16 | +}) { |
| 17 | + try { |
| 18 | + const db = await getDb() |
| 19 | + |
| 20 | + const existingUser = await db.collection("users").findOne({ |
| 21 | + email: formData.email, |
| 22 | + }) |
| 23 | + |
| 24 | + if (existingUser) { |
| 25 | + return { error: "User with this email already exists" } |
| 26 | + } |
| 27 | + |
| 28 | + const hashedPassword = await hash(formData.password, 12) |
| 29 | + |
| 30 | + const result = await db.collection("users").insertOne({ |
| 31 | + name: formData.name, |
| 32 | + email: formData.email, |
| 33 | + password: hashedPassword, |
| 34 | + role: formData.role, |
| 35 | + phone: formData.phone || null, |
| 36 | + nin: formData.nin || null, |
| 37 | + businessName: formData.businessName || null, |
| 38 | + createdAt: new Date(), |
| 39 | + }) |
| 40 | + |
| 41 | + if (!result.insertedId) { |
| 42 | + return { error: "Failed to create user" } |
| 43 | + } |
| 44 | + |
| 45 | + return { success: true } |
| 46 | + } catch (error) { |
| 47 | + console.error("Registration error:", error) |
| 48 | + return { error: "An error occurred during registration" } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +export async function loginUser(email: string, password: string) { |
| 53 | + try { |
| 54 | + await signIn("credentials", { |
| 55 | + email, |
| 56 | + password, |
| 57 | + redirect: false, |
| 58 | + }) |
| 59 | + |
| 60 | + return { success: true } |
| 61 | + } catch (error) { |
| 62 | + if (error instanceof AuthError) { |
| 63 | + switch (error.type) { |
| 64 | + case "CredentialsSignin": |
| 65 | + return { error: "Invalid email or password" } |
| 66 | + default: |
| 67 | + return { error: "An error occurred during login" } |
| 68 | + } |
| 69 | + } |
| 70 | + throw error |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +export async function logoutUser() { |
| 75 | + await signOut({ redirectTo: "/" }) |
| 76 | +} |
0 commit comments