|
| 1 | +"use server"; |
| 2 | + |
| 3 | +import { redirect } from "next/navigation"; |
| 4 | +import { revalidatePath } from "next/cache"; |
| 5 | +import { createClient } from "@/utils/supabase/server"; |
| 6 | + |
| 7 | +export interface LoginActionState { |
| 8 | + status: "idle" | "in_progress" | "success" | "failed"; |
| 9 | +} |
| 10 | + |
| 11 | +export const login = async ( |
| 12 | + _: LoginActionState, |
| 13 | + formData: FormData, |
| 14 | +): Promise<LoginActionState> => { |
| 15 | + const supabase = createClient(); |
| 16 | + |
| 17 | + const { error } = await supabase.auth.signInWithPassword({ |
| 18 | + email: formData.get("email") as string, |
| 19 | + password: formData.get("password") as string, |
| 20 | + }); |
| 21 | + |
| 22 | + if (error) { |
| 23 | + return { status: "failed" } as LoginActionState; |
| 24 | + } |
| 25 | + |
| 26 | + revalidatePath("/", "layout"); |
| 27 | + redirect("/"); |
| 28 | +}; |
| 29 | + |
| 30 | +export interface RegisterActionState { |
| 31 | + status: "idle" | "in_progress" | "success" | "failed" | "user_exists"; |
| 32 | +} |
| 33 | + |
| 34 | +export const register = async (_: RegisterActionState, formData: FormData) => { |
| 35 | + const supabase = createClient(); |
| 36 | + |
| 37 | + let email = formData.get("email") as string; |
| 38 | + let password = formData.get("password") as string; |
| 39 | + |
| 40 | + const { data, error } = await supabase.auth.signUp({ email, password }); |
| 41 | + |
| 42 | + if (error) { |
| 43 | + if (error.code === "user_already_exists") { |
| 44 | + return { status: "user_exists" } as RegisterActionState; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const { user, session } = data; |
| 49 | + |
| 50 | + if (user && session) { |
| 51 | + const { error } = await supabase.auth.signInWithPassword({ |
| 52 | + email: formData.get("email") as string, |
| 53 | + password: formData.get("password") as string, |
| 54 | + }); |
| 55 | + |
| 56 | + if (error) { |
| 57 | + return { status: "failed" } as LoginActionState; |
| 58 | + } |
| 59 | + |
| 60 | + revalidatePath("/", "layout"); |
| 61 | + redirect("/"); |
| 62 | + } else { |
| 63 | + return { status: "failed" } as RegisterActionState; |
| 64 | + } |
| 65 | +}; |
| 66 | + |
| 67 | +export const getUserFromSession = async () => { |
| 68 | + const supabase = createClient(); |
| 69 | + const { data } = await supabase.auth.getUser(); |
| 70 | + return data.user; |
| 71 | +}; |
| 72 | + |
| 73 | +export const signOut = async () => { |
| 74 | + const supabase = createClient(); |
| 75 | + const { error } = await supabase.auth.signOut(); |
| 76 | + |
| 77 | + if (!error) { |
| 78 | + redirect("/login"); |
| 79 | + } |
| 80 | +}; |
0 commit comments