mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-04-20 03:50:20 +00:00
refactor: update authentication flow to use NextAuth, replace better-auth with axios for API calls, and clean up unused code
This commit is contained in:
parent
0fd269df31
commit
020d74c5e2
@ -1,10 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import prisma from "@/lib/db";
|
||||
import { VerifyUserDetails } from "@/lib/person";
|
||||
import { signUpFormSchema } from "@/lib/schemas";
|
||||
import { phoneNumber } from "better-auth/plugins";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
@ -34,7 +31,7 @@ export async function signin(previousState: ActionState, formData: FormData) {
|
||||
};
|
||||
}
|
||||
const FORMATTED_MOBILE_NUMBER: string = `${phoneNumber.split("-").join("")}`;
|
||||
console.log(FORMATTED_MOBILE_NUMBER);
|
||||
console.log({ FORMATTED_MOBILE_NUMBER });
|
||||
const userExistsResponse = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
|
||||
{
|
||||
@ -48,7 +45,7 @@ export async function signin(previousState: ActionState, formData: FormData) {
|
||||
},
|
||||
);
|
||||
const userExists = await userExistsResponse.json();
|
||||
console.log(userExists.non_field_errors);
|
||||
console.log("user exists", userExists);
|
||||
if (userExists?.non_field_errors) {
|
||||
return redirect(`/signup?phone_number=${phoneNumber}`);
|
||||
}
|
||||
@ -75,7 +72,6 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
const parsedData = signUpFormSchema.safeParse(data);
|
||||
// get phone number from /signup?phone_number=999-1231
|
||||
const headersList = await headers();
|
||||
|
||||
console.log("DATA ON SERVER SIDE", data);
|
||||
|
||||
@ -87,83 +83,82 @@ export async function signup(_actionState: ActionState, formData: FormData) {
|
||||
};
|
||||
}
|
||||
|
||||
const idCardExists = await prisma.user.findFirst({
|
||||
where: {
|
||||
id_card: parsedData.data.id_card,
|
||||
},
|
||||
});
|
||||
// const idCardExists = await prisma.user.findFirst({
|
||||
// where: {
|
||||
// id_card: parsedData.data.id_card,
|
||||
// },
|
||||
// });
|
||||
|
||||
if (idCardExists) {
|
||||
return {
|
||||
message: "ID card already exists.",
|
||||
payload: formData,
|
||||
db_error: "id_card",
|
||||
};
|
||||
}
|
||||
// if (idCardExists) {
|
||||
// return {
|
||||
// message: "ID card already exists.",
|
||||
// payload: formData,
|
||||
// db_error: "id_card",
|
||||
// };
|
||||
// }
|
||||
|
||||
const phoneNumberExists = await prisma.user.findFirst({
|
||||
where: {
|
||||
phoneNumber: parsedData.data.phone_number,
|
||||
},
|
||||
});
|
||||
// const phoneNumberExists = await prisma.user.findFirst({
|
||||
// where: {
|
||||
// phoneNumber: parsedData.data.phone_number,
|
||||
// },
|
||||
// });
|
||||
|
||||
if (phoneNumberExists) {
|
||||
return {
|
||||
message: "Phone number already exists.",
|
||||
payload: formData,
|
||||
db_error: "phone_number",
|
||||
};
|
||||
}
|
||||
// if (phoneNumberExists) {
|
||||
// return {
|
||||
// message: "Phone number already exists.",
|
||||
// payload: formData,
|
||||
// db_error: "phone_number",
|
||||
// };
|
||||
// }
|
||||
|
||||
const newUser = await prisma.user.create({
|
||||
data: {
|
||||
name: parsedData.data.name,
|
||||
islandId: parsedData.data.island_id,
|
||||
atollId: parsedData.data.atoll_id,
|
||||
address: parsedData.data.address,
|
||||
id_card: parsedData.data.id_card,
|
||||
dob: new Date(parsedData.data.dob),
|
||||
role: "USER",
|
||||
accNo: parsedData.data.accNo,
|
||||
phoneNumber: parsedData.data.phone_number,
|
||||
},
|
||||
});
|
||||
const isValidPerson = await VerifyUserDetails({ user: newUser });
|
||||
// const newUser = await prisma.user.create({
|
||||
// data: {
|
||||
// name: parsedData.data.name,
|
||||
// islandId: parsedData.data.island_id,
|
||||
// atollId: parsedData.data.atoll_id,
|
||||
// address: parsedData.data.address,
|
||||
// id_card: parsedData.data.id_card,
|
||||
// dob: new Date(parsedData.data.dob),
|
||||
// role: "USER",
|
||||
// accNo: parsedData.data.accNo,
|
||||
// phoneNumber: parsedData.data.phone_number,
|
||||
// },
|
||||
// });
|
||||
// const isValidPerson = await VerifyUserDetails({ user: newUser });
|
||||
|
||||
if (!isValidPerson) {
|
||||
await SendUserRejectionDetailSMS({
|
||||
details: `
|
||||
A new user has requested for verification. \n
|
||||
USER DETAILS:
|
||||
Name: ${parsedData.data.name}
|
||||
Address: ${parsedData.data.address}
|
||||
ID Card: ${parsedData.data.id_card}
|
||||
DOB: ${parsedData.data.dob.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
ACC No: ${parsedData.data.accNo}\n\nVerify the user with the following link: ${process.env.BETTER_AUTH_URL}/users/${newUser.id}/verify
|
||||
`,
|
||||
phoneNumber: process.env.ADMIN_PHONENUMBER ?? "",
|
||||
});
|
||||
return {
|
||||
message:
|
||||
"Your account has been requested for verification. Please wait for a response from admin.",
|
||||
payload: formData,
|
||||
db_error: "invalidPersonValidation",
|
||||
};
|
||||
}
|
||||
// if (!isValidPerson) {
|
||||
// await SendUserRejectionDetailSMS({
|
||||
// details: `
|
||||
// A new user has requested for verification. \n
|
||||
// USER DETAILS:
|
||||
// Name: ${parsedData.data.name}
|
||||
// Address: ${parsedData.data.address}
|
||||
// ID Card: ${parsedData.data.id_card}
|
||||
// DOB: ${parsedData.data.dob.toLocaleDateString("en-US", {
|
||||
// month: "short",
|
||||
// day: "2-digit",
|
||||
// year: "numeric",
|
||||
// })}
|
||||
// ACC No: ${parsedData.data.accNo}\n\nVerify the user with the following link: ${process.env.BETTER_AUTH_URL}/users/${newUser.id}/verify
|
||||
// `,
|
||||
// phoneNumber: process.env.ADMIN_PHONENUMBER ?? "",
|
||||
// });
|
||||
// return {
|
||||
// message:
|
||||
// "Your account has been requested for verification. Please wait for a response from admin.",
|
||||
// payload: formData,
|
||||
// db_error: "invalidPersonValidation",
|
||||
// };
|
||||
|
||||
if (isValidPerson) {
|
||||
await authClient.phoneNumber.sendOtp({
|
||||
phoneNumber: newUser.phoneNumber,
|
||||
});
|
||||
}
|
||||
redirect(
|
||||
`/verify-otp?phone_number=${encodeURIComponent(newUser.phoneNumber)}`,
|
||||
);
|
||||
return { message: "User created successfully" };
|
||||
// if (isValidPerson) {
|
||||
// await authClient.phoneNumber.sendOtp({
|
||||
// phoneNumber: newUser.phoneNumber,
|
||||
// });
|
||||
// }
|
||||
// redirect(
|
||||
// `/verify-otp?phone_number=${encodeURIComponent(newUser.phoneNumber)}`,
|
||||
// );
|
||||
// return { message: "User created successfully" };
|
||||
}
|
||||
|
||||
export const sendOtp = async (phoneNumber: string, code: string) => {
|
||||
|
@ -1,85 +1,79 @@
|
||||
"use server";
|
||||
|
||||
import prisma from "@/lib/db";
|
||||
import { VerifyUserDetails } from "@/lib/person";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { CreateClient } from "./ninja/client";
|
||||
|
||||
export async function VerifyUser(userId: string) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
include: {
|
||||
atoll: true,
|
||||
island: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
const isValidPerson = await VerifyUserDetails({ user });
|
||||
|
||||
if (!isValidPerson)
|
||||
throw new Error("The user details does not match national data.");
|
||||
|
||||
if (isValidPerson) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
verified: true,
|
||||
},
|
||||
});
|
||||
|
||||
const ninjaClient = await CreateClient({
|
||||
group_settings_id: "",
|
||||
address1: "",
|
||||
city: user.atoll?.name || "",
|
||||
state: user.island?.name || "",
|
||||
postal_code: "",
|
||||
country_id: "462",
|
||||
address2: user.address || "",
|
||||
contacts: {
|
||||
first_name: user.name?.split(" ")[0] || "",
|
||||
last_name: user.name?.split(" ")[1] || "",
|
||||
email: user.email || "",
|
||||
phone: user.phoneNumber || "",
|
||||
send_email: false,
|
||||
custom_value1: user.dob?.toISOString().split("T")[0] || "",
|
||||
custom_value2: user.id_card || "",
|
||||
custom_value3: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath("/users");
|
||||
// const user = await prisma.user.findUnique({
|
||||
// where: {
|
||||
// id: userId,
|
||||
// },
|
||||
// include: {
|
||||
// atoll: true,
|
||||
// island: true,
|
||||
// },
|
||||
// });
|
||||
// if (!user) {
|
||||
// throw new Error("User not found");
|
||||
// }
|
||||
// const isValidPerson = await VerifyUserDetails({ user });
|
||||
// if (!isValidPerson)
|
||||
// throw new Error("The user details does not match national data.");
|
||||
// if (isValidPerson) {
|
||||
// await prisma.user.update({
|
||||
// where: {
|
||||
// id: userId,
|
||||
// },
|
||||
// data: {
|
||||
// verified: true,
|
||||
// },
|
||||
// });
|
||||
// const ninjaClient = await CreateClient({
|
||||
// group_settings_id: "",
|
||||
// address1: "",
|
||||
// city: user.atoll?.name || "",
|
||||
// state: user.island?.name || "",
|
||||
// postal_code: "",
|
||||
// country_id: "462",
|
||||
// address2: user.address || "",
|
||||
// contacts: {
|
||||
// first_name: user.name?.split(" ")[0] || "",
|
||||
// last_name: user.name?.split(" ")[1] || "",
|
||||
// email: user.email || "",
|
||||
// phone: user.phoneNumber || "",
|
||||
// send_email: false,
|
||||
// custom_value1: user.dob?.toISOString().split("T")[0] || "",
|
||||
// custom_value2: user.id_card || "",
|
||||
// custom_value3: "",
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
// revalidatePath("/users");
|
||||
}
|
||||
|
||||
export async function Rejectuser({
|
||||
userId,
|
||||
reason,
|
||||
}: { userId: string; reason: string }) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
// const user = await prisma.user.findUnique({
|
||||
// where: {
|
||||
// id: userId,
|
||||
// },
|
||||
// });
|
||||
// if (!user) {
|
||||
// throw new Error("User not found");
|
||||
// }
|
||||
|
||||
await SendUserRejectionDetailSMS({
|
||||
details: reason,
|
||||
phoneNumber: user.phoneNumber,
|
||||
});
|
||||
await prisma.user.delete({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
});
|
||||
// await SendUserRejectionDetailSMS({
|
||||
// details: reason,
|
||||
// phoneNumber: user.phoneNumber,
|
||||
// });
|
||||
// await prisma.user.delete({
|
||||
// where: {
|
||||
// id: userId,
|
||||
// },
|
||||
// });
|
||||
revalidatePath("/users");
|
||||
redirect("/users");
|
||||
}
|
||||
@ -117,13 +111,13 @@ export async function AddDevice({
|
||||
mac_address,
|
||||
user_id,
|
||||
}: { name: string; mac_address: string; user_id: string }) {
|
||||
const newDevice = await prisma.device.create({
|
||||
data: {
|
||||
name: name,
|
||||
mac: mac_address,
|
||||
userId: user_id,
|
||||
},
|
||||
});
|
||||
// const newDevice = await prisma.device.create({
|
||||
// data: {
|
||||
// name: name,
|
||||
// mac: mac_address,
|
||||
// userId: user_id,
|
||||
// },
|
||||
// });
|
||||
revalidatePath("/devices");
|
||||
return newDevice;
|
||||
// return newDevice;
|
||||
}
|
||||
|
@ -1,12 +1,11 @@
|
||||
import LoginForm from "@/components/auth/login-form";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import { headers } from "next/headers";
|
||||
import Image from "next/image";
|
||||
import { redirect } from "next/navigation";
|
||||
import React from "react";
|
||||
|
||||
export default async function LoginPage() {
|
||||
|
||||
return (
|
||||
<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 ">
|
||||
|
@ -1,51 +1,53 @@
|
||||
import DevicesToPay from "@/components/devices-to-pay";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import prisma from "@/lib/db";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { headers } from "next/headers";
|
||||
import React from "react";
|
||||
export default async function PaymentPage({
|
||||
params,
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ paymentId: string }>;
|
||||
params: Promise<{ paymentId: string }>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers()
|
||||
})
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session?.session.userId
|
||||
}
|
||||
})
|
||||
const paymentId = (await params).paymentId;
|
||||
const payment = await prisma.payment.findUnique({
|
||||
where: {
|
||||
id: paymentId,
|
||||
},
|
||||
include: {
|
||||
devices: true,
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">
|
||||
Payment
|
||||
</h3>
|
||||
<span className={cn("text-sm border px-4 py-2 rounded-md uppercase font-semibold", payment?.paid ? "text-green-500 bg-green-500/20" : "text-yellow-500 bg-yellow-700")}>
|
||||
{payment?.paid ? "Paid" : "Pending"}
|
||||
</span>
|
||||
</div>
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: session?.session.userId,
|
||||
},
|
||||
});
|
||||
const paymentId = (await params).paymentId;
|
||||
const payment = await prisma.payment.findUnique({
|
||||
where: {
|
||||
id: paymentId,
|
||||
},
|
||||
include: {
|
||||
devices: true,
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm border px-4 py-2 rounded-md uppercase font-semibold",
|
||||
payment?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-700",
|
||||
)}
|
||||
>
|
||||
{payment?.paid ? "Paid" : "Pending"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DevicesToPay
|
||||
user={user || undefined}
|
||||
payment={payment || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
<div
|
||||
id="user-filters"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DevicesToPay user={user || undefined} payment={payment || undefined} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
|
||||
export const { GET, POST } = toNextJsHandler(auth.handler);
|
||||
|
108
app/auth.ts
Normal file
108
app/auth.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import { logout } from "@/queries/authentication";
|
||||
import type { NextAuthOptions } from "next-auth";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
pages: {
|
||||
signIn: "/auth/signin",
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
maxAge: 30 * 60, // 30 mins
|
||||
},
|
||||
events: {
|
||||
signOut({ token }) {
|
||||
const apitoken = token.apiToken;
|
||||
console.log("apitoken", apitoken);
|
||||
logout({ token: apitoken as string });
|
||||
},
|
||||
},
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "text", placeholder: "jsmith" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const { email, password } = credentials as {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
console.log("email and password", email, password);
|
||||
const res = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/auth/login/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: email,
|
||||
password: password,
|
||||
}),
|
||||
},
|
||||
);
|
||||
console.log("status", res.status);
|
||||
|
||||
const data = await res.json();
|
||||
console.log({ data });
|
||||
switch (res.status) {
|
||||
case 200:
|
||||
return { ...data.user, apiToken: data.token, expiry: data.expiry };
|
||||
case 400:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.message, status: res.status }),
|
||||
);
|
||||
case 429:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.message, status: res.status }),
|
||||
);
|
||||
case 403:
|
||||
throw new Error(
|
||||
JSON.stringify({ message: data.error, status: res.status }),
|
||||
);
|
||||
default:
|
||||
throw new Error(
|
||||
JSON.stringify({
|
||||
message: "FATAL: Unexprted Error occured!",
|
||||
status: res.status,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
redirect: async ({ url, baseUrl }) => {
|
||||
// Allows relative callback URLs
|
||||
if (url.startsWith("/")) return `${baseUrl}${url}`;
|
||||
return baseUrl;
|
||||
},
|
||||
session: async ({ session, token }) => {
|
||||
const sanitizedToken = Object.keys(token).reduce((p, c) => {
|
||||
// strip unnecessary properties
|
||||
if (c !== "iat" && c !== "exp" && c !== "jti" && c !== "apiToken") {
|
||||
Object.assign(p, { [c]: token[c] });
|
||||
}
|
||||
return p;
|
||||
}, {});
|
||||
// session.expires = token.expiry
|
||||
return {
|
||||
...session,
|
||||
user: sanitizedToken,
|
||||
apiToken: token.apiToken,
|
||||
// expires: token.expiry,
|
||||
};
|
||||
},
|
||||
jwt: ({ token, user }) => {
|
||||
if (typeof user !== "undefined") {
|
||||
// user has just signed in so the user object is populated
|
||||
return user as unknown as JWT;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
};
|
@ -1,14 +1,14 @@
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import prisma from "@/lib/db";
|
||||
import { headers } from "next/headers";
|
||||
import Link from "next/link";
|
||||
@ -17,180 +17,188 @@ import DeviceCard from "../device-card";
|
||||
import Pagination from "../pagination";
|
||||
|
||||
export async function AdminDevicesTable({
|
||||
searchParams,
|
||||
parentalControl,
|
||||
searchParams,
|
||||
parentalControl,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
}>;
|
||||
parentalControl?: boolean;
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
}>;
|
||||
parentalControl?: boolean;
|
||||
}) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers()
|
||||
})
|
||||
const isAdmin = session?.user.role === "ADMIN"
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const sortBy = (await searchParams)?.sortBy || "asc";
|
||||
const totalDevices = await prisma.device.count({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
{
|
||||
mac: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
const isAdmin = session?.user.role === "ADMIN";
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const sortBy = (await searchParams)?.sortBy || "asc";
|
||||
const totalDevices = await prisma.device.count({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
{
|
||||
mac: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(totalDevices / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
const totalPages = Math.ceil(totalDevices / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
|
||||
const devices = await prisma.device.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
{
|
||||
mac: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
User: true,
|
||||
payments: true,
|
||||
},
|
||||
skip: offset,
|
||||
take: limit,
|
||||
orderBy: {
|
||||
name: `${sortBy}` as "asc" | "desc",
|
||||
},
|
||||
});
|
||||
const devices = await prisma.device.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
{
|
||||
mac: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
User: true,
|
||||
payments: true,
|
||||
},
|
||||
skip: offset,
|
||||
take: limit,
|
||||
orderBy: {
|
||||
name: `${sortBy}` as "asc" | "desc",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
{devices.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No devices yet.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableCaption>Table of all devices.</TableCaption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Device Name</TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>MAC Address</TableHead>
|
||||
<TableHead>isActive</TableHead>
|
||||
<TableHead>blocked</TableHead>
|
||||
<TableHead>blockedBy</TableHead>
|
||||
<TableHead>expiryDate</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{devices.map((device) => (
|
||||
<TableRow key={device.id}>
|
||||
<TableCell>
|
||||
<div className="flex flex-col items-start">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/devices/${device.id}`}
|
||||
>
|
||||
{device.name}
|
||||
</Link>
|
||||
{device.isActive && (
|
||||
return (
|
||||
<div>
|
||||
{devices.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No devices yet.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableCaption>Table of all devices.</TableCaption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Device Name</TableHead>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>MAC Address</TableHead>
|
||||
<TableHead>isActive</TableHead>
|
||||
<TableHead>blocked</TableHead>
|
||||
<TableHead>blockedBy</TableHead>
|
||||
<TableHead>expiryDate</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{devices.map((device) => (
|
||||
<TableRow key={device.id}>
|
||||
<TableCell>
|
||||
<div className="flex flex-col items-start">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/devices/${device.id}`}
|
||||
>
|
||||
{device.name}
|
||||
</Link>
|
||||
{device.isActive && (
|
||||
<span className="text-muted-foreground">
|
||||
Active until{" "}
|
||||
{new Date().toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<span className="text-muted-foreground">
|
||||
Active until{" "}
|
||||
{new Date().toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
{device.blocked && (
|
||||
<div className="p-2 rounded border my-2">
|
||||
<span>Comment: </span>
|
||||
<p className="text-neutral-500">
|
||||
blocked because he was watching youtube
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
{device.User?.name}
|
||||
</TableCell>
|
||||
|
||||
{device.blocked && (
|
||||
<div className="p-2 rounded border my-2">
|
||||
<span>Comment: </span>
|
||||
<p className="text-neutral-500">
|
||||
blocked because he was watching youtube
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{device.User?.name}</TableCell>
|
||||
|
||||
<TableCell className="font-medium">{device.mac}</TableCell>
|
||||
<TableCell>
|
||||
{device.isActive ? "Active" : "Inactive"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{device.blocked ? "Blocked" : "Not Blocked"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{device.blocked ? device.blockedBy : ""}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date().toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BlockDeviceDialog admin={isAdmin} type={device.blocked ? "unblock" : "block"} device={device} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={7}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {devices.length} locations for "{query}
|
||||
"
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{totalDevices} devices
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination totalPages={totalPages} currentPage={page} />
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{devices.map((device) => (
|
||||
<DeviceCard parentalControl={parentalControl} key={device.id} device={device} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
<TableCell className="font-medium">{device.mac}</TableCell>
|
||||
<TableCell>
|
||||
{device.isActive ? "Active" : "Inactive"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{device.blocked ? "Blocked" : "Not Blocked"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{device.blocked ? device.blockedBy : ""}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date().toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<BlockDeviceDialog
|
||||
admin={isAdmin}
|
||||
type={device.blocked ? "unblock" : "block"}
|
||||
device={device}
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={7}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {devices.length} locations for "{query}
|
||||
"
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{totalDevices} devices
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination totalPages={totalPages} currentPage={page} />
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{devices.map((device) => (
|
||||
<DeviceCard
|
||||
parentalControl={parentalControl}
|
||||
key={device.id}
|
||||
device={device}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ import {
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import prisma from "@/lib/db";
|
||||
import { headers } from "next/headers";
|
||||
import { AccountPopover } from "./account-popver";
|
||||
@ -19,7 +19,7 @@ export async function ApplicationLayout({
|
||||
children,
|
||||
}: { children: React.ReactNode }) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers()
|
||||
headers: await headers(),
|
||||
});
|
||||
const billFormula = await prisma.billFormula.findFirst();
|
||||
const user = await prisma.user.findFirst({
|
||||
|
@ -23,6 +23,7 @@ export default function LoginForm() {
|
||||
<PhoneInput
|
||||
id="phone-number"
|
||||
name="phoneNumber"
|
||||
className="b0rder"
|
||||
maxLength={8}
|
||||
disabled={isPending}
|
||||
placeholder="Enter phone number"
|
||||
@ -32,11 +33,7 @@ export default function LoginForm() {
|
||||
{state.status === "error" && (
|
||||
<p className="text-red-500 text-sm">{state.message}</p>
|
||||
)}
|
||||
<Button
|
||||
className=""
|
||||
disabled={isPending}
|
||||
type="submit"
|
||||
>
|
||||
<Button className="" disabled={isPending} type="submit">
|
||||
{isPending ? <Loader2 className="animate-spin" /> : "Request OTP"}
|
||||
</Button>
|
||||
</div>
|
||||
|
@ -8,7 +8,7 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import prisma from "@/lib/db";
|
||||
import { headers } from "next/headers";
|
||||
import ClickableRow from "./clickable-row";
|
||||
@ -27,9 +27,9 @@ export async function DevicesTable({
|
||||
parentalControl?: boolean;
|
||||
}) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers()
|
||||
})
|
||||
const isAdmin = session?.user.role === "ADMIN"
|
||||
headers: await headers(),
|
||||
});
|
||||
const isAdmin = session?.user.role === "ADMIN";
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const sortBy = (await searchParams)?.sortBy || "asc";
|
||||
@ -53,12 +53,16 @@ export async function DevicesTable({
|
||||
NOT: {
|
||||
payments: {
|
||||
some: {
|
||||
paid: false
|
||||
}
|
||||
}
|
||||
paid: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
isActive: isAdmin ? undefined : parentalControl,
|
||||
blocked: isAdmin ? undefined : parentalControl !== undefined ? undefined : false,
|
||||
blocked: isAdmin
|
||||
? undefined
|
||||
: parentalControl !== undefined
|
||||
? undefined
|
||||
: false,
|
||||
},
|
||||
});
|
||||
|
||||
@ -86,8 +90,8 @@ export async function DevicesTable({
|
||||
NOT: {
|
||||
payments: {
|
||||
some: {
|
||||
paid: false
|
||||
}
|
||||
paid: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
isActive: parentalControl,
|
||||
@ -158,7 +162,12 @@ export async function DevicesTable({
|
||||
// )}
|
||||
// </TableCell>
|
||||
// </TableRow>
|
||||
<ClickableRow admin={isAdmin} key={device.id} device={device} parentalControl={parentalControl} />
|
||||
<ClickableRow
|
||||
admin={isAdmin}
|
||||
key={device.id}
|
||||
device={device}
|
||||
parentalControl={parentalControl}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
@ -181,7 +190,11 @@ export async function DevicesTable({
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{devices.map((device) => (
|
||||
<DeviceCard parentalControl={parentalControl} key={device.id} device={device} />
|
||||
<DeviceCard
|
||||
parentalControl={parentalControl}
|
||||
key={device.id}
|
||||
device={device}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
|
@ -1,17 +1,17 @@
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import prisma from "@/lib/db";
|
||||
import Link from "next/link";
|
||||
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { Calendar } from "lucide-react";
|
||||
@ -22,219 +22,258 @@ import { Button } from "./ui/button";
|
||||
import { Separator } from "./ui/separator";
|
||||
|
||||
type PaymentWithDevices = Prisma.PaymentGetPayload<{
|
||||
include: {
|
||||
devices: true;
|
||||
};
|
||||
}>
|
||||
include: {
|
||||
devices: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
export async function PaymentsTable({
|
||||
searchParams,
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
}>;
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
}>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers()
|
||||
})
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const totalPayments = await prisma.payment.count({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const totalPayments = await prisma.payment.count({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(totalPayments / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
const totalPages = Math.ceil(totalPayments / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
|
||||
const payments = await prisma.payment.findMany({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
devices: true
|
||||
},
|
||||
const payments = await prisma.payment.findMany({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
devices: true,
|
||||
},
|
||||
|
||||
skip: offset,
|
||||
take: limit,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
skip: offset,
|
||||
take: limit,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
{payments.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No Payments yet.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableCaption>Table of all devices.</TableCaption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Details</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
return (
|
||||
<div>
|
||||
{payments.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No Payments yet.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableCaption>Table of all devices.</TableCaption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Details</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{payments.map((payment) => (
|
||||
<TableRow key={payment.id}>
|
||||
<TableCell>
|
||||
<div className={cn("flex flex-col items-start border rounded p-2", payment?.paid ? "bg-green-500/10 border-dashed border-green=500" : "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50")}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground">
|
||||
{new Date(payment.createdAt).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{payments.map((payment) => (
|
||||
<TableRow key={payment.id}>
|
||||
<TableCell>
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2",
|
||||
payment?.paid
|
||||
? "bg-green-500/10 border-dashed border-green=500"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground">
|
||||
{new Date(payment.createdAt).toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link className="font-medium hover:underline" href={`/payments/${payment.id}`}>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge className={cn(payment?.paid ? "text-green-500 bg-green-500/20" : "text-yellow-500 bg-yellow-500/20")} variant={payment.paid ? "outline" : "secondary"}>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li key={device.id} className="text-sm text-muted-foreground">
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium" >
|
||||
{payment.numberOfMonths} Months
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.amount.toFixed(2)}
|
||||
</span>
|
||||
MVR
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {payments.length} locations for "{query}
|
||||
"
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{totalPayments} payments
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination totalPages={totalPages} currentPage={page} />
|
||||
</div>
|
||||
<div className="sm:hidden block">
|
||||
{payments.map((payment) => (
|
||||
<MobilePaymentDetails key={payment.id} payment={payment} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/payments/${payment.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge
|
||||
className={cn(
|
||||
payment?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={payment.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li
|
||||
key={device.id}
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
{payment.numberOfMonths} Months
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.amount.toFixed(2)}
|
||||
</span>
|
||||
MVR
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {payments.length} locations for "{query}
|
||||
"
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{totalPayments} payments
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination totalPages={totalPages} currentPage={page} />
|
||||
</div>
|
||||
<div className="sm:hidden block">
|
||||
{payments.map((payment) => (
|
||||
<MobilePaymentDetails key={payment.id} payment={payment} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
function MobilePaymentDetails({ payment }: { payment: PaymentWithDevices }) {
|
||||
return (
|
||||
<div className={cn("flex flex-col items-start border rounded p-2", payment?.paid ? "bg-green-500/10 border-dashed border-green=500" : "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50")}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(payment.createdAt).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2",
|
||||
payment?.paid
|
||||
? "bg-green-500/10 border-dashed border-green=500"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(payment.createdAt).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link className="font-medium hover:underline" href={`/payments/${payment.id}`}>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge className={cn(payment?.paid ? "text-green-500 bg-green-500/20" : "text-yellow-500 bg-yellow-500/20")} variant={payment.paid ? "outline" : "secondary"}>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li key={device.id} className="text-sm text-muted-foreground">
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div className="block sm:hidden">
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Duration</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.numberOfMonths} Months
|
||||
</span>
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/payments/${payment.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge
|
||||
className={cn(
|
||||
payment?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={payment.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
<ol className="list-disc list-inside text-sm">
|
||||
{payment.devices.map((device) => (
|
||||
<li key={device.id} className="text-sm text-muted-foreground">
|
||||
{device.name}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div className="block sm:hidden">
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Duration</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.numberOfMonths} Months
|
||||
</span>
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
@ -5,164 +5,160 @@ import flags from "react-phone-number-input/flags";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type PhoneInputProps = Omit<
|
||||
React.ComponentProps<"input">,
|
||||
"onChange" | "value" | "ref"
|
||||
React.ComponentProps<"input">,
|
||||
"onChange" | "value" | "ref"
|
||||
> &
|
||||
Omit<RPNInput.Props<typeof RPNInput.default>, "onChange"> & {
|
||||
onChange?: (value: RPNInput.Value) => void;
|
||||
};
|
||||
Omit<RPNInput.Props<typeof RPNInput.default>, "onChange"> & {
|
||||
onChange?: (value: RPNInput.Value) => void;
|
||||
};
|
||||
|
||||
const PhoneInput: React.ForwardRefExoticComponent<PhoneInputProps> =
|
||||
React.forwardRef<React.ElementRef<typeof RPNInput.default>, PhoneInputProps>(
|
||||
({ className, onChange, ...props }, ref) => {
|
||||
return (
|
||||
<RPNInput.default
|
||||
ref={ref}
|
||||
className={cn("flex", className)}
|
||||
flagComponent={FlagComponent}
|
||||
countrySelectComponent={CountrySelect}
|
||||
inputComponent={InputComponent}
|
||||
smartCaret={false}
|
||||
/**
|
||||
* Handles the onChange event.
|
||||
*
|
||||
* react-phone-number-input might trigger the onChange event as undefined
|
||||
* when a valid phone number is not entered. To prevent this,
|
||||
* the value is coerced to an empty string.
|
||||
*
|
||||
* @param {E164Number | undefined} value - The entered value
|
||||
*/
|
||||
onChange={(value) => onChange?.(value || ("" as RPNInput.Value))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
React.forwardRef<React.ElementRef<typeof RPNInput.default>, PhoneInputProps>(
|
||||
({ className, onChange, ...props }, ref) => {
|
||||
return (
|
||||
<RPNInput.default
|
||||
ref={ref}
|
||||
className={cn("flex", className)}
|
||||
flagComponent={FlagComponent}
|
||||
countrySelectComponent={CountrySelect}
|
||||
inputComponent={InputComponent}
|
||||
smartCaret={false}
|
||||
/**
|
||||
* Handles the onChange event.
|
||||
*
|
||||
* react-phone-number-input might trigger the onChange event as undefined
|
||||
* when a valid phone number is not entered. To prevent this,
|
||||
* the value is coerced to an empty string.
|
||||
*
|
||||
* @param {E164Number | undefined} value - The entered value
|
||||
*/
|
||||
onChange={(value) => onChange?.(value || ("" as RPNInput.Value))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
PhoneInput.displayName = "PhoneInput";
|
||||
|
||||
const InputComponent = React.forwardRef<
|
||||
HTMLInputElement,
|
||||
React.ComponentProps<"input">
|
||||
HTMLInputElement,
|
||||
React.ComponentProps<"input">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<Input
|
||||
className={cn("rounded-e-lg rounded-s-none", className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
<Input className={cn("mx-2", className)} {...props} ref={ref} />
|
||||
));
|
||||
InputComponent.displayName = "InputComponent";
|
||||
|
||||
type CountryEntry = { label: string; value: RPNInput.Country | undefined };
|
||||
|
||||
type CountrySelectProps = {
|
||||
disabled?: boolean;
|
||||
value: RPNInput.Country;
|
||||
options: CountryEntry[];
|
||||
onChange: (country: RPNInput.Country) => void;
|
||||
disabled?: boolean;
|
||||
value: RPNInput.Country;
|
||||
options: CountryEntry[];
|
||||
onChange: (country: RPNInput.Country) => void;
|
||||
};
|
||||
|
||||
const CountrySelect = ({
|
||||
disabled,
|
||||
value: selectedCountry,
|
||||
options: countryList,
|
||||
onChange,
|
||||
disabled,
|
||||
value: selectedCountry,
|
||||
options: countryList,
|
||||
onChange,
|
||||
}: CountrySelectProps) => {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="flex gap-1 rounded-e-none rounded-s-lg border-r-0 px-3 focus:z-10"
|
||||
disabled={true}
|
||||
>
|
||||
<FlagComponent
|
||||
country={selectedCountry}
|
||||
countryName={selectedCountry}
|
||||
/>
|
||||
<ChevronsUpDown
|
||||
className={cn(
|
||||
"-mr-2 size-4 opacity-50",
|
||||
disabled ? "hidden" : "opacity-100",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[300px] p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search country..." />
|
||||
<CommandList>
|
||||
<ScrollArea className="h-72">
|
||||
<CommandEmpty>No country found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{countryList.map(({ value, label }) =>
|
||||
value ? (
|
||||
<CountrySelectOption
|
||||
key={value}
|
||||
country={value}
|
||||
countryName={label}
|
||||
selectedCountry={selectedCountry}
|
||||
onChange={onChange}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</CommandGroup>
|
||||
</ScrollArea>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="flex gap-1 px-3 focus:z-10"
|
||||
disabled={true}
|
||||
>
|
||||
<FlagComponent
|
||||
country={selectedCountry}
|
||||
countryName={selectedCountry}
|
||||
/>
|
||||
<ChevronsUpDown
|
||||
className={cn(
|
||||
"-mr-2 size-4 opacity-50",
|
||||
disabled ? "hidden" : "opacity-100",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[300px] p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search country..." />
|
||||
<CommandList>
|
||||
<ScrollArea className="h-72">
|
||||
<CommandEmpty>No country found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{countryList.map(({ value, label }) =>
|
||||
value ? (
|
||||
<CountrySelectOption
|
||||
key={value}
|
||||
country={value}
|
||||
countryName={label}
|
||||
selectedCountry={selectedCountry}
|
||||
onChange={onChange}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</CommandGroup>
|
||||
</ScrollArea>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
interface CountrySelectOptionProps extends RPNInput.FlagProps {
|
||||
selectedCountry: RPNInput.Country;
|
||||
onChange: (country: RPNInput.Country) => void;
|
||||
selectedCountry: RPNInput.Country;
|
||||
onChange: (country: RPNInput.Country) => void;
|
||||
}
|
||||
|
||||
const CountrySelectOption = ({
|
||||
country,
|
||||
countryName,
|
||||
selectedCountry,
|
||||
onChange,
|
||||
country,
|
||||
countryName,
|
||||
selectedCountry,
|
||||
onChange,
|
||||
}: CountrySelectOptionProps) => {
|
||||
return (
|
||||
<CommandItem className="gap-2" onSelect={() => onChange(country)}>
|
||||
<FlagComponent country={country} countryName={countryName} />
|
||||
<span className="flex-1 text-sm">{countryName}</span>
|
||||
<span className="text-sm text-foreground/50">{`+${RPNInput.getCountryCallingCode(country)}`}</span>
|
||||
<CheckIcon
|
||||
className={`ml-auto size-4 ${country === selectedCountry ? "opacity-100" : "opacity-0"}`}
|
||||
/>
|
||||
</CommandItem>
|
||||
);
|
||||
return (
|
||||
<CommandItem className="gap-2" onSelect={() => onChange(country)}>
|
||||
<FlagComponent country={country} countryName={countryName} />
|
||||
<span className="flex-1 text-sm">{countryName}</span>
|
||||
<span className="text-sm text-foreground/50">{`+${RPNInput.getCountryCallingCode(country)}`}</span>
|
||||
<CheckIcon
|
||||
className={`ml-auto size-4 ${country === selectedCountry ? "opacity-100" : "opacity-0"}`}
|
||||
/>
|
||||
</CommandItem>
|
||||
);
|
||||
};
|
||||
|
||||
const FlagComponent = ({ country, countryName }: RPNInput.FlagProps) => {
|
||||
const Flag = flags[country];
|
||||
const Flag = flags[country];
|
||||
|
||||
return (
|
||||
<span className="flex scale-125 h-4 w-6 overflow-hidden rounded-sm cursor-not-allowed">
|
||||
{Flag && <Flag title={countryName} />}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<span className="flex scale-125 h-4 w-6 overflow-hidden rounded-sm cursor-not-allowed">
|
||||
{Flag && <Flag title={countryName} />}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export { PhoneInput };
|
||||
|
@ -1,7 +0,0 @@
|
||||
import { phoneNumberClient } from "better-auth/client/plugins";
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: process.env.BETTER_AUTH_URL,
|
||||
plugins: [phoneNumberClient()],
|
||||
});
|
@ -1,5 +1,5 @@
|
||||
"use server";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { auth } from "@/app/auth";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
import { headers } from "next/headers";
|
||||
import { cache } from "react";
|
||||
import { auth } from "./auth";
|
||||
import { auth } from "../app/auth";
|
||||
|
||||
const getCurrentUserCache = cache(async () => {
|
||||
const session = await auth.api.getSession({
|
||||
|
44
lib/auth.ts
44
lib/auth.ts
@ -1,44 +0,0 @@
|
||||
import { sendOtp } from "@/actions/auth-actions";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { phoneNumber } from "better-auth/plugins";
|
||||
import prisma from "./db";
|
||||
|
||||
export const auth = betterAuth({
|
||||
session: {
|
||||
cookieCache: {
|
||||
enabled: true,
|
||||
maxAge: 10 * 60, // Cache duration in seconds
|
||||
},
|
||||
},
|
||||
trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS?.split(",") || [
|
||||
"localhost:3000",
|
||||
],
|
||||
user: {
|
||||
additionalFields: {
|
||||
role: {
|
||||
type: "string",
|
||||
required: false,
|
||||
defaultValue: "USER",
|
||||
input: false, // don't allow user to set role
|
||||
},
|
||||
lang: {
|
||||
type: "string",
|
||||
required: false,
|
||||
defaultValue: "en",
|
||||
},
|
||||
},
|
||||
},
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: "postgresql", // or "mysql", "postgresql", ...etc
|
||||
}),
|
||||
plugins: [
|
||||
phoneNumber({
|
||||
sendOTP: async ({ phoneNumber, code }) => {
|
||||
// Implement sending OTP code via SMS
|
||||
console.log("Send OTP in auth.ts", phoneNumber, code);
|
||||
await sendOtp(phoneNumber, code);
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
17
lib/db.ts
17
lib/db.ts
@ -1,17 +0,0 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const prismaClientSingleton = () => {
|
||||
return new PrismaClient();
|
||||
};
|
||||
|
||||
type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClientSingleton | undefined;
|
||||
};
|
||||
|
||||
const prisma = globalForPrisma.prisma ?? prismaClientSingleton();
|
||||
|
||||
export default prisma;
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
38
lib/types/user.ts
Normal file
38
lib/types/user.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import type { ISODateString } from "next-auth";
|
||||
|
||||
export interface Permission {
|
||||
id: number;
|
||||
name: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface TAuthUser {
|
||||
expiry?: string;
|
||||
token?: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
user_permissions: Permission[];
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
is_superuser: boolean;
|
||||
date_joined: string;
|
||||
last_login: string;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
user?: {
|
||||
token?: string;
|
||||
name?: string | null;
|
||||
email?: string | null;
|
||||
image?: string | null;
|
||||
user?: User & {
|
||||
expiry?: string;
|
||||
};
|
||||
};
|
||||
expires: ISODateString;
|
||||
}
|
745
package-lock.json
generated
745
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -17,7 +17,6 @@
|
||||
"dependencies": {
|
||||
"@faker-js/faker": "^9.3.0",
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@prisma/client": "^6.1.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.2",
|
||||
"@radix-ui/react-checkbox": "^1.1.2",
|
||||
"@radix-ui/react-collapsible": "^1.1.1",
|
||||
@ -31,7 +30,7 @@
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@tanstack/react-query": "^5.61.4",
|
||||
"better-auth": "^1.1.13",
|
||||
"axios": "^1.8.4",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
@ -41,12 +40,12 @@
|
||||
"moment": "^2.30.1",
|
||||
"motion": "^11.15.0",
|
||||
"next": "15.1.2",
|
||||
"next-auth": "^4.24.11",
|
||||
"next-themes": "^0.4.3",
|
||||
"nextjs-toploader": "^3.7.15",
|
||||
"prisma": "^6.1.0",
|
||||
"react": "19.0.0",
|
||||
"react-aria-components": "^1.5.0",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-day-picker": "^9.6.3",
|
||||
"react-dom": "19.0.0",
|
||||
"react-hook-form": "^7.53.2",
|
||||
"react-phone-number-input": "^3.4.9",
|
||||
@ -68,4 +67,4 @@
|
||||
"typescript": "^5.7.2"
|
||||
},
|
||||
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +0,0 @@
|
||||
"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();
|
||||
}
|
48
queries/authentication.ts
Normal file
48
queries/authentication.ts
Normal file
@ -0,0 +1,48 @@
|
||||
"use server";
|
||||
import type { TAuthUser } from "@/lib/types/user";
|
||||
import axiosInstance from "@/utils/axiosInstance";
|
||||
|
||||
export async function login({
|
||||
password,
|
||||
username,
|
||||
}: {
|
||||
username: string;
|
||||
password: string;
|
||||
}): Promise<TAuthUser> {
|
||||
const response = await axiosInstance
|
||||
.post("/auth/login/", {
|
||||
username: username,
|
||||
password: password,
|
||||
})
|
||||
.then((res) => {
|
||||
console.log(res);
|
||||
return res.data; // Return the data from the response
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err.response);
|
||||
throw err; // Throw the error to maintain the Promise rejection
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
export async function logout({ token }: { token: string }) {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/auth/logout/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${token}`, // Include the token for authentication
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.status !== 204) {
|
||||
throw new Error("Failed to log out from the backend");
|
||||
}
|
||||
console.log("logout res in backend", response);
|
||||
|
||||
// Since the API endpoint returns 204 No Content on success, we don't need to parse JSON
|
||||
return null; // Return null to indicate a successful logout with no content
|
||||
}
|
13
utils/axiosInstance.ts
Normal file
13
utils/axiosInstance.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import axios from "axios";
|
||||
|
||||
axios.defaults.xsrfCookieName = "csrftoken";
|
||||
axios.defaults.xsrfHeaderName = "X-CSRFToken";
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
||||
validateStatus: (status) => {
|
||||
return status < 500; // Resolve only if the status code is less than 500
|
||||
},
|
||||
});
|
||||
|
||||
export default axiosInstance;
|
Loading…
x
Reference in New Issue
Block a user