mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-07-02 03:38:22 +00:00
first commit
This commit is contained in:
79
actions/auth-actions.ts
Normal file
79
actions/auth-actions.ts
Normal file
@ -0,0 +1,79 @@
|
||||
"use server";
|
||||
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import prisma from "@/lib/db";
|
||||
import type { signUpFormSchema } from "@/lib/schemas";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
|
||||
const formSchema = z.object({
|
||||
phoneNumber: z
|
||||
.string()
|
||||
.regex(/^[7|9][0-9]{2}-[0-9]{4}$/, "Please enter a valid phone number"),
|
||||
});
|
||||
|
||||
export async function signin(
|
||||
currentState: { message: string; status: string },
|
||||
formData: FormData,
|
||||
) {
|
||||
const phoneNumber = formData.get("phoneNumber") as string;
|
||||
const result = formSchema.safeParse({ phoneNumber });
|
||||
console.log(phoneNumber);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
message: result.error.errors[0].message, // Get the error message from Zod
|
||||
status: "error",
|
||||
};
|
||||
}
|
||||
|
||||
if (!phoneNumber) {
|
||||
return {
|
||||
message: "Please enter a phone number",
|
||||
status: "error",
|
||||
};
|
||||
}
|
||||
const NUMBER_WITH_COUNTRY_CODE: string = `+960${phoneNumber.split("-").join("")}`;
|
||||
|
||||
const userExists = await prisma.user.findUnique({
|
||||
where: {
|
||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
||||
},
|
||||
});
|
||||
if (!userExists) {
|
||||
return redirect(`/signup?phone_number=${phoneNumber}`);
|
||||
}
|
||||
await authClient.phoneNumber.sendOtp({
|
||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
||||
});
|
||||
redirect("/verify-otp");
|
||||
}
|
||||
|
||||
export async function signup({
|
||||
userData,
|
||||
}: { userData: z.infer<typeof signUpFormSchema> }) {
|
||||
const newUser = await prisma.user.create({
|
||||
data: { ...userData, email: "" },
|
||||
});
|
||||
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
export const sendOtp = async (phoneNumber: string, code: string) => {
|
||||
// Implement sending OTP code via SMS
|
||||
console.log("Send OTP server fn", phoneNumber, code);
|
||||
const respose = await fetch("https://smsapi.sarlink.link/send", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_key: process.env.SMS_API_KEY,
|
||||
number: phoneNumber,
|
||||
text: `Your OTP code is ${code}`,
|
||||
}),
|
||||
});
|
||||
const data = await respose.json();
|
||||
console.log(data);
|
||||
return data;
|
||||
};
|
Reference in New Issue
Block a user