Added module gate

This commit is contained in:
Amit Salunke 2026-09-10 17:50:15 +05:30
parent d647fb0684
commit 686a739541
14 changed files with 104 additions and 163 deletions

View File

@ -0,0 +1,11 @@
# API error handling
All API calls normalize transport and backend failures into `ApiError`.
- Authenticated HTTP 401: clear the local session through the auth store.
- HTTP 403: keep the session; the caller is authenticated but forbidden/not entitled.
- HTTP 404/409/422: do not retry automatically; render the relevant screen state.
- Network/timeout/429/5xx: keep the session and allow bounded retry/recovery.
- Only a request that actually carried a bearer token can trigger automatic session expiry.
The normalizer accepts both legacy FastAPI string `detail` responses and the new structured `detail: {code, message, context}` contract.

View File

@ -1,29 +1,8 @@
import axios from "axios";
import axios, { AxiosHeaders } from "axios";
import { getApiAccessToken } from "@/api/access-token";
const apiClient = axios.create({
baseURL:
process.env.EXPO_PUBLIC_API_URL ??
process.env.EXPO_PUBLIC_API_BASE_URL ??
"http://localhost:8000/api",
timeout: 30000,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Bypass-Tunnel-Reminder": "true",
},
});
apiClient.interceptors.request.use(
(config) => {
const token = getApiAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error),
);
import { normalizeApiError } from "@/api/error-utils";
import { notifyUnauthorized } from "@/api/session-events";
const apiClient=axios.create({baseURL:process.env.EXPO_PUBLIC_API_URL ?? process.env.EXPO_PUBLIC_API_BASE_URL ?? "http://localhost:8000/api",timeout:30000,headers:{"Content-Type":"application/json",Accept:"application/json","Bypass-Tunnel-Reminder":"true"}});
apiClient.interceptors.request.use((config)=>{const token=getApiAccessToken(); if(token){const headers=AxiosHeaders.from(config.headers); headers.set("Authorization",`Bearer ${token}`); config.headers=headers;} return config;},(error)=>Promise.reject(normalizeApiError(error)));
apiClient.interceptors.response.use((response)=>response,(error:unknown)=>{const apiError=normalizeApiError(error); const requestHeaders=axios.isAxiosError(error)?AxiosHeaders.from(error.config?.headers):null; const hadBearerToken=Boolean(requestHeaders?.get("Authorization")?.toString().startsWith("Bearer ")); if(hadBearerToken && apiError.status===401) notifyUnauthorized(); return Promise.reject(apiError);});
export default apiClient;

22
src/api/error-utils.ts Normal file
View File

