mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
Move auth config and build admin menus
Extract NextAuth configuration into a shared library, load admin sidebar items from role permissions, and update related RBAC types and UI.
This commit is contained in:
+197
@@ -0,0 +1,197 @@
|
||||
import { type NextAuthOptions } from "next-auth"
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
|
||||
const { BASE_URL_API, DEVICE_CODE } = process.env
|
||||
|
||||
/**
|
||||
* CUSTOM NEXTAUTH EXP
|
||||
* THIS VALUE SHOULD BE LESS THAN ACCESS TOKEN EXP (EX: 1 days)
|
||||
* */
|
||||
export const EXP_SESSION = 12 * 60 * 60 // 12 hours
|
||||
// const EXP_SESSION = 24 * 60 * 60 // 1 days
|
||||
// const EXP_SESSION = 10 // 10 seconds
|
||||
|
||||
// Determine if we are using HTTPS
|
||||
async function refreshAccessToken(token: any) {
|
||||
// If the access token has expired, try to refresh it
|
||||
try {
|
||||
// FOR INSECURE SSL (ex: Self Signed Certificates)
|
||||
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
||||
|
||||
// 1. Race Condition Check:
|
||||
// If we refreshed recently (within 10s), return the current token
|
||||
// to prevent parallel requests from spamming the API.
|
||||
if (token.last_refreshed && Date.now() - token.last_refreshed < 10000) {
|
||||
return token;
|
||||
}
|
||||
console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`)
|
||||
|
||||
const response = await fetch(BASE_URL_API + "/auth/refresh-token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Refresh-Token": token?.refresh_token,
|
||||
"Device-Code": DEVICE_CODE || "40001",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: token?.detail.email
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data)
|
||||
|
||||
if (!response.ok) throw token
|
||||
|
||||
console.log("[REFRESH] Success. New Access Token received.")
|
||||
return {
|
||||
...token, // Keep the previous token properties
|
||||
access_token: data.data.access_token,
|
||||
refresh_token: data.data.refresh_token,
|
||||
expired_at: Math.floor(Date.now() + EXP_SESSION * 1000),
|
||||
last_refreshed: Date.now(), // Mark this refresh
|
||||
error: null, // Clear errors
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("[REFRESH] Error refreshing access token", error)
|
||||
|
||||
return {
|
||||
...token,
|
||||
error: "RefreshAccessTokenError",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const authOptions: NextAuthOptions = {
|
||||
// FORCE COOKIE SETTINGS (To fix localhost rejection)
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: {},
|
||||
password: {}
|
||||
},
|
||||
async authorize(credentials, req) {
|
||||
// FOR INSECURE SSL (ex: Self Signed Certificates)
|
||||
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
||||
|
||||
const { email, password } = credentials as any;
|
||||
|
||||
const res = await fetch(`${BASE_URL_API}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password, }),
|
||||
});
|
||||
|
||||
const data: any = await res.json();
|
||||
|
||||
if (res.ok) {
|
||||
if (data) {
|
||||
const rawDetail = data.data.detail;
|
||||
|
||||
const keepNonAdminMenu = rawDetail?.role?.role_detail?.filter((item: any) => item?.menu?.is_admin_menu === false).map((item: any) => ({
|
||||
action: item.action,
|
||||
menu: {
|
||||
name: item.menu.name,
|
||||
icon: item.menu.icon,
|
||||
path_url: item.menu.path_url,
|
||||
}
|
||||
}))
|
||||
|
||||
const cleanDetail = {
|
||||
id: rawDetail.id,
|
||||
email: rawDetail.email,
|
||||
nik: rawDetail.nik,
|
||||
fullname: rawDetail.fullname,
|
||||
nickname: rawDetail.nickname,
|
||||
avatar: rawDetail.avatar,
|
||||
phone_number: rawDetail.phone_number,
|
||||
role: {
|
||||
id: rawDetail.role?.id,
|
||||
code: rawDetail.role?.code,
|
||||
name: rawDetail.role?.name,
|
||||
allow_admin_panel: rawDetail.role?.allow_admin_panel,
|
||||
role_detail: keepNonAdminMenu
|
||||
}
|
||||
};
|
||||
|
||||
// console.log(cleanDetail.role)
|
||||
|
||||
return {
|
||||
access_token: data.data.access_token,
|
||||
refresh_token: data.data.refresh_token,
|
||||
detail: cleanDetail, // <--- Using the Pruned Object
|
||||
expired_at: Math.floor(Date.now() + (EXP_SESSION * 1000)),
|
||||
last_refreshed: Date.now()
|
||||
} as any;
|
||||
} else {
|
||||
throw new Error(`Invalid email or password`)
|
||||
}
|
||||
} else {
|
||||
throw new Error(data.message)
|
||||
}
|
||||
}
|
||||
})
|
||||
],
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
|
||||
/* SET MAX_AGE IF NOT USING REFRESH TOKEN */
|
||||
// maxAge: 30 * 24 * 60 * 60, // 30 days
|
||||
// maxAge: 24 * 60 * 60, // 1 days
|
||||
// maxAge: 10, // 10 seconds
|
||||
// updateAge: 10, // 1 days
|
||||
},
|
||||
pages: {
|
||||
signIn: "/auth",
|
||||
// newUser: "/complete-account" // where to redirect if user is new
|
||||
// signOut: "/login"
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user, account, profile, trigger, session }: any) {
|
||||
|
||||
// 1. Handle Update Trigger (Client side update)
|
||||
if (trigger === "update" && session?.access_token) {
|
||||
// Note, that `session` can be any arbitrary object, remember to validate it!
|
||||
console.log("====================================== MASUK KE JWT ========================================")
|
||||
console.log("============================ SESSION UPDATED FROM THE CLIENT ===================================")
|
||||
|
||||
// const newSession = {
|
||||
// ...session, // Keep the previous token properties
|
||||
// expired_at: Math.floor(Date.now() + EXP_SESSION * 1000) // UPDATE NEXTAUTH SESSION EXP
|
||||
// }
|
||||
// console.log({ session: newSession })
|
||||
// return newSession
|
||||
return session
|
||||
}
|
||||
|
||||
// 2. Initial Sign In
|
||||
if (user) {
|
||||
return { ...token, ...user }
|
||||
}
|
||||
|
||||
// 3. Safety Check: If we somehow lost the access token, return what we have (or error)
|
||||
if (!token?.access_token) {
|
||||
console.log("JWT callback: token already null, skipping refresh.");
|
||||
return token;
|
||||
}
|
||||
|
||||
// 4. Check Validity
|
||||
// If expired_at is missing, we assume we need to refresh (safety)
|
||||
// Refresh 15 seconds *before* it actually dies to prevent timing issues
|
||||
const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000));
|
||||
|
||||
if (isValid) return token;
|
||||
|
||||
// 5. Token Expired (or missing expiry), Refresh it
|
||||
console.log(`[JWT] Token Expired (or invalid timestamp). Refreshing... Current: ${Date.now()}, ExpiredAt: ${token.expired_at}`)
|
||||
return await refreshAccessToken(token)
|
||||
},
|
||||
async session({ session, token, user }) {
|
||||
// Send properties to the client, like an access_token from a provider.
|
||||
session.user = token as any;
|
||||
|
||||
return session;
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { signOut, useSession } from "next-auth/react";
|
||||
import axios from "../axios";
|
||||
import { EXP_SESSION } from "@/pages/api/auth/[...nextauth]";
|
||||
import { EXP_SESSION } from "../auth";
|
||||
|
||||
export const useRefreshToken = () => {
|
||||
const { data: session, update } = useSession();
|
||||
|
||||
+1
-1
@@ -1,8 +1,8 @@
|
||||
import { getServerSession } from "next-auth"
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"
|
||||
import { redirect } from "next/navigation"
|
||||
import { ResponseData } from "@/types/types"
|
||||
import { logger } from "./logger"
|
||||
import { authOptions } from "./auth"
|
||||
|
||||
export default async function fetchData(url: string = '/', cache: "default" | "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" = 'default', next?: NextFetchRequestConfig) {
|
||||
const { BASE_URL_API } = process.env
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// "use server" opens a door from the client to the server, Exports must be async Server Functions. use for Form submissions, mutations, client-triggered server actions
|
||||
// But import "server-only" locks the client out of a module, cannot call by client components. use for Database, auth, secret API calls
|
||||
|
||||
import "server-only";
|
||||
import { cache } from "react";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { ResponseData } from "@/types/types";
|
||||
import { redirect } from "next/navigation";
|
||||
import { authOptions } from "./auth";
|
||||
|
||||
export const getAccessData = cache(async () => {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
// Validate session first
|
||||
if (!session?.user?.detail?.role?.id) {
|
||||
redirect("/auth?error=Session%20error%20or%20has%20expired");
|
||||
}
|
||||
|
||||
const res = await fetch(`${process.env.BASE_URL_API}/role/${session?.user.detail.role.id}`,
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${session?.user.access_token}`,
|
||||
},
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
|
||||
// This will activate the closest `error.js` Error Boundar`)
|
||||
throw new Error(`Failed to retrieve access data (${res.status}) ${res.statusText}`);
|
||||
}
|
||||
|
||||
const data: ResponseData = await res.json()
|
||||
|
||||
return data.data
|
||||
});
|
||||
|
||||
export async function reqAccessPagePermission(path: string, action: string = "view", redirectPage: "/forbidden") {
|
||||
const accessData = await getAccessData();
|
||||
|
||||
// Check whether the current page is registered
|
||||
const menu = accessData?.role_detail?.find((item: any) => item.menu?.path_url === path);
|
||||
|
||||
if (!menu) {
|
||||
redirect(redirectPage);
|
||||
}
|
||||
|
||||
// Check whether the user has permission
|
||||
if (!menu.action?.includes(action)) {
|
||||
redirect(redirectPage);
|
||||
}
|
||||
|
||||
return menu;
|
||||
}
|
||||
+1
-1
@@ -1,9 +1,9 @@
|
||||
"use server"
|
||||
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/pages/api/auth/[...nextauth]"; // Adjust path as needed
|
||||
import axios from "@/lib/axios"; // Your axios instance
|
||||
import { writeLog } from "./logger";
|
||||
import { authOptions } from "./auth";
|
||||
|
||||
// 1. Define a standard response format for all your actions
|
||||
export type ActionResponse<T = any> =
|
||||
|
||||
Reference in New Issue
Block a user