mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-02-21 18:22:00 +00:00
refactor: migrate authentication and signup flow to use external API and improve type safety
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m58s
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 1m58s
This commit is contained in:
parent
8ffabb1fcb
commit
0fd269df31
@ -4,8 +4,8 @@ import { authClient } from "@/lib/auth-client";
|
|||||||
import prisma from "@/lib/db";
|
import prisma from "@/lib/db";
|
||||||
import { VerifyUserDetails } from "@/lib/person";
|
import { VerifyUserDetails } from "@/lib/person";
|
||||||
import { signUpFormSchema } from "@/lib/schemas";
|
import { signUpFormSchema } from "@/lib/schemas";
|
||||||
|
import { phoneNumber } from "better-auth/plugins";
|
||||||
import { headers } from "next/headers";
|
import { headers } from "next/headers";
|
||||||
// import type { User } from "@prisma/client";
|
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { SendUserRejectionDetailSMS } from "./user-actions";
|
import { SendUserRejectionDetailSMS } from "./user-actions";
|
||||||
@ -33,14 +33,23 @@ export async function signin(previousState: ActionState, formData: FormData) {
|
|||||||
status: "error",
|
status: "error",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const NUMBER_WITH_COUNTRY_CODE: string = `+960${phoneNumber.split("-").join("")}`;
|
const FORMATTED_MOBILE_NUMBER: string = `${phoneNumber.split("-").join("")}`;
|
||||||
|
console.log(FORMATTED_MOBILE_NUMBER);
|
||||||
const userExists = await prisma.user.findUnique({
|
const userExistsResponse = await fetch(
|
||||||
where: {
|
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
|
||||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
mobile: FORMATTED_MOBILE_NUMBER,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
if (!userExists) {
|
const userExists = await userExistsResponse.json();
|
||||||
|
console.log(userExists.non_field_errors);
|
||||||
|
if (userExists?.non_field_errors) {
|
||||||
return redirect(`/signup?phone_number=${phoneNumber}`);
|
return redirect(`/signup?phone_number=${phoneNumber}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,12 +60,10 @@ export async function signin(previousState: ActionState, formData: FormData) {
|
|||||||
status: "error",
|
status: "error",
|
||||||
};
|
};
|
||||||
|
|
||||||
await authClient.phoneNumber.sendOtp({
|
// await authClient.phoneNumber.sendOtp({
|
||||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
// phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
||||||
});
|
// });
|
||||||
redirect(
|
redirect(`/verify-otp?phone_number=${FORMATTED_MOBILE_NUMBER}`);
|
||||||
`/verify-otp?phone_number=${encodeURIComponent(NUMBER_WITH_COUNTRY_CODE)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ActionState = {
|
type ActionState = {
|
||||||
@ -69,11 +76,8 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
|||||||
const parsedData = signUpFormSchema.safeParse(data);
|
const parsedData = signUpFormSchema.safeParse(data);
|
||||||
// get phone number from /signup?phone_number=999-1231
|
// get phone number from /signup?phone_number=999-1231
|
||||||
const headersList = await headers();
|
const headersList = await headers();
|
||||||
const referer = headersList.get("referer");
|
|
||||||
const number = referer?.split("?")[1]?.split("=")[1];
|
|
||||||
let NUMBER_WITH_COUNTRY_CODE: string;
|
|
||||||
|
|
||||||
console.log(data);
|
console.log("DATA ON SERVER SIDE", data);
|
||||||
|
|
||||||
if (!parsedData.success) {
|
if (!parsedData.success) {
|
||||||
return {
|
return {
|
||||||
@ -83,13 +87,6 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (number) {
|
|
||||||
NUMBER_WITH_COUNTRY_CODE = `+960${number.split("-").join("")}`;
|
|
||||||
} else {
|
|
||||||
NUMBER_WITH_COUNTRY_CODE = `+960${parsedData.data.phone_number.split("-").join("")}`;
|
|
||||||
}
|
|
||||||
console.log({ NUMBER_WITH_COUNTRY_CODE });
|
|
||||||
|
|
||||||
const idCardExists = await prisma.user.findFirst({
|
const idCardExists = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
id_card: parsedData.data.id_card,
|
id_card: parsedData.data.id_card,
|
||||||
@ -106,7 +103,7 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
|||||||
|
|
||||||
const phoneNumberExists = await prisma.user.findFirst({
|
const phoneNumberExists = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
phoneNumber: parsedData.data.phone_number,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -128,7 +125,7 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
|||||||
dob: new Date(parsedData.data.dob),
|
dob: new Date(parsedData.data.dob),
|
||||||
role: "USER",
|
role: "USER",
|
||||||
accNo: parsedData.data.accNo,
|
accNo: parsedData.data.accNo,
|
||||||
phoneNumber: NUMBER_WITH_COUNTRY_CODE,
|
phoneNumber: parsedData.data.phone_number,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const isValidPerson = await VerifyUserDetails({ user: newUser });
|
const isValidPerson = await VerifyUserDetails({ user: newUser });
|
||||||
|
@ -6,12 +6,7 @@ import { redirect } from "next/navigation";
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
export default async function LoginPage() {
|
export default async function LoginPage() {
|
||||||
const session = await auth.api.getSession({
|
|
||||||
headers: await headers(),
|
|
||||||
});
|
|
||||||
if (session) {
|
|
||||||
return redirect("/devices");
|
|
||||||
}
|
|
||||||
return (
|
return (
|
||||||
<div className="dark:bg-black w-full h-screen flex items-center justify-center font-sans">
|
<div className="dark:bg-black w-full h-screen flex items-center justify-center font-sans">
|
||||||
<div className="flex flex-col items-center justify-center w-full h-full ">
|
<div className="flex flex-col items-center justify-center w-full h-full ">
|
||||||
|
@ -1,44 +1,33 @@
|
|||||||
import SignUpForm from "@/components/auth/signup-form";
|
import SignUpForm from "@/components/auth/signup-form";
|
||||||
import { auth } from "@/lib/auth";
|
import { getAtollsWithIslands } from "@/queries/atoll";
|
||||||
import prisma from "@/lib/db";
|
|
||||||
import { headers } from "next/headers";
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import React from "react";
|
|
||||||
|
|
||||||
export default async function SignupPage({
|
export default async function SignupPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
}: {
|
}: {
|
||||||
searchParams: Promise<{ phone_number: string }>;
|
searchParams: Promise<{ phone_number: string }>;
|
||||||
}) {
|
}) {
|
||||||
const session = await auth.api.getSession({
|
|
||||||
headers: await headers(),
|
|
||||||
});
|
|
||||||
if (session) {
|
|
||||||
return redirect("/devices");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const atolls = await getAtollsWithIslands();
|
||||||
|
console.log(atolls.data);
|
||||||
const phone_number = (await searchParams).phone_number;
|
const phone_number = (await searchParams).phone_number;
|
||||||
if (!phone_number) {
|
if (!phone_number) {
|
||||||
return redirect("/login");
|
return redirect("/login");
|
||||||
}
|
}
|
||||||
const atolls = await prisma.atoll.findMany({
|
|
||||||
include: {
|
|
||||||
islands: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="dark:bg-black w-full h-screen flex items-center justify-center font-sans">
|
<div className="dark:bg-black w-full h-screen flex items-center justify-center font-sans">
|
||||||
<div className="flex flex-col items-center justify-center w-full h-full ">
|
<div className="flex flex-col items-center justify-center w-full h-full ">
|
||||||
<Image alt="Sar Link Logo" src="/logo.png" width={100} height={100} />
|
<Image priority alt="Sar Link Logo" src="/logo.png" width={100} height={100} style={{ width: "auto", height: "auto" }} />
|
||||||
<div className="mt-4 flex flex-col items-center justify-center">
|
<div className="mt-4 flex flex-col items-center justify-center">
|
||||||
<h4 className="font-bold text-xl text-gray-600">SAR Link Portal</h4>
|
<h4 className="font-bold text-xl text-gray-600">SAR Link Portal</h4>
|
||||||
<p className="text-gray-500">
|
<p className="text-gray-500">
|
||||||
Pay for your devices and track your bills.
|
Pay for your devices and track your bills.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<SignUpForm atolls={atolls} />
|
<SignUpForm atolls={atolls.data} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
@ -1,9 +1,14 @@
|
|||||||
import { ApplicationLayout } from "@/components/auth/application-layout";
|
import { ApplicationLayout } from "@/components/auth/application-layout";
|
||||||
|
import QueryProvider from "@/components/query-provider";
|
||||||
|
|
||||||
export default function DashboardLayout({
|
export default function DashboardLayout({
|
||||||
children,
|
children,
|
||||||
}: Readonly<{
|
}: Readonly<{
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
return <ApplicationLayout>{children}</ApplicationLayout>;
|
return <ApplicationLayout>
|
||||||
|
<QueryProvider>
|
||||||
|
{children}
|
||||||
|
</QueryProvider>
|
||||||
|
</ApplicationLayout>;
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ import { Barlow } from "next/font/google";
|
|||||||
import NextTopLoader from "nextjs-toploader";
|
import NextTopLoader from "nextjs-toploader";
|
||||||
import { Toaster } from "sonner";
|
import { Toaster } from "sonner";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import QueryProvider from "@/components/query-provider";
|
|
||||||
const barlow = Barlow({
|
const barlow = Barlow({
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
weight: ["100", "300", "400", "500", "600", "700", "800", "900"],
|
weight: ["100", "300", "400", "500", "600", "700", "800", "900"],
|
||||||
@ -35,7 +34,7 @@ export default function RootLayout({
|
|||||||
enableSystem
|
enableSystem
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
<QueryProvider>{children}</QueryProvider>
|
{children}
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</Provider>
|
</Provider>
|
||||||
</body>
|
</body>
|
||||||
|
@ -5,7 +5,6 @@ import Link from "next/link";
|
|||||||
|
|
||||||
import { signup } from "@/actions/auth-actions";
|
import { signup } from "@/actions/auth-actions";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { Island, Prisma } from "@prisma/client";
|
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
@ -19,16 +18,11 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
|
import type { Atoll } from "@/lib/backend-types";
|
||||||
|
|
||||||
type AtollWithIslands = Prisma.AtollGetPayload<{
|
|
||||||
include: {
|
|
||||||
islands: true;
|
|
||||||
};
|
|
||||||
}>;
|
|
||||||
|
|
||||||
export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
export default function SignUpForm({ atolls }: { atolls: Atoll[] }) {
|
||||||
const [atoll, setAtoll] = React.useState<AtollWithIslands>();
|
const [atoll, setAtoll] = React.useState<Atoll>();
|
||||||
const [islands, setIslands] = React.useState<Island[]>();
|
|
||||||
|
|
||||||
const [actionState, action, isPending] = React.useActionState(signup, {
|
const [actionState, action, isPending] = React.useActionState(signup, {
|
||||||
message: "",
|
message: "",
|
||||||
@ -36,7 +30,7 @@ export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
|||||||
|
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
setIslands(atoll?.islands);
|
console.log(atoll)
|
||||||
}, [atoll]);
|
}, [atoll]);
|
||||||
|
|
||||||
|
|
||||||
@ -122,11 +116,11 @@ export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
|||||||
<Select
|
<Select
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
setAtoll(atolls.find((atoll) => atoll.id === v));
|
console.log({ v })
|
||||||
setIslands([]);
|
setAtoll(atolls.find((atoll) => atoll.id === Number.parseInt(v)));
|
||||||
}}
|
}}
|
||||||
name="atoll_id"
|
name="atoll_id"
|
||||||
value={atoll?.id}
|
value={atoll?.id?.toString() ?? ""}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-full">
|
<SelectTrigger className="w-full">
|
||||||
<SelectValue placeholder="Select atoll" />
|
<SelectValue placeholder="Select atoll" />
|
||||||
@ -135,7 +129,7 @@ export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
|||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
<SelectLabel>Atolls</SelectLabel>
|
<SelectLabel>Atolls</SelectLabel>
|
||||||
{atolls.map((atoll) => (
|
{atolls.map((atoll) => (
|
||||||
<SelectItem key={atoll.id} value={atoll.id}>
|
<SelectItem key={atoll.id} value={atoll.id.toString()}>
|
||||||
{atoll.name}
|
{atoll.name}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
@ -159,8 +153,8 @@ export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
|||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
<SelectLabel>Islands</SelectLabel>
|
<SelectLabel>Islands</SelectLabel>
|
||||||
{islands?.map((island) => (
|
{atoll?.islands?.map((island) => (
|
||||||
<SelectItem key={island.id} value={island.id}>
|
<SelectItem key={island.id} value={island.id.toString()}>
|
||||||
{island.name}
|
{island.name}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
@ -333,4 +327,4 @@ export default function SignUpForm({ atolls }: { atolls: AtollWithIslands[] }) {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
31
lib/backend-types.ts
Normal file
31
lib/backend-types.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
export interface Links {
|
||||||
|
next_page: string | null;
|
||||||
|
previous_page: string | null;
|
||||||
|
}
|
||||||
|
export interface Meta {
|
||||||
|
total: number;
|
||||||
|
per_page: number;
|
||||||
|
current_page: number;
|
||||||
|
last_page: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataResponse<T> {
|
||||||
|
meta: Meta;
|
||||||
|
links: Links;
|
||||||
|
data: T[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Atoll {
|
||||||
|
id: number;
|
||||||
|
islands: Island[];
|
||||||
|
name: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Island {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
@ -5,10 +5,10 @@ export const signUpFormSchema = z.object({
|
|||||||
.string()
|
.string()
|
||||||
.min(2, { message: "ID Card is required" })
|
.min(2, { message: "ID Card is required" })
|
||||||
.regex(/^[A][0-9]{6}$/, "Please enter a valid ID Card number."),
|
.regex(/^[A][0-9]{6}$/, "Please enter a valid ID Card number."),
|
||||||
atoll_id: z.string().min(2, { message: "Atoll is required." }),
|
atoll_id: z.string().min(1, { message: "Atoll is required." }),
|
||||||
island_id: z
|
island_id: z
|
||||||
.string({ required_error: "Island is required." })
|
.string({ required_error: "Island is required." })
|
||||||
.min(2, { message: "Island is required." }),
|
.min(1, { message: "Island is required." }),
|
||||||
address: z.string().min(2, { message: "address is required." }),
|
address: z.string().min(2, { message: "address is required." }),
|
||||||
dob: z.coerce.date({ message: "Date of birth is required." }),
|
dob: z.coerce.date({ message: "Date of birth is required." }),
|
||||||
phone_number: z
|
phone_number: z
|
||||||
@ -26,5 +26,8 @@ export const signUpFormSchema = z.object({
|
|||||||
required_error: "You must accept the privacy policy",
|
required_error: "You must accept the privacy policy",
|
||||||
})
|
})
|
||||||
.transform((val) => val === "on"),
|
.transform((val) => val === "on"),
|
||||||
accNo: z.string().min(2, { message: "Account number is required." }),
|
accNo: z
|
||||||
|
.string()
|
||||||
|
.min(2, { message: "Account number is required." })
|
||||||
|
.regex(/^(7\d{12}|9\d{16})$/, "Please enter a valid account number"),
|
||||||
});
|
});
|
||||||
|
10
queries/atoll.ts
Normal file
10
queries/atoll.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import type { Atoll, DataResponse } from "@/lib/backend-types";
|
||||||
|
|
||||||
|
export async function getAtollsWithIslands(): Promise<DataResponse<Atoll>> {
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.SARLINK_API_BASE_URL}/api/auth/atolls`,
|
||||||
|
);
|
||||||
|
return response.json();
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user