@ -0,0 +1,22 @@
import axios, { AxiosError } from "axios";
import { ApiError, ApiErrorPayload, ApiValidationIssue, StructuredApiErrorDetail } from "./types";
function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value); }
function validationMessage(detail: ApiValidationIssue[]): string | null { const first=detail.find((issue)=>typeof issue?.msg === "string" && issue.msg.trim().length>0); return first?.msg?.trim() ?? null; }
function structuredDetail(detail: unknown): StructuredApiErrorDetail | null { if(!isRecord(detail)) return null; return { code: typeof detail.code === "string" ? detail.code : undefined, message: typeof detail.message === "string" ? detail.message : undefined, context: isRecord(detail.context) ? detail.context : null }; }
export function normalizeApiError(error: unknown): ApiError {
if(error instanceof ApiError) return error;
if(!axios.isAxiosError(error)) return new ApiError({message:error instanceof Error && error.message ? error.message : "Unexpected client error.",status:null,code:null,details:null,cause:error});
const axiosError=error as AxiosError<ApiErrorPayload>; const payload=axiosError.response?.data; const detail=payload?.detail ?? null; const structured=structuredDetail(detail);
let message:string|null=null;
if(typeof detail === "string" && detail.trim()) message=detail.trim();
else if(Array.isArray(detail)) message=validationMessage(detail as ApiValidationIssue[]);
else if(structured?.message?.trim()) message=structured.message.trim();
else if(typeof payload?.message === "string" && payload.message.trim()) message=payload.message.trim();
const code=structured?.code ?? (typeof payload?.code === "string" ? payload.code : null) ?? axiosError.code ?? null;
return new ApiError({message:message ?? axiosError.message ?? "Request failed.",status:axiosError.response?.status ?? null,code,details:detail,cause:axiosError,response:axiosError.response ? {status:axiosError.response.status,data:payload}:undefined});
}
export function getApiErrorStatus(error: unknown): number | null { if(error instanceof ApiError) return error.status; if(axios.isAxiosError(error)) return error.response?.status ?? null; if(isRecord(error)){ if(typeof error.status === "number") return error.status; const response=error.response; if(isRecord(response)&&typeof response.status === "number") return response.status;} return null; }
export function getApiErrorMessage(error: unknown, fallback="Something went wrong. Please try again."): string { if(error instanceof ApiError && error.message.trim()) return error.message; const normalized=normalizeApiError(error); return normalized.message || fallback; }
export function isUnauthorizedApiError(error: unknown): boolean { return getApiErrorStatus(error)===401; }
export function isForbiddenApiError(error: unknown): boolean { return getApiErrorStatus(error)===403; }
export function isTransientApiError(error: unknown): boolean { const status=getApiErrorStatus(error); return status===null || status===408 || status===429 || (status!==null && status>=500); }

View File

@ -1,76 +1,7 @@
import axios, { AxiosError, AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios";
import { ApiError, ApiErrorPayload } from "./types";
export type AccessTokenProvider = () => string | null | Promise<string | null>;
export interface HttpClientOptions {
baseURL: string;
timeoutMs?: number;
accessTokenProvider?: AccessTokenProvider;
}
function normalizeApiError(error: unknown): ApiError {
if (!axios.isAxiosError(error)) {
return new ApiError({
message: "Unexpected client error.",
status: null,
code: null,
details: null,
cause: error,
});
}
const axiosError = error as AxiosError<ApiErrorPayload>;
const payload = axiosError.response?.data;
const detail = payload?.detail ?? null;
return new ApiError({
message:
typeof detail === "string" && detail.trim()
? detail
: axiosError.message || "Request failed.",
status: axiosError.response?.status ?? null,
code: payload?.code ?? axiosError.code ?? null,
details: detail,
cause: axiosError,
});
}
export function createHttpClient(options: HttpClientOptions): AxiosInstance {
const client = axios.create({
baseURL: options.baseURL.replace(/\/+$/, ""),
timeout: options.timeoutMs ?? 20_000,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
client.interceptors.request.use(async (config) => {
if (!options.accessTokenProvider) return config;
const token = await options.accessTokenProvider();
if (!token) return config;
const headers = AxiosHeaders.from(config.headers);
headers.set("Authorization", `Bearer ${token}`);
config.headers = headers;
return config;
});
client.interceptors.response.use(
(response) => response,
(error: unknown) => Promise.reject(normalizeApiError(error)),
);
return client;
}
export async function request<T>(
client: AxiosInstance,
config: AxiosRequestConfig,
): Promise<T> {
const response = await client.request<T>(config);
return response.data;
}
import axios, { AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios";
import { normalizeApiError } from "./error-utils";
import { notifyUnauthorized } from "./session-events";
export type AccessTokenProvider=()=>string|null|Promise<string|null>;
export interface HttpClientOptions { baseURL:string; timeoutMs?:number; accessTokenProvider?:AccessTokenProvider; }
export function createHttpClient(options:HttpClientOptions):AxiosInstance { const client=axios.create({baseURL:options.baseURL.replace(/\/+$/, ""),timeout:options.timeoutMs??20000,headers:{Accept:"application/json","Content-Type":"application/json"}}); client.interceptors.request.use(async(config)=>{if(!options.accessTokenProvider)return config;const token=await options.accessTokenProvider();if(!token)return config;const headers=AxiosHeaders.from(config.headers);headers.set("Authorization",`Bearer ${token}`);config.headers=headers;return config;}); client.interceptors.response.use((response)=>response,(error:unknown)=>{const apiError=normalizeApiError(error);const requestHeaders=axios.isAxiosError(error)?AxiosHeaders.from(error.config?.headers):null;const hadBearerToken=Boolean(requestHeaders?.get("Authorization")?.toString().startsWith("Bearer "));if(hadBearerToken&&apiError.status===401)notifyUnauthorized();return Promise.reject(apiError);}); return client; }
export async function request<T>(client:AxiosInstance,config:AxiosRequestConfig):Promise<T>{const response=await client.request<T>(config);return response.data;}

View File

@ -0,0 +1,4 @@
type UnauthorizedHandler = () => void;
let unauthorizedHandler: UnauthorizedHandler | null = null;
export function setUnauthorizedHandler(handler: UnauthorizedHandler | null): void { unauthorizedHandler = handler; }
export function notifyUnauthorized(): void { unauthorizedHandler?.(); }

View File

@ -1,40 +1,14 @@
export interface ApiValidationIssue {
type?: string;
loc?: Array<string | number>;
msg?: string;
input?: unknown;
ctx?: unknown;
}
export interface ApiErrorPayload {
detail?: string | ApiValidationIssue[] | unknown;
code?: string;
}
export interface ApiValidationIssue { type?: string; loc?: Array<string | number>; msg?: string; input?: unknown; ctx?: unknown; }
export interface StructuredApiErrorDetail { code?: string; message?: string; context?: Record<string, unknown> | null; }
export interface ApiErrorPayload { detail?: string | ApiValidationIssue[] | StructuredApiErrorDetail | unknown; code?: string; message?: string; }
export class ApiError extends Error {
readonly status: number | null;
readonly code: string | null;
readonly details: unknown;
readonly cause?: unknown;
constructor(init: {
message: string;
status: number | null;
code: string | null;
details: unknown;
cause?: unknown;
}) {
super(init.message);
this.name = "ApiError";
this.status = init.status;
this.code = init.code;
this.details = init.details;
this.cause = init.cause;
readonly response?: { status?: number; data?: ApiErrorPayload };
constructor(init: { message: string; status: number | null; code: string | null; details: unknown; cause?: unknown; response?: { status?: number; data?: ApiErrorPayload }; }) {
super(init.message); this.name="ApiError"; this.status=init.status; this.code=init.code; this.details=init.details; this.cause=init.cause; this.response=init.response;
}
}
export interface ApiResponse<T> {
success: boolean;
message: string;
data: T;
}
export interface ApiResponse<T> { success: boolean; message: string; data: T; }

View File

@ -54,7 +54,7 @@ export default function LibraryScreen() {
useFocusEffect(
useCallback(() => {
if (accessToken) {
void refreshAccess();
void refreshAccess().catch((error) => console.warn("Unable to refresh library access:", error));
}
}, [accessToken, refreshAccess]),
);

View File

@ -125,7 +125,9 @@ export default function SubscriptionScreen() {
useFocusEffect(
useCallback(() => {
if (accessToken) void refreshAccess();
if (accessToken) {
void refreshAccess().catch((error) => console.warn("Unable to refresh subscription access:", error));
}
}, [accessToken, refreshAccess]),
);

View File

@ -10,6 +10,7 @@ import {
toModuleIndexItem,
} from "@/features/modules/module-index";
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
import { isUnauthorizedApiError } from "@/api/error-utils";
interface ModuleAccessGateProps extends PropsWithChildren {
moduleCode: string;
@ -55,8 +56,8 @@ export function ModuleAccessGate({ moduleCode, children }: ModuleAccessGateProps
.then(() => {
if (active) setAccessRefreshSucceeded(true);
})
.catch(() => {
if (active) setAccessError(true);
.catch((error) => {
if (active && !isUnauthorizedApiError(error)) setAccessError(true);
})
.finally(() => {
if (active) setAccessChecked(true);

View File

@ -35,7 +35,9 @@ export default function ProfileOverviewCard() {
const refreshAccess = useAuthStore((state) => state.refreshAccess);
useEffect(() => {
if (accessToken) void refreshAccess();
if (accessToken) {
void refreshAccess().catch((error) => console.warn("Unable to refresh profile access:", error));
}
}, [accessToken, refreshAccess]);
const activeSubscriptions = access?.active_subscriptions ?? [];

View File

@ -5,11 +5,10 @@ function shouldRetry(failureCount: number, error: unknown): boolean {
if (failureCount >= 2) return false;
if (error instanceof ApiError) {
if ([400, 401, 403, 404, 409, 422].includes(error.status ?? 0)) {
return false;
}
const status = error.status ?? 0;
if ([400, 401, 403, 404, 409, 422].includes(status)) return false;
if (status === 0 || status === 408 || status === 429 || status >= 500) return true;
}
return true;
}

View File

@ -64,7 +64,7 @@ export default function HomeScreen() {
useFocusEffect(
useCallback(() => {
void refreshSession();
void refreshSession().catch((error) => console.warn("Unable to refresh session:", error));
}, [refreshSession]),
);

View File

@ -54,7 +54,9 @@ export default function ModulesIndexScreen() {
useFocusEffect(
useCallback(() => {
if (accessToken) {
void refreshAccess();
void refreshAccess().catch((error) => {
console.warn("Unable to refresh module access:", error);
});
}
}, [accessToken, refreshAccess]),
);

View File

@ -7,6 +7,8 @@ import {
setApiAccessToken,
} from "@/api/access-token";
import { getAccessMe } from "@/features/access/api/access.api";
import { isUnauthorizedApiError } from "@/api/error-utils";
import { setUnauthorizedHandler } from "@/api/session-events";
import { getMe } from "@/features/auth/api/auth.api";
import type {
@ -160,10 +162,23 @@ export const useAuthStore = create<AuthStore>()(
// Refresh canonical identity and access independently. A temporary
// access-service failure must not invalidate an otherwise valid login.
await Promise.allSettled([
const [identityResult, accessResult] = await Promise.allSettled([
get().refreshIdentity(),
get().refreshAccess(),
]);
const unauthorized =
(identityResult.status === "rejected" && isUnauthorizedApiError(identityResult.reason)) ||
(accessResult.status === "rejected" && isUnauthorizedApiError(accessResult.reason));
if (unauthorized) {
get().logout();
throw identityResult.status === "rejected"
? identityResult.reason
: accessResult.status === "rejected"
? accessResult.reason
: new Error("Session validation failed.");
}
},
refreshIdentity: async () => {
@ -211,23 +226,16 @@ export const useAuthStore = create<AuthStore>()(
// Identity 401/invalid-token is handled conservatively by clearing the
// local session. Access failures are non-fatal and leave prior access
// state intact for transient-network resilience.
if (identityResult.status === "rejected") {
const err = identityResult.reason as {
response?: { status?: number };
status?: number;
};
const status = err?.response?.status ?? err?.status;
if (status === 401) {
get().logout();
}
if (identityResult.status === "rejected" && isUnauthorizedApiError(identityResult.reason)) {
get().logout();
return;
}
if (accessResult.status === "rejected") {
console.warn(
"Failed to refresh access state:",
accessResult.reason,
);
if (accessResult.status === "rejected" && isUnauthorizedApiError(accessResult.reason)) {
get().logout();
return;
}
if (identityResult.status === "rejected") console.warn("Failed to refresh identity:", identityResult.reason);
if (accessResult.status === "rejected") console.warn("Failed to refresh access state:", accessResult.reason);
},
logout: () => {
@ -265,3 +273,9 @@ export const useAuthStore = create<AuthStore>()(
},
),
);
setUnauthorizedHandler(() => {
const state = useAuthStore.getState();
if (state.accessToken || state.isAuthenticated) state.logout();
});