# Team Member Refresh Token — Admin Panel Integration Guide This guide documents how to integrate **team member login** and **refresh token rotation** into the Yimaru admin panel. It covers the login/refresh APIs, token lifecycle, storage, HTTP client interceptors, TypeScript types, error handling, and security notes. **Use this guide when:** staff sign in with `POST /api/v1/team/login` and the admin panel must keep sessions alive without forcing re-login when the short-lived access JWT expires. --- ## Table of contents 1. [Feature overview](#feature-overview) 2. [Team auth vs learner auth](#team-auth-vs-learner-auth) 3. [Architecture & token lifecycle](#architecture--token-lifecycle) 4. [Token types & expiry](#token-types--expiry) 5. [Response envelopes](#response-envelopes) 6. [API reference](#api-reference) 7. [Login flow (admin panel)](#login-flow-admin-panel) 8. [Refresh flow (admin panel)](#refresh-flow-admin-panel) 9. [HTTP client integration](#http-client-integration) 10. [Session storage recommendations](#session-storage-recommendations) 11. [Logout & session invalidation](#logout--session-invalidation) 12. [JWT claims & RBAC](#jwt-claims--rbac) 13. [TypeScript types & API client](#typescript-types--api-client) 14. [Error handling](#error-handling) 15. [Security notes](#security-notes) 16. [Integration checklist](#integration-checklist) 17. [Limitations & future work](#limitations--future-work) 18. [Quick reference](#quick-reference) --- ## Feature overview Team members (internal staff) authenticate against the **`team_members`** table. The admin panel should use the **team** auth endpoints exclusively — not learner `auth/login` or `auth/admin-login` unless you intentionally support legacy platform-admin users. | Capability | Endpoint | Auth required | |------------|----------|---------------| | Sign in | `POST /api/v1/team/login` | No | | Refresh session | `POST /api/v1/team/refresh` | No | | Call protected admin APIs | Any RBAC-protected route | Yes — `Authorization: Bearer ` | On successful **login** or **refresh**, the API returns: - **`access_token`** — short-lived JWT sent on every protected request - **`refresh_token`** — long-lived opaque token used only to obtain new tokens - **`member_id`** — team member primary key (also embedded in JWT as `UserId`) - **`team_role`** — RBAC role string from `team_members.team_role` (e.g. `ADMIN`, `CONTENT_MANAGER`) --- ## Team auth vs learner auth Do **not** mix token families. Each refresh endpoint only accepts tokens it issued. | Aspect | Team member (admin panel) | Platform user / learner | |--------|---------------------------|-------------------------| | Login | `POST /api/v1/team/login` | `POST /api/v1/auth/login`, OTP flows, etc. | | Refresh | `POST /api/v1/team/refresh` | `POST /api/v1/auth/refresh` | | Identity table | `team_members` | `users` | | Refresh token store | `team_refresh_tokens` | `refresh_tokens` | | Refresh rotation | **Yes** — old token revoked, new token returned | **Yes** — old token revoked server-side | | Logout API | **Not implemented** for team | `POST /api/v1/auth/logout` | If the admin panel stores a team `refresh_token`, all refresh calls must go to **`/api/v1/team/refresh`**. --- ## Architecture & token lifecycle ```mermaid sequenceDiagram participant UI as Admin panel participant API as Yimaru API participant DB as PostgreSQL UI->>API: POST /team/login (email, password) API->>DB: Validate member, revoke old refresh tokens API->>DB: Insert new team_refresh_tokens row API-->>UI: access_token + refresh_token loop Protected requests UI->>API: Bearer access_token API-->>UI: 200 or 401 (expired) end UI->>API: POST /team/refresh (refresh_token) API->>DB: Validate, revoke used token, insert new token API-->>UI: new access_token + new refresh_token Note over UI: Must persist NEW refresh_token immediately ``` **Source of truth (backend):** - Handler: `internal/web_server/handlers/team_handler.go` — `TeamMemberLogin`, `TeamMemberRefresh` - Service: `internal/services/team/tokens.go` — `IssueRefreshTokenOnLogin`, `RefreshSession` - Migration: `000039_team_refresh_tokens` — `team_refresh_tokens` table - Routes: `internal/web_server/routes.go` — `/team/login`, `/team/refresh` (no auth middleware) ### Rotation rules (critical) 1. **Single-use refresh tokens** — each `refresh_token` can be exchanged **once**. The server revokes it before issuing a new one. 2. **Always save the new refresh token** — after every successful refresh response, replace the stored `refresh_token` with `data.refresh_token` from the response. Reusing an old refresh token returns `401`. 3. **Login invalidates prior sessions** — `IssueRefreshTokenOnLogin` revokes all active refresh tokens for that member. A new login on another device/browser ends refresh capability for older sessions. 4. **Account status checked on refresh** — if the member is suspended/inactive, refresh returns `403` even with a previously valid token. --- ## Token types & expiry | Token | Format | Config (server) | Purpose | |-------|--------|-----------------|---------| | Access token | JWT (HS256) | `ACCESS_EXPIRY` env (seconds) | `Authorization: Bearer` header | | Refresh token | Opaque base32 string (~52 chars) | `REFRESH_EXPIRY` env (seconds) | Body of `POST /team/refresh` only | JWT claims (`internal/web_server/jwt/jwt.go`): ```json { "UserId": 42, "Role": "ADMIN", "iss": "yimaru.com", "aud": ["api.yimaru.com"], "exp": 1719244800 } ``` `Role` in the JWT is the **platform role** mapped from `team_role` (see [JWT claims & RBAC](#jwt-claims--rbac)). `UserId` is the **team member ID**, not a row in `users`. **Admin panel tip:** decode the JWT client-side only to read `exp` for proactive refresh timing. Never trust client-side role checks for security — the API enforces RBAC on every request. --- ## Response envelopes ### Success (`200`) All team login/refresh success responses use `domain.Response`: ```json { "message": "Login successful", "data": { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "MFRGGZDFMZTWQ2LKONSW44DJNZ2GKY3FONUXEY3FON2GK5BA", "member_id": 42, "team_role": "ADMIN" }, "success": true, "status_code": 200, "metadata": null } ``` Refresh success uses `"message": "Token refreshed successfully"` but **`data` has the same shape** as login. ### Error (`4xx` / `5xx`) Errors use `domain.ErrorResponse`: ```json { "message": "Refresh failed", "error": "Invalid or expired refresh token" } ``` Protected routes that receive an expired access token return Fiber errors (often plain text body), e.g. `"Access token expired"` with HTTP `401`. --- ## API reference Base URL: `{API_BASE}/api/v1` (e.g. `https://api.yimaru.com/api/v1`). ### `POST /team/login` Authenticate a team member with email and password. **Request** ```http POST /api/v1/team/login Content-Type: application/json { "email": "staff@yimaru.com", "password": "your-password" } ``` | Field | Type | Required | Validation | |-------|------|----------|------------| | `email` | string | Yes | Valid email | | `password` | string | Yes | Non-empty | **Success `200`** — `data` is [team member session payload](#success-200). **Errors** | HTTP | `error` (typical) | Meaning | |------|-------------------|---------| | `400` | Validation message | Missing/invalid fields | | `401` | `Invalid credentials` | Wrong email/password | | `401` | `Account is not active` | Member suspended/inactive/terminated | | `401` | `Please accept your invitation email...` | `email_verified` is false | | `500` | Server message | Unexpected failure | --- ### `POST /team/refresh` Exchange a valid team refresh token for a new access JWT and a **new** refresh token. **Request** ```http POST /api/v1/team/refresh Content-Type: application/json { "refresh_token": "" } ``` | Field | Type | Required | |-------|------|----------| | `refresh_token` | string | Yes | **No `Authorization` header** — this endpoint is public (the refresh token in the body is the credential). **Success `200`** — same `data` shape as login. **Replace both tokens in storage.** **Errors** | HTTP | `error` (typical) | Admin UI behavior | |------|-------------------|-------------------| | `400` | Validation / parse error | Fix client payload | | `401` | `Invalid or expired refresh token` | Clear session, redirect to login | | `403` | `Account is not active` | Clear session, show account disabled message | | `500` | Server message | Retry once; then force login | --- ## Login flow (admin panel) ```mermaid flowchart TD A[Login form] --> B[POST /team/login] B -->|200| C[Persist access_token + refresh_token] C --> D[Store member_id + team_role] D --> E[Redirect to dashboard] B -->|401| F[Show error toast] B -->|400| G[Show field errors] ``` **Recommended steps** 1. Submit email/password to `POST /api/v1/team/login`. 2. On success, persist `access_token`, `refresh_token`, `member_id`, and `team_role`. 3. Optionally call `GET /api/v1/team/me` to load profile (requires Bearer token + `team.profile.get_mine`). 4. Navigate to the authenticated area. **Example (fetch)** ```typescript async function teamLogin(email: string, password: string): Promise { const res = await fetch(`${API_BASE}/api/v1/team/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password }), }); const body: ApiResponse = await res.json(); if (!res.ok) { throw new TeamAuthError(body.message, body.error, res.status); } return body.data; } ``` --- ## Refresh flow (admin panel) Use refresh when: - A protected API returns `401` with `"Access token expired"`, or - Proactively, shortly before JWT `exp` (recommended for smoother UX) ```mermaid flowchart TD A[API request with Bearer token] --> B{401 expired?} B -->|No| C[Return response] B -->|Yes| D{Refresh in flight?} D -->|Yes| E[Queue request, wait for refresh] D -->|No| F[POST /team/refresh] F -->|200| G[Save NEW tokens] G --> H[Retry original request] F -->|401/403| I[Clear session → login page] ``` ### Rules for implementers 1. **Serialize refresh** — only one refresh request at a time. Concurrent 401s should share the same in-flight refresh promise (mutex / queue). 2. **Update storage atomically** — write both `access_token` and `refresh_token` together after refresh succeeds. 3. **Do not refresh with `/auth/refresh`** — team tokens are stored in a different table. 4. **Retry the failed request once** with the new access token after refresh. 5. **On refresh failure** — clear all auth state and redirect to login. Do not retry refresh in a loop. **Example** ```typescript async function teamRefresh(refreshToken: string): Promise { const res = await fetch(`${API_BASE}/api/v1/team/refresh`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ refresh_token: refreshToken }), }); const body: ApiResponse = await res.json(); if (!res.ok) { throw new TeamAuthError(body.message, body.error, res.status); } // IMPORTANT: body.data.refresh_token is NEW — old one is revoked return body.data; } ``` --- ## HTTP client integration ### Axios interceptor sketch ```typescript import axios, { AxiosError, InternalAxiosRequestConfig } from "axios"; import { authStore } from "./auth-store"; // your persistence layer const api = axios.create({ baseURL: `${API_BASE}/api/v1` }); api.interceptors.request.use((config) => { const token = authStore.getAccessToken(); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); let refreshPromise: Promise | null = null; api.interceptors.response.use( (response) => response, async (error: AxiosError) => { const original = error.config as InternalAxiosRequestConfig & { _retry?: boolean }; if ( error.response?.status !== 401 || original._retry || original.url?.includes("/team/login") || original.url?.includes("/team/refresh") ) { return Promise.reject(error); } const msg = String(error.response?.data ?? ""); if (!msg.includes("Access token expired") && !msg.includes("Invalid access token")) { return Promise.reject(error); } original._retry = true; if (!refreshPromise) { const rt = authStore.getRefreshToken(); if (!rt) { authStore.clear(); return Promise.reject(error); } refreshPromise = teamRefresh(rt) .then((session) => { authStore.setSession(session); return session; }) .finally(() => { refreshPromise = null; }); } try { const session = await refreshPromise; original.headers.Authorization = `Bearer ${session.access_token}`; return api(original); } catch { authStore.clear(); window.location.href = "/login"; return Promise.reject(error); } } ); export { api }; ``` ### Proactive refresh (optional) Decode JWT `exp` and schedule refresh ~60 seconds before expiry: ```typescript function scheduleProactiveRefresh(accessToken: string, refreshToken: string) { const payload = JSON.parse(atob(accessToken.split(".")[1])); const expiresAtMs = payload.exp * 1000; const refreshAtMs = expiresAtMs - 60_000; const delay = Math.max(0, refreshAtMs - Date.now()); setTimeout(async () => { try { const session = await teamRefresh(refreshToken); authStore.setSession(session); scheduleProactiveRefresh(session.access_token, session.refresh_token); } catch { authStore.clear(); } }, delay); } ``` Use proactive refresh **in addition to** the 401 interceptor, not instead of it. --- ## Session storage recommendations | Storage | Access token | Refresh token | Notes | |---------|--------------|---------------|-------| | `sessionStorage` | OK | OK | Cleared on tab close; simpler SPA setup | | `localStorage` | OK | OK | Survives browser restart; slightly higher XSS risk | | Memory only + httpOnly cookie | Best if BFF exists | Best if BFF exists | Requires a backend-for-frontend to set cookies | **Minimum to persist after login/refresh:** ```typescript interface TeamMemberSession { access_token: string; refresh_token: string; member_id: number; team_role: string; } ``` Also store nothing sensitive in URL query params. Never send `refresh_token` as a query parameter or log it. --- ## Logout & session invalidation There is **no** `POST /api/v1/team/logout` endpoint today. **Client-side logout** 1. Clear `access_token`, `refresh_token`, and session metadata from storage. 2. Redirect to the login page. **Server-side invalidation (without logout API)** | Event | Effect on existing refresh tokens | |-------|-----------------------------------| | User logs in again (same or other device) | All prior refresh tokens for that member revoked | | Refresh succeeds | Previous refresh token revoked; only the new one works | | Admin changes member status to non-active | Next refresh returns `403` | | Token expires (`REFRESH_EXPIRY`) | Refresh returns `401` | For “log out everywhere”, the member must sign in again (which revokes old tokens) or an admin must deactivate the account. --- ## JWT claims & RBAC `team_role` from the API maps to JWT `Role` via `TeamRole.PlatformRole()`: | `team_role` (API) | JWT `Role` | RBAC behavior | |-------------------|------------|---------------| | `SUPER_ADMIN` | `SUPER_ADMIN` | Full bypass | | `ADMIN`, `CONTENT_MANAGER`, `FINANCE`, `HR`, `ANALYST` | `ADMIN` | Permission checks via RBAC | | `INSTRUCTOR` | `INSTRUCTOR` | Limited permissions | | `SUPPORT_AGENT` | `SUPPORT` | Support-scoped permissions | Protected admin routes use `authMiddleware` + `RequirePermission(...)`. A valid access token alone is not enough — the role must have the required permission key. After refresh, `team_role` in the response reflects the current DB value. Update any UI role badges if you cache `team_role` separately from the JWT. --- ## TypeScript types & API client ```typescript export interface ApiResponse { message: string; data: T; success: boolean; status_code: number; metadata?: unknown; } export interface ApiErrorResponse { message: string; error?: string; } export interface TeamMemberSession { access_token: string; refresh_token: string; member_id: number; team_role: string; } export interface TeamMemberLoginRequest { email: string; password: string; } export interface TeamMemberRefreshRequest { refresh_token: string; } export class TeamAuthError extends Error { constructor( message: string, public readonly detail: string | undefined, public readonly status: number ) { super(message); this.name = "TeamAuthError"; } } ``` ### React Query / auth context sketch ```typescript import { createContext, useContext, useMemo, useState } from "react"; type AuthContextValue = { session: TeamMemberSession | null; login: (email: string, password: string) => Promise; logout: () => void; getAccessToken: () => string | null; }; const AuthContext = createContext(null); export function AuthProvider({ children }: { children: React.ReactNode }) { const [session, setSession] = useState(() => loadSessionFromStorage() ); const value = useMemo( () => ({ session, async login(email, password) { const next = await teamLogin(email, password); saveSessionToStorage(next); setSession(next); }, logout() { clearSessionStorage(); setSession(null); }, getAccessToken: () => session?.access_token ?? null, }), [session] ); return {children}; } export function useAuth() { const ctx = useContext(AuthContext); if (!ctx) throw new Error("useAuth must be used within AuthProvider"); return ctx; } ``` Wire the [Axios interceptor](#axios-interceptor-sketch) to `authStore` / `AuthProvider` so all admin API modules share the same refresh logic. --- ## Error handling | Scenario | HTTP | Action | |----------|------|--------| | Wrong password | `401` on login | Show `error` message; keep form | | Pending invitation | `401` on login | Link to invitation accept flow | | Access token expired | `401` on API | Trigger refresh once, then retry | | Refresh token expired/revoked | `401` on refresh | Clear session → login | | Account deactivated | `403` on refresh | Clear session → show support message | | Missing permission | `403` on API | Show “no access” (do not refresh) | | Network error | — | Toast + retry; do not clear session | **Distinguish 401 causes on protected routes** - `"Access token expired"` / `"Invalid access token"` → try refresh - `"Authorization header missing"` → user not logged in → login page - Refresh endpoint `401` → session dead → login page --- ## Security notes 1. **HTTPS only** in production for login and refresh. 2. **Never expose refresh tokens** in logs, analytics, or error reports. 3. **Rotate on every refresh** — treat `refresh_token` like a password; store the latest value only. 4. **XSS** — if using `localStorage`, keep dependencies patched; CSP helps. Prefer httpOnly cookies if you add a BFF later. 5. **CSRF** — not applicable to bearer-token JSON APIs from a SPA origin; relevant only if you move tokens to cookies. 6. **Tab sync** — if multiple tabs share `localStorage`, listen to `storage` events so one tab’s refresh updates others. --- ## Integration checklist - [ ] Login form calls `POST /api/v1/team/login` (not `auth/admin-login` unless supporting legacy users) - [ ] Persist `access_token`, `refresh_token`, `member_id`, `team_role` on login success - [ ] All admin API calls send `Authorization: Bearer ` - [ ] HTTP client intercepts `401` access-token failures and calls `POST /api/v1/team/refresh` - [ ] After refresh, **replace** stored `refresh_token` with the new value from `data` - [ ] Serialize concurrent refresh attempts (single in-flight refresh) - [ ] On refresh `401`/`403`, clear storage and redirect to login - [ ] Logout clears tokens locally (no team logout API yet) - [ ] Optional: proactive refresh before JWT `exp` - [ ] RBAC: gate UI with permissions; do not rely on `team_role` alone - [ ] Test: login → wait for access expiry → API call succeeds via refresh - [ ] Test: reuse old refresh token → expect `401` - [ ] Test: login on second browser → first browser refresh fails → login prompt --- ## Limitations & future work | Item | Status | |------|--------| | Team logout endpoint (revoke refresh token) | Not implemented — client clears storage only | | Refresh token in httpOnly cookie | Not implemented — body JSON only | | `Refresh-Token` header on API calls | Read in middleware but **not required** for team flow | | Activity log on refresh | `AUTH_TOKEN_REFRESHED` recorded server-side | --- ## Quick reference ```http # Login POST /api/v1/team/login Content-Type: application/json { "email": "...", "password": "..." } # Refresh (no Authorization header) POST /api/v1/team/refresh Content-Type: application/json { "refresh_token": "..." } # Protected admin call GET /api/v1/team/me Authorization: Bearer ``` **Success `data` fields:** `access_token`, `refresh_token`, `member_id`, `team_role` **Backend files:** `team_handler.go`, `tokens.go`, `routes.go` (`/team/login`, `/team/refresh`) **Swagger:** `docs/swagger.yaml` — tags `team`, paths `/api/v1/team/login` and `/api/v1/team/refresh`