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:
2025-03-23 15:07:03 +05:00
parent 0fd269df31
commit 020d74c5e2
23 changed files with 1269 additions and 1271 deletions

View File

@ -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 ">

View File

@ -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>
);
}

View File

@ -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
View 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,
};