Allow bulk in-app and email sends to target team_member_ids and team_role alongside platform users, including scheduled dispatch. Document team refresh token admin integration and select-missing-words sequence order. Co-authored-by: Cursor <cursoragent@cursor.com>
22 KiB
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
- Feature overview
- Team auth vs learner auth
- Architecture & token lifecycle
- Token types & expiry
- Response envelopes
- API reference
- Login flow (admin panel)
- Refresh flow (admin panel)
- HTTP client integration
- Session storage recommendations
- Logout & session invalidation
- JWT claims & RBAC
- TypeScript types & API client
- Error handling
- Security notes
- Integration checklist
- Limitations & future work
- 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 <access_token> |
On successful login or refresh, the API returns:
access_token— short-lived JWT sent on every protected requestrefresh_token— long-lived opaque token used only to obtain new tokensmember_id— team member primary key (also embedded in JWT asUserId)team_role— RBAC role string fromteam_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
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_tokenstable - Routes:
internal/web_server/routes.go—/team/login,/team/refresh(no auth middleware)
Rotation rules (critical)
- Single-use refresh tokens — each
refresh_tokencan be exchanged once. The server revokes it before issuing a new one. - Always save the new refresh token — after every successful refresh response, replace the stored
refresh_tokenwithdata.refresh_tokenfrom the response. Reusing an old refresh token returns401. - Login invalidates prior sessions —
IssueRefreshTokenOnLoginrevokes all active refresh tokens for that member. A new login on another device/browser ends refresh capability for older sessions. - Account status checked on refresh — if the member is suspended/inactive, refresh returns
403even 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):
{
"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). 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:
{
"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:
{
"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
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.
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
POST /api/v1/team/refresh
Content-Type: application/json
{
"refresh_token": "<stored-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)
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
- Submit email/password to
POST /api/v1/team/login. - On success, persist
access_token,refresh_token,member_id, andteam_role. - Optionally call
GET /api/v1/team/meto load profile (requires Bearer token +team.profile.get_mine). - Navigate to the authenticated area.
Example (fetch)
async function teamLogin(email: string, password: string): Promise<TeamMemberSession> {
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<TeamMemberSession> = 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
401with"Access token expired", or - Proactively, shortly before JWT
exp(recommended for smoother UX)
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
- Serialize refresh — only one refresh request at a time. Concurrent 401s should share the same in-flight refresh promise (mutex / queue).
- Update storage atomically — write both
access_tokenandrefresh_tokentogether after refresh succeeds. - Do not refresh with
/auth/refresh— team tokens are stored in a different table. - Retry the failed request once with the new access token after refresh.
- On refresh failure — clear all auth state and redirect to login. Do not retry refresh in a loop.
Example
async function teamRefresh(refreshToken: string): Promise<TeamMemberSession> {
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<TeamMemberSession> = 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
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<TeamMemberSession> | 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:
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:
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
- Clear
access_token,refresh_token, and session metadata from storage. - 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
export interface ApiResponse<T> {
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
import { createContext, useContext, useMemo, useState } from "react";
type AuthContextValue = {
session: TeamMemberSession | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
getAccessToken: () => string | null;
};
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [session, setSession] = useState<TeamMemberSession | null>(() =>
loadSessionFromStorage()
);
const value = useMemo<AuthContextValue>(
() => ({
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 <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
return ctx;
}
Wire the Axios interceptor 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
- HTTPS only in production for login and refresh.
- Never expose refresh tokens in logs, analytics, or error reports.
- Rotate on every refresh — treat
refresh_tokenlike a password; store the latest value only. - XSS — if using
localStorage, keep dependencies patched; CSP helps. Prefer httpOnly cookies if you add a BFF later. - CSRF — not applicable to bearer-token JSON APIs from a SPA origin; relevant only if you move tokens to cookies.
- Tab sync — if multiple tabs share
localStorage, listen tostorageevents so one tab’s refresh updates others.
Integration checklist
- Login form calls
POST /api/v1/team/login(notauth/admin-loginunless supporting legacy users) - Persist
access_token,refresh_token,member_id,team_roleon login success - All admin API calls send
Authorization: Bearer <access_token> - HTTP client intercepts
401access-token failures and callsPOST /api/v1/team/refresh - After refresh, replace stored
refresh_tokenwith the new value fromdata - 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_rolealone - 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
# 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 <access_token>
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