Starting to resolve the issue on prediction8

This commit is contained in:
Your Name 2026-10-27 09:09:53 +02:00
parent 6822786da5
commit b2e4fbfc5d
2 changed files with 75 additions and 4 deletions

View File

@ -1,11 +1,11 @@
/**
* React context for authentication state in the web admin console.
*/
import React, { createContext, useContext, useMemo, useState } from 'react';
import { readAuth, writeAuth } from './tokenStorage';
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { clearAuth, readAuth, writeAuth } from './tokenStorage';
import { hasAdminAccess, hasStaffAccess, hasAdminPanelAccess } from './roleAccess';
import { hasPermission as checkPermission } from './permissions';
import { logoutSession } from '../services/api';
import { ensureFreshAccessToken, logoutSession } from '../services/api';
export type AuthState = {
accessToken: string | null;
@ -18,6 +18,8 @@ export type AuthState = {
type AuthContextValue = {
auth: AuthState;
/** False until boot refresh finishes — avoid firing protected calls with a stale JWT. */
authReady: boolean;
isAuthenticated: boolean;
isAdmin: boolean;
isStaff: boolean;
@ -35,6 +37,32 @@ const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [auth, setAuthState] = useState<AuthState>(() => readAuth());
const [authReady, setAuthReady] = useState(false);
useEffect(() => {
let cancelled = false;
void (async () => {
const hadSession = Boolean(readAuth().refreshToken || readAuth().accessToken);
const token = await ensureFreshAccessToken();
if (cancelled) return;
if (token) {
setAuthState(readAuth());
} else if (hadSession && !readAuth().refreshToken) {
clearAuth();
setAuthState(readAuth());
} else if (hadSession && !token) {
// Refresh failed (revoked / secret rotated) — clear so UI redirects to login.
clearAuth();
setAuthState(readAuth());
} else {
setAuthState(readAuth());
}
setAuthReady(true);
})();
return () => {
cancelled = true;
};
}, []);
const setAuth = (next: AuthState) => {
setAuthState(next);
@ -61,6 +89,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const canApproveFundOps = can('fund_operation.approve') || can('admin.fund_operations.approve');
return {
auth,
authReady,
isAuthenticated,
isAdmin,
hasAdminPanel,
@ -73,7 +102,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
setAuth,
logout,
};
}, [auth]);
}, [auth, authReady]);
if (!authReady) {
return null;
}
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

View File

@ -33,6 +33,27 @@ api.interceptors.request.use((config) => {
let refreshing: Promise<string | null> | null = null;
/** Returns JWT `exp` (unix seconds) or null if the token is not a readable JWT. */
export function readJwtExpSeconds(accessToken: string): number | null {
try {
const parts = accessToken.split('.');
if (parts.length < 2) return null;
const json = atob(parts[1]!.replace(/-/g, '+').replace(/_/g, '/'));
const payload = JSON.parse(json) as { exp?: unknown };
return typeof payload.exp === 'number' ? payload.exp : null;
} catch {
return null;
}
}
/** True when the access token is missing, malformed, expired, or within `skewSeconds` of expiry. */
export function isAccessTokenExpiringSoon(accessToken: string | null, skewSeconds = 60): boolean {
if (!accessToken) return true;
const exp = readJwtExpSeconds(accessToken);
if (exp == null) return true;
return exp <= Math.floor(Date.now() / 1000) + skewSeconds;
}
async function refreshAccessToken(): Promise<string | null> {
const { refreshToken } = readAuth();
if (!refreshToken) return null;
@ -58,6 +79,23 @@ async function refreshAccessToken(): Promise<string | null> {
}
}
/**
* Ensures a usable access token before protected API/WS traffic (hard refresh).
* Shares the same single-flight refresh as the 401 interceptor.
*/
export async function ensureFreshAccessToken(skewSeconds = 60): Promise<string | null> {
const { accessToken, refreshToken } = readAuth();
if (!refreshToken && !accessToken) return null;
if (!isAccessTokenExpiringSoon(accessToken, skewSeconds)) return accessToken;
if (!refreshToken) return null;
refreshing = refreshing ?? refreshAccessToken();
try {
return await refreshing;
} finally {
refreshing = null;
}
}
/** Revokes the refresh token server-side, then clears local auth storage. */
export async function logoutSession(): Promise<void> {
const { refreshToken } = readAuth();