Add Clerk authentication to API requests
- Update API client to include Bearer token in requests - Add token getter method to reportService for photo uploads - Create ApiInitializer component to set up auth tokens - Use Clerk's getToken() to retrieve session tokens - Fix 401 Unauthorized errors on report submission
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
// API service configuration and base client
|
||||
import { useAuth } from '@clerk/clerk-react';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';
|
||||
|
||||
@@ -11,21 +12,30 @@ export interface ApiError {
|
||||
|
||||
export class ApiClient {
|
||||
private baseUrl: string;
|
||||
private getToken?: () => Promise<string | null>;
|
||||
|
||||
constructor(baseUrl: string = API_BASE_URL) {
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
setTokenGetter(getToken: () => Promise<string | null>) {
|
||||
this.getToken = getToken;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
|
||||
// Get auth token if available
|
||||
const token = this.getToken ? await this.getToken() : null;
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user