Deduplicate token refresh and sync sessions

Caches and deduplicates token refreshes, syncs refreshed tokens to the browser session, and updates auth configuration and documentation. Adds an RBAC requirements draft. The new credentials.md contains VPS credentials; remove it from the commit and rotate those credentials.
This commit is contained in:
Ichsan Kurniawan
2026-11-13 15:01:46 +07:00
parent 230213cd2e
commit ff802a5b5d
5 changed files with 380 additions and 69 deletions
+22
View File
@@ -35,6 +35,28 @@ The easiest way to deploy your Next.js app is to use the [Vercel Platform](https
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
```js
// actions/assignments.ts
"use server";
import { revalidatePath } from "next/cache";
export async function updateAssignmentTeamAction(assignmentId: string, employeeIds: string[]) {
// 1. Await your database update logic here
// await db.assignments.update({ where: { id: assignmentId }, data: { assignedEmployees: employeeIds } })
// 2. Tell Next.js to refresh the Server Component with fresh data
revalidatePath(`/task/client-detail/[client_id]`, 'page');
}
export async function updateAssignmentStatusAction(assignmentId: string, statusData: any) {
// 1. Await your database update logic here
// 2. Tell Next.js to refresh the Server Component
revalidatePath(`/task/client-detail/[client_id]`, 'page');
}
```
## Deploy on VPS
```bash
+13
View File
@@ -0,0 +1,13 @@
VPS Credentials
ip : 36.66.3.44
port : 22
user : root
pass : YT6ZAeM33N
production environment
project path => /home/repositories/hats-app (or /home/repository/hats-app)
pm2 name => hats-app
staging environment
project path => /home/repositories/hats-app-dev/hats-app (or /home/repository/hats-app-dev/hats-app)
pm2 name => hats-app-dev
+60 -36
View File
@@ -1,7 +1,8 @@
import { type NextAuthOptions } from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
const { BASE_URL_API, DEVICE_CODE } = process.env
const BASE_URL_API = process.env.BASE_URL_API_LOCAL_SERVER;
const DEVICE_CODE = process.env.DEVICE_CODE || "40001";
/**
* CUSTOM NEXTAUTH EXP
@@ -11,20 +12,30 @@ 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'
// In-flight refresh promise map & short-lived cache (survives across parallel requests in the same Node.js process)
const refreshPromises = new Map<string, Promise<any>>();
const recentRefreshedTokens = new Map<string, { token: any; expiresAt: number }>();
// 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;
async function refreshAccessToken(token: any) {
const key = token?.detail?.email || token?.access_token?.slice(-10) || "default";
// 1. If we have a recently refreshed token in memory (within last 30s), reuse it immediately
const cached = recentRefreshedTokens.get(key);
if (cached && Date.now() < cached.expiresAt) {
console.log(`[REFRESH] Reusing recently refreshed token for ${key}`);
return cached.token;
}
console.log(`[REFRESH] Attempting refresh for token ending in... ${token.access_token?.slice(-5)}`)
// 2. If a refresh is already in-flight for this user/token, await that same promise (deduplication)
if (refreshPromises.has(key)) {
console.log(`[REFRESH] Waiting for existing in-flight refresh for ${key}`);
return await refreshPromises.get(key);
}
// 3. Initiate the refresh promise
const promise = (async () => {
try {
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",
@@ -34,32 +45,49 @@ async function refreshAccessToken(token: any) {
"Device-Code": DEVICE_CODE || "40001",
},
body: JSON.stringify({
email: token?.detail.email
email: token?.detail?.email
}),
})
});
const data = await response.json()
console.log(data)
const data = await response.json();
if (!response.ok) throw token
if (!response.ok) {
console.log("[REFRESH] Refresh API returned error:", data);
throw data;
}
console.log("[REFRESH] Success. New Access Token received.")
return {
console.log("[REFRESH] Success. New Access Token received.");
const newToken = {
...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
is_refreshed: true, // Signal client to sync cookie
error: null, // Clear errors
}
};
// Cache for 30 seconds to absorb parallel requests and immediate Fast Refresh bursts
recentRefreshedTokens.set(key, {
token: newToken,
expiresAt: Date.now() + 30000,
});
return newToken;
} catch (error) {
console.log("[REFRESH] Error refreshing access token", error)
console.log("[REFRESH] Error refreshing access token", error);
return {
...token,
error: "RefreshAccessTokenError",
};
} finally {
refreshPromises.delete(key);
}
})();
refreshPromises.set(key, promise);
return await promise;
}
export const authOptions: NextAuthOptions = {
@@ -150,19 +178,15 @@ export const authOptions: NextAuthOptions = {
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
// 1. Handle Update Trigger (Client side update / cookie sync)
if (trigger === "update") {
if (session?.access_token) {
return { ...token, ...session, is_refreshed: false };
}
const isValid = token.expired_at && (Date.now() < (token.expired_at - 15000));
if (isValid) return { ...token, is_refreshed: false };
const refreshed = await refreshAccessToken(token);
return { ...refreshed, is_refreshed: false };
}
// 2. Initial Sign In
@@ -181,7 +205,7 @@ export const authOptions: NextAuthOptions = {
// 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;
if (isValid) return { ...token, is_refreshed: false };
// 5. Token Expired (or missing expiry), Refresh it
console.log(`[JWT] Token Expired (or invalid timestamp). Refreshing... Current: ${Date.now()}, ExpiredAt: ${token.expired_at}`)
+28 -6
View File
@@ -1,8 +1,8 @@
'use client'
import { ReactNode } from 'react';
import { ReactNode, useEffect, useRef } from 'react';
import { type Session } from 'next-auth';
import { SessionProvider as Provider } from 'next-auth/react'
import { SessionProvider as Provider, useSession } from 'next-auth/react'
type Props = {
children: ReactNode,
@@ -10,13 +10,35 @@ type Props = {
basePath?: string
};
const SessionProvider: React.FC<Props> = ({ children, session }) => {
function SessionSync() {
const { data: session, update } = useSession();
const isUpdatingRef = useRef(false);
useEffect(() => {
const user = session?.user as any;
if (!user) return;
// If the token was refreshed on the server during SSR / Server Components,
// the browser cookie was not updated because Server Components cannot set cookies.
// We trigger update() to hit /api/auth/session, which writes the updated Set-Cookie header.
if (user.is_refreshed && !isUpdatingRef.current) {
isUpdatingRef.current = true;
user.is_refreshed = false;
update().finally(() => {
isUpdatingRef.current = false;
});
}
}, [session, update]);
return null;
}
const SessionProvider: React.FC<Props> = ({ children, session, basePath }) => {
return (
<>
<Provider session={session}>
<Provider session={session} basePath={basePath} refetchInterval={10 * 60}>
<SessionSync />
{children}
</Provider>
</>
);
}
+230
View File
@@ -0,0 +1,230 @@
Saya ingin membangun RBAC Role-Based Access Control pada project ini
Akan terdapat menu baru nantinya yaitu menu Access Permissions dan Menu Management, untuk User Role existing gunakan menu yang ada pada `/information/user-role`
Menu Access Permissions akan berada pada path RBAC yang ber sub menu Permissions, Menu dan Role
Masing-masing pathnya:
Access Permissions => `/rbac/action-pemission`
Menu => `/rbac/menu`
User Role => `/rbac/user-role`
### Access Permission
untuk menu Access Permission akan terdapat operasi CRUD seperti pada menu admin yang lain, dimana form field nya akan berisi
name => permission name
deskripsi => deksripsi dari access permission
contoh hasil jadi yang akan di submit ke backend adalah sebagai berikut: {
"name": "APPROVE_ATTENDANCE",
"description": "Pemssion yang berfungsi sebagai approval kehadiran pada sebuah role"
}
endpoint:
GET: /api/v1/permission
POST: /api/v1/permission
PUT: /api/v1/permission/{
{id
}
}
DELETE: /api/v1/permission/{
{id
}
}
### Menu Management
kemudian untuk menu akan terdapat juga operasi CRUD seperti pada menu admin yang lain, dimana form field nya akan berisi
id: number (*generate by backend)
name : string
path_url : string
description: string (*field opsional, deksripsi dari access menu)
icon : string (*field opsional, berisi dropdown atau select, berisi icon dan nama icon yang akan ditampilkan pada sidebar, list icon menyusul, dan akan menggunakan icon yang ada pada https: //cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.35.0/dist/tabler-icons.min.css)
is_menu_admin : bool (*field opsional, berfungsi untuk menandakan apakah menu ini adalah menu yang terdapat pada halaman admin, default value nya adalah false)
menu_parent_id : number (*field opsional, berisi dropdown atau select dari menu yang ada saat ini)
action : array string (*fiel opsional, field ini multi-select artinya user dapat memilih lebih dari satu permission, sumber data berasal dari daftar access permssions yang sudah dibuat)
contoh hasil jadi yang akan di submit ke backend adalah sebagai berikut: {
"name": "Overview",
"path_url": "/",
"icon ": "ti ti-category",
"description": "Homepage menu pada aplikasi HATs",
"is_menu_admin": false,
"menu_parent_id": undefined | null,
"action": [
"APPROVE_ATTENDANCE",
"APPROVE_AUTOCHECKOUT",
"CHECK_IN",
"CHECK_OUT"
]
}
{
"name": "Administration",
"path_url": "/administration",
"icon ": "ti ti-user-hexagon",
"description": "Parent menu dari modul user, company, area, division",
"is_menu_admin": true,
"menu_parent_id": undefined | null,
"action": []
}
{
"name": "User",
"path_url": "/administration/user",
"icon ": "",
"description": "Menu user management, menu untuk mengelola seluruh pengguna dalam aplikasi HATs",
"is_menu_admin": true,
"menu_parent_id": 2,
"action": [
"VIEW",
"CREATE",
"UPDATE",
"DELETE",
"CHANGE_PASSWORD",
"RESET_PASSWORD",
"EXPORT"
]
}
endpoint:
GET: /api/v1/menu
POST: /api/v1/menu
PUT: /api/v1/menu/{
{id
}
}
DELETE: /api/v1/menu/{
{id
}
}
### User Role
kemudian untuk menu user-role, sebelumnya menu sudah ada pada `/information/user-role`, namum saya ingin refactor pada halaman tersebut dan memindahkannya pada path baru `/rbac/user-role`.
untuk form nya saya juga ingin memindahkannya ke halaman bukan dalam sebuah modal form. kemudian untuk isi field nya:
id: number (generate by backend)
name: string
description: string (*field opsional)
allow_admin_panel: bool (*field opsional, default value is false)
role_detail: array object
untuk field menu_permission, field ini akan sangat komplek
- dalam halaman tersebut akan meload data menu ke backend terlebih dahulu
- dari list menu tersebut akan dipisah menjadi 2 array object, yaitu menu non admin dan menu admin
- dari masing-masing 2 array object menu tersebut akan di mapping dibuat hierarchical menu tree dan di buat tree view berdasarkan id dan menu_parent_id
- kemudian di render menjadi 2 section, menu non admin dan menu admin
- jika allow_admin_panel false, maka menu admin dikosongkan (tidak ditampilkan)
- untuk setiap menu tree node, terdapat checkbox, dimana checkbox tersebut untuk memilih permission yang dimiliki oleh role untuk menu tersebut
contoh hasil jadi yang akan di submit ke backend adalah sebagai berikut: {
"name": "Team Leader",
"description": "",
"allow_admin_panel": true,
"role_detail": [
{
"menu_id": 1,
"menu_name": "Overview",
"menu_path": "/",
"is_menu_admin": false,
"action": [
"APPROVE_ATTENDANCE",
"APPROVE_AUTOCHECKOUT",
"CHECK_IN",
"CHECK_OUT"
]
},
{
"menu_id": 3,
"menu_name": "Task",
"menu_path": "/task",
"is_menu_admin": false,
"action": [
"VIEW_ASSIGNMENT",
"VIEW_PROJECT",
"UPDATE_TECHNICAL_STATUS"
]
},
{
"menu_id": 1,
"menu_name": "User",
"menu_path": "/administration/user",
"is_menu_admin": true,
"action": [
"VIEW",
"CHANGE_PASSWORD",
"RESET_PASSWORD",
"EXPORT"
]
},
...
]
}
{
"name": "MANAGER",
"description": "",
"allow_admin_panel": true,
"role_detail": [
{
"menu_id": 1,
"menu_name": "Overview",
"menu_path": "/",
"is_menu_admin": false,
"action": [
"APPROVE_LEAVE",
"APPROVE_ATTENDANCE",
"APPROVE_AUTOCHECKOUT"
]
},
{
"menu_id": 3,
"menu_name": "Task",
"menu_path": "/task",
"is_menu_admin": false,
"action": [
"CREATE_CLIENT",
"UPDATE_CLIENT",
"DELETE_CLIENT",
"VIEW_ASSIGNMENT",
"CREATE_ASSIGNMENT",
"UPDATE_ASSIGNMENT",
"DELETE_ASSIGNMENT",
"VIEW_PROJECT",
"UPDATE_TECHNICAL_STATUS"
]
},
{
"menu_id": 1,
"menu_name": "User",
"menu_path": "/administration/user",
"is_menu_admin": true,
"action": [
"VIEW",
"CREATE",
"UPDATE",
"DELETE",
"CHANGE_PASSWORD",
"RESET_PASSWORD",
"EXPORT"
]
}
]
}
GET: /api/v1/role
POST: /api/v1/role
PUT: /api/v1/role/{
{id
}
}
DELETE: /api/v1/role/{
{id
}
}
Contoh tampilan untuk form dan detail user role ada pada gambar yang saya lampirkan pada conversation ini, saya akan anda bisa membuatnya lebih bagus dari pada ini
Mohon dipersiapkan juga satu component badge yaitu rabc-badge.tsx, fungsinya yaitu untuk menampilkan detail permission pada access-permission, menu dan user-role
untuk warna-warnanya adalah:
- VIEW => warna primary / his (apapun aksinya yang ada VIEW)
- CREATE/ADD => sky
- UPDATE/EDIT => teal/emerald
- DELETE/REMOVE => rose
- PASSWORD => yellow
- APPROVE/APPROVAL => violet
- EXPORT => fuchsia
- other => cyan
untuk design non AI Slop, contoh CRUD ada pada menu-menu pada admin panel existing seperti pada halaman `/administration/company`, selalu gunakan rules pada `.agents/skill/design-taste-frontend` dan `.agents/skill/karpathy-guidelines`