Added module gate
This commit is contained in:
parent
d647fb0684
commit
686a739541
|
|
@ -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.
|
||||||
|
|
@ -1,29 +1,8 @@
|
||||||
import axios from "axios";
|
import axios, { AxiosHeaders } from "axios";
|
||||||
|
|
||||||
import { getApiAccessToken } from "@/api/access-token";
|
import { getApiAccessToken } from "@/api/access-token";
|
||||||
|
import { normalizeApiError } from "@/api/error-utils";
|
||||||
const apiClient = axios.create({
|
import { notifyUnauthorized } from "@/api/session-events";
|
||||||
baseURL:
|
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"}});
|
||||||
process.env.EXPO_PUBLIC_API_URL ??
|
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)));
|
||||||
process.env.EXPO_PUBLIC_API_BASE_URL ??
|
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);});
|
||||||
"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),
|
|
||||||
);
|
|
||||||
|
|
||||||
export default apiClient;
|
export default apiClient;
|
||||||
|
|
|
||||||
|
|
@ -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); }
|
||||||
|
|
@ -1,76 +1,7 @@
|
||||||
import axios, { AxiosError, AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios";
|
import axios, { AxiosHeaders, AxiosInstance, AxiosRequestConfig } from "axios";
|
||||||
import { ApiError, ApiErrorPayload } from "./types";
|
import { normalizeApiError } from "./error-utils";
|
||||||
|
import { notifyUnauthorized } from "./session-events";
|
||||||
export type AccessTokenProvider = () => string | null | Promise<string | null>;
|
export type AccessTokenProvider=()=>string|null|Promise<string|null>;
|
||||||
|
export interface HttpClientOptions { baseURL:string; timeoutMs?:number; accessTokenProvider?:AccessTokenProvider; }
|
||||||
export interface HttpClientOptions {
|
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; }
|
||||||
baseURL: string;
|
export async function request<T>(client:AxiosInstance,config:AxiosRequestConfig):Promise<T>{const response=await client.request<T>(config);return response.data;}
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -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?.(); }
|
||||||
|
|
@ -1,40 +1,14 @@
|
||||||
export interface ApiValidationIssue {
|
export interface ApiValidationIssue { type?: string; loc?: Array<string | number>; msg?: string; input?: unknown; ctx?: unknown; }
|
||||||
type?: string;
|
export interface StructuredApiErrorDetail { code?: string; message?: string; context?: Record<string, unknown> | null; }
|
||||||
loc?: Array<string | number>;
|
export interface ApiErrorPayload { detail?: string | ApiValidationIssue[] | StructuredApiErrorDetail | unknown; code?: string; message?: string; }
|
||||||
msg?: string;
|
|
||||||
input?: unknown;
|
|
||||||
ctx?: unknown;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApiErrorPayload {
|
|
||||||
detail?: string | ApiValidationIssue[] | unknown;
|
|
||||||
code?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
readonly status: number | null;
|
readonly status: number | null;
|
||||||
readonly code: string | null;
|
readonly code: string | null;
|
||||||
readonly details: unknown;
|
readonly details: unknown;
|
||||||
readonly cause?: unknown;
|
readonly cause?: unknown;
|
||||||
|
readonly response?: { status?: number; data?: ApiErrorPayload };
|
||||||
constructor(init: {
|
constructor(init: { message: string; status: number | null; code: string | null; details: unknown; cause?: unknown; response?: { status?: number; data?: ApiErrorPayload }; }) {
|
||||||
message: string;
|
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;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export interface ApiResponse<T> { success: boolean; message: string; data: T; }
|
||||||
export interface ApiResponse<T> {
|
|
||||||
success: boolean;
|
|
||||||
message: string;
|
|
||||||
data: T;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,7 @@ export default function LibraryScreen() {
|
||||||
useFocusEffect(
|
useFocusEffect(
|
||||||
useCallback(() => {
|
useCallback(() => {
|
||||||
if (accessToken) {
|
if (accessToken) {
|
||||||
void refreshAccess();
|
void refreshAccess().catch((error) => console.warn("Unable to refresh library access:", error));
|
||||||
}
|
}
|
||||||
}, [accessToken, refreshAccess]),
|
}, [accessToken, refreshAccess]),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -125,7 +125,9 @@ export default function SubscriptionScreen() {
|
||||||
|
|
||||||
useFocusEffect(
|
useFocusEffect(
|
||||||
useCallback(() => {
|
useCallback(() => {
|
||||||
if (accessToken) void refreshAccess();
|
if (accessToken) {
|
||||||
|
void refreshAccess().catch((error) => console.warn("Unable to refresh subscription access:", error));
|
||||||
|
}
|
||||||
}, [accessToken, refreshAccess]),
|
}, [accessToken, refreshAccess]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import {
|
||||||
toModuleIndexItem,
|
toModuleIndexItem,
|
||||||
} from "@/features/modules/module-index";
|
} from "@/features/modules/module-index";
|
||||||
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
|
import { isModuleUnlockedByAccess } from "@/features/access/module-access";
|
||||||
|
import { isUnauthorizedApiError } from "@/api/error-utils";
|
||||||
|
|
||||||
interface ModuleAccessGateProps extends PropsWithChildren {
|
interface ModuleAccessGateProps extends PropsWithChildren {
|
||||||
moduleCode: string;
|
moduleCode: string;
|
||||||
|
|
@ -55,8 +56,8 @@ export function ModuleAccessGate({ moduleCode, children }: ModuleAccessGateProps
|
||||||
.then(() => {
|
.then(() => {
|
||||||
if (active) setAccessRefreshSucceeded(true);
|
if (active) setAccessRefreshSucceeded(true);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch((error) => {
|
||||||
if (active) setAccessError(true);
|
if (active && !isUnauthorizedApiError(error)) setAccessError(true);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (active) setAccessChecked(true);
|
if (active) setAccessChecked(true);
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,9 @@ export default function ProfileOverviewCard() {
|
||||||
const refreshAccess = useAuthStore((state) => state.refreshAccess);
|
const refreshAccess = useAuthStore((state) => state.refreshAccess);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (accessToken) void refreshAccess();
|
if (accessToken) {
|
||||||
|
void refreshAccess().catch((error) => console.warn("Unable to refresh profile access:", error));
|
||||||
|
}
|
||||||
}, [accessToken, refreshAccess]);
|
}, [accessToken, refreshAccess]);
|
||||||
|
|
||||||
const activeSubscriptions = access?.active_subscriptions ?? [];
|
const activeSubscriptions = access?.active_subscriptions ?? [];
|
||||||
|
|
|
||||||
|
|
@ -5,11 +5,10 @@ function shouldRetry(failureCount: number, error: unknown): boolean {
|
||||||
if (failureCount >= 2) return false;
|
if (failureCount >= 2) return false;
|
||||||
|
|
||||||
if (error instanceof ApiError) {
|
if (error instanceof ApiError) {
|
||||||
if ([400, 401, 403, 404, 409, 422].includes(error.status ?? 0)) {
|
const status = error.status ?? 0;
|
||||||
return false;
|
if ([400, 401, 403, 404, 409, 422].includes(status)) return false;
|
||||||
|
if (status === 0 || status === 408 || status === 429 || status >= 500) return true;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,7 @@ export default function HomeScreen() {
|
||||||
|
|
||||||
useFocusEffect(
|
useFocusEffect(
|
||||||
useCallback(() => {
|
useCallback(() => {
|
||||||
void refreshSession();
|
void refreshSession().catch((error) => console.warn("Unable to refresh session:", error));
|
||||||
}, [refreshSession]),
|
}, [refreshSession]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,9 @@ export default function ModulesIndexScreen() {
|
||||||
useFocusEffect(
|
useFocusEffect(
|
||||||
useCallback(() => {
|
useCallback(() => {
|
||||||
if (accessToken) {
|
if (accessToken) {
|
||||||
void refreshAccess();
|
void refreshAccess().catch((error) => {
|
||||||
|
console.warn("Unable to refresh module access:", error);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}, [accessToken, refreshAccess]),
|
}, [accessToken, refreshAccess]),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,8 @@ import {
|
||||||
setApiAccessToken,
|
setApiAccessToken,
|
||||||
} from "@/api/access-token";
|
} from "@/api/access-token";
|
||||||
import { getAccessMe } from "@/features/access/api/access.api";
|
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 { getMe } from "@/features/auth/api/auth.api";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
|
|
@ -160,10 +162,23 @@ export const useAuthStore = create<AuthStore>()(
|
||||||
|
|
||||||
// Refresh canonical identity and access independently. A temporary
|
// Refresh canonical identity and access independently. A temporary
|
||||||
// access-service failure must not invalidate an otherwise valid login.
|
// access-service failure must not invalidate an otherwise valid login.
|
||||||
await Promise.allSettled([
|
const [identityResult, accessResult] = await Promise.allSettled([
|
||||||
get().refreshIdentity(),
|
get().refreshIdentity(),
|
||||||
get().refreshAccess(),
|
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 () => {
|
refreshIdentity: async () => {
|
||||||
|
|
@ -211,23 +226,16 @@ export const useAuthStore = create<AuthStore>()(
|
||||||
// Identity 401/invalid-token is handled conservatively by clearing the
|
// Identity 401/invalid-token is handled conservatively by clearing the
|
||||||
// local session. Access failures are non-fatal and leave prior access
|
// local session. Access failures are non-fatal and leave prior access
|
||||||
// state intact for transient-network resilience.
|
// state intact for transient-network resilience.
|
||||||
if (identityResult.status === "rejected") {
|
if (identityResult.status === "rejected" && isUnauthorizedApiError(identityResult.reason)) {
|
||||||
const err = identityResult.reason as {
|
|
||||||
response?: { status?: number };
|
|
||||||
status?: number;
|
|
||||||
};
|
|
||||||
const status = err?.response?.status ?? err?.status;
|
|
||||||
if (status === 401) {
|
|
||||||
get().logout();
|
get().logout();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
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") {
|
if (accessResult.status === "rejected") console.warn("Failed to refresh access state:", accessResult.reason);
|
||||||
console.warn(
|
|
||||||
"Failed to refresh access state:",
|
|
||||||
accessResult.reason,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
logout: () => {
|
logout: () => {
|
||||||
|
|
@ -265,3 +273,9 @@ export const useAuthStore = create<AuthStore>()(
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
|
setUnauthorizedHandler(() => {
|
||||||
|
const state = useAuthStore.getState();
|
||||||
|
if (state.accessToken || state.isAuthenticated) state.logout();
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue