57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
"use server";
|
|
|
|
import { createClient } from "@/utils/supabase/server";
|
|
import { encodedRedirect } from "@/utils/utils";
|
|
import { redirect } from "next/navigation";
|
|
import { checkSession } from "./session";
|
|
|
|
export const signInAction = async (formData: FormData) => {
|
|
const supabase = await createClient();
|
|
const email = formData.get("email") as string;
|
|
const encodeEmail = encodeURIComponent(email);
|
|
|
|
try {
|
|
// First, check for existing session
|
|
const {
|
|
data: { session },
|
|
} = await supabase.auth.getSession();
|
|
|
|
// If there's an active session and the email matches
|
|
if (session?.user?.email === email) {
|
|
return {
|
|
success: true,
|
|
message: "You are already signed in",
|
|
redirectTo: "/dashboard",
|
|
};
|
|
}
|
|
|
|
// If no active session or different email, proceed with OTP
|
|
const { data, error } = await supabase.auth.signInWithOtp({
|
|
email,
|
|
options: {
|
|
shouldCreateUser: false,
|
|
},
|
|
});
|
|
|
|
if (error) {
|
|
return {
|
|
success: false,
|
|
error: error.message,
|
|
redirectTo: `/verify-otp?email=${encodeEmail}`,
|
|
};
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
message: "OTP has been sent to your email",
|
|
redirectTo: `/verify-otp?email=${encodeEmail}`,
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
success: false,
|
|
error: "An unexpected error occurred",
|
|
redirectTo: "/sign-in",
|
|
};
|
|
}
|
|
};
|