104 lines
2.5 KiB
TypeScript
104 lines
2.5 KiB
TypeScript
// src/app/(auth-pages)/actions.ts
|
|
"use server";
|
|
|
|
import db from "@/lib/db";
|
|
import { SignInFormData } from "@/src/models/auth/sign-in.model";
|
|
import { VerifyOtpFormData } from "@/src/models/auth/verify-otp.model";
|
|
import { User } from "@/src/models/users/users.model";
|
|
import { authRepository } from "@/src/repositories/authentication.repository";
|
|
import { createClient } from "@/utils/supabase/server";
|
|
import { redirect } from "next/navigation";
|
|
|
|
export async function signIn(
|
|
data: SignInFormData
|
|
): Promise<{ success: boolean; message: string; redirectTo?: string }> {
|
|
try {
|
|
const result = await authRepository.signIn(data);
|
|
return {
|
|
success: true,
|
|
message: "Check your email for the login link!",
|
|
redirectTo: result.redirectTo,
|
|
};
|
|
} catch (error) {
|
|
console.error("Authentication error:", error);
|
|
return {
|
|
success: false,
|
|
message:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Authentication failed. Please try again.",
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function verifyOtp(
|
|
data: VerifyOtpFormData
|
|
): Promise<{ success: boolean; message: string; redirectTo?: string }> {
|
|
try {
|
|
const result = await authRepository.verifyOtp(data);
|
|
return {
|
|
success: true,
|
|
message: "Successfully authenticated!",
|
|
redirectTo: result.redirectTo,
|
|
};
|
|
} catch (error) {
|
|
console.error("OTP verification error:", error);
|
|
return {
|
|
success: false,
|
|
message:
|
|
error instanceof Error
|
|
? error.message
|
|
: "OTP verification failed. Please try again.",
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function signOut() {
|
|
try {
|
|
const result = await authRepository.signOut();
|
|
return {
|
|
success: true,
|
|
redirectTo: result.redirectTo,
|
|
};
|
|
} catch (error) {
|
|
console.error("Sign out error:", error);
|
|
return {
|
|
success: false,
|
|
message:
|
|
error instanceof Error
|
|
? error.message
|
|
: "Sign out failed. Please try again.",
|
|
};
|
|
}
|
|
}
|
|
|
|
// get current user
|
|
export async function getCurrentUser(): Promise<User> {
|
|
const supabase = await createClient();
|
|
|
|
const {
|
|
data: { user },
|
|
error,
|
|
} = await supabase.auth.getUser();
|
|
|
|
if (error) {
|
|
console.error("Error fetching current user:", error);
|
|
throw new Error(error.message);
|
|
}
|
|
|
|
const userDetail = await db.users.findUnique({
|
|
where: {
|
|
id: user?.id,
|
|
},
|
|
include: {
|
|
profile: true,
|
|
},
|
|
});
|
|
|
|
if (!userDetail) {
|
|
throw new Error("User not found");
|
|
}
|
|
|
|
return userDetail;
|
|
}
|