-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
58 lines (50 loc) · 1.28 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"use server";
import { signIn, signOut } from "@/auth";
import { db } from "@/db";
import { AuthError } from "next-auth";
import { revalidatePath } from "next/cache";
const getUserByEmail = async (email: string) => {
try {
const user = await db.user.findUnique({
where: {
email,
},
});
return user;
} catch (error) {
console.log(error);
return null;
}
};
export const login = async (provider: string) => {
await signIn(provider, { redirectTo: "/" });
revalidatePath("/");
};
export const logout = async () => {
await signOut({ redirectTo: "/" });
revalidatePath("/");
};
export const loginWithCreds = async (formData: FormData) => {
const rawFormData = {
email: formData.get("email"),
password: formData.get("password"),
role: "ADMIN",
redirectTo: "/",
};
const existingUser = await getUserByEmail(formData.get("email") as string);
console.log(existingUser);
try {
await signIn("credentials", rawFormData);
} catch (error: any) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
return { error: "Invalid credentials!" };
default:
return { error: "Something went wrong!" };
}
}
throw error;
}
revalidatePath("/");
};