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