From 686a73954133dccd46ab1460fc610fcc3544a385 Mon Sep 17 00:00:00 2001 From: Amit Salunke Date: Thu, 10 Sep 2026 17:50:15 +0530 Subject: [PATCH] Added module gate --- docs/api-error-handling.md | 11 +++ src/api/client.ts | 33 ++------ src/api/error-utils.ts | 22 +++++ src/api/http-client.ts | 83 ++----------------- src/api/session-events.ts | 4 + src/api/types.ts | 40 ++------- src/app/(tabs)/library.tsx | 2 +- src/app/subscription/index.tsx | 4 +- .../access/components/ModuleAccessGate.tsx | 5 +- .../components/ProfileOverviewCard.tsx | 4 +- src/lib/query/query-client.ts | 7 +- src/screens/home/HomeScreen.tsx | 2 +- src/screens/modules/ModulesIndexScreen.tsx | 4 +- src/store/auth.store.ts | 46 ++++++---- 14 files changed, 104 insertions(+), 163 deletions(-) create mode 100644 docs/api-error-handling.md create mode 100644 src/api/error-utils.ts create mode 100644 src/api/session-events.ts diff --git a/docs/api-error-handling.md b/docs/api-error-handling.md new file mode 100644 index 0000000..b3c4b33 --- /dev/null +++ b/docs/api-error-handling.md @@ -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. diff --git a/src/api/client.ts b/src/api/client.ts index cbaffb1..e8f8280 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -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; diff --git a/src/api/error-utils.ts b/src/api/error-utils.ts new file mode 100644 index 0000000..7c50e28 --- /dev/null +++ b/src/api/error-utils.ts @@ -0,0 +1,22 @@ +import axios, { AxiosError } from "axios"; +import { ApiError, ApiErrorPayload, ApiValidationIssue, StructuredApiErrorDetail } from "./types"; +function isRecord(value: unknown): value is Record { 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; 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); } diff --git a/src/api/http-client.ts b/src/api/http-client.ts index dba54e4..21e8464 100644 --- a/src/api/http-client.ts +++ b/src/api/http-client.ts @@ -1,76 +1,7 @@ -import axios, { AxiosError, AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios"; -import { ApiError, ApiErrorPayload } from "./types"; - -export type AccessTokenProvider = () => string | null | Promise; - -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; - 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( - client: AxiosInstance, - config: AxiosRequestConfig, -): Promise { - const response = await client.request(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; +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(client:AxiosInstance,config:AxiosRequestConfig):Promise{const response=await client.request(config);return response.data;} diff --git a/src/api/session-events.ts b/src/api/session-events.ts new file mode 100644 index 0000000..980b5d6 --- /dev/null +++ b/src/api/session-events.ts @@ -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?.(); } diff --git a/src/api/types.ts b/src/api/types.ts index 848aa73..0e88676 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -1,40 +1,14 @@ -export interface ApiValidationIssue { - type?: string; - loc?: Array; - msg?: string; - input?: unknown; - ctx?: unknown; -} - -export interface ApiErrorPayload { - detail?: string | ApiValidationIssue[] | unknown; - code?: string; -} - +export interface ApiValidationIssue { type?: string; loc?: Array; msg?: string; input?: unknown; ctx?: unknown; } +export interface StructuredApiErrorDetail { code?: string; message?: string; context?: Record | 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 { - success: boolean; - message: string; - data: T; -} \ No newline at end of file +export interface ApiResponse { success: boolean; message: string; data: T; } diff --git a/src/app/(tabs)/library.tsx b/src/app/(tabs)/library.tsx index f4a35fc..6a67f8d 100644 --- a/src/app/(tabs)/library.tsx +++ b/src/app/(tabs)/library.tsx @@ -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]), ); diff --git a/src/app/subscription/index.tsx b/src/app/subscription/index.tsx index a42b415..1e875ba 100644 --- a/src/app/subscription/index.tsx +++ b/src/app/subscription/index.tsx @@ -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]), ); diff --git a/src/features/access/components/ModuleAccessGate.tsx b/src/features/access/components/ModuleAccessGate.tsx index 5c9cc74..6a4a177 100644 --- a/src/features/access/components/ModuleAccessGate.tsx +++ b/src/features/access/components/ModuleAccessGate.tsx @@ -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); diff --git a/src/features/profile/components/ProfileOverviewCard.tsx b/src/features/profile/components/ProfileOverviewCard.tsx index e852835..307630f 100644 --- a/src/features/profile/components/ProfileOverviewCard.tsx +++ b/src/features/profile/components/ProfileOverviewCard.tsx @@ -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 ?? []; diff --git a/src/lib/query/query-client.ts b/src/lib/query/query-client.ts index 2fdebac..4c20b40 100644 --- a/src/lib/query/query-client.ts +++ b/src/lib/query/query-client.ts @@ -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; } diff --git a/src/screens/home/HomeScreen.tsx b/src/screens/home/HomeScreen.tsx index 071229a..1763b0d 100644 --- a/src/screens/home/HomeScreen.tsx +++ b/src/screens/home/HomeScreen.tsx @@ -64,7 +64,7 @@ export default function HomeScreen() { useFocusEffect( useCallback(() => { - void refreshSession(); + void refreshSession().catch((error) => console.warn("Unable to refresh session:", error)); }, [refreshSession]), ); diff --git a/src/screens/modules/ModulesIndexScreen.tsx b/src/screens/modules/ModulesIndexScreen.tsx index f654f40..be0a665 100644 --- a/src/screens/modules/ModulesIndexScreen.tsx +++ b/src/screens/modules/ModulesIndexScreen.tsx @@ -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]), ); diff --git a/src/store/auth.store.ts b/src/store/auth.store.ts index 9c8381c..371c40c 100644 --- a/src/store/auth.store.ts +++ b/src/store/auth.store.ts @@ -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()( // 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()( // 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()( }, ), ); + + +setUnauthorizedHandler(() => { + const state = useAuthStore.getState(); + if (state.accessToken || state.isAuthenticated) state.logout(); +});