MVP Build
This commit is contained in:
61
frontend/src/core/auth/Auth0Provider.tsx
Normal file
61
frontend/src/core/auth/Auth0Provider.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* @ai-summary Auth0 provider wrapper with API token injection
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Auth0Provider as BaseAuth0Provider, useAuth0 } from '@auth0/auth0-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { apiClient } from '../api/client';
|
||||
|
||||
interface Auth0ProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const Auth0Provider: React.FC<Auth0ProviderProps> = ({ children }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const domain = import.meta.env.VITE_AUTH0_DOMAIN;
|
||||
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
|
||||
const audience = import.meta.env.VITE_AUTH0_AUDIENCE;
|
||||
|
||||
const onRedirectCallback = (appState?: { returnTo?: string }) => {
|
||||
navigate(appState?.returnTo || '/dashboard');
|
||||
};
|
||||
|
||||
return (
|
||||
<BaseAuth0Provider
|
||||
domain={domain}
|
||||
clientId={clientId}
|
||||
authorizationParams={{
|
||||
redirect_uri: window.location.origin,
|
||||
audience: audience,
|
||||
}}
|
||||
onRedirectCallback={onRedirectCallback}
|
||||
cacheLocation="localstorage"
|
||||
>
|
||||
<TokenInjector>{children}</TokenInjector>
|
||||
</BaseAuth0Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// Component to inject token into API client
|
||||
const TokenInjector: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const { getAccessTokenSilently, isAuthenticated } = useAuth0();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
// Add token to all API requests
|
||||
apiClient.interceptors.request.use(async (config) => {
|
||||
try {
|
||||
const token = await getAccessTokenSilently();
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to get access token:', error);
|
||||
}
|
||||
return config;
|
||||
});
|
||||
}
|
||||
}, [isAuthenticated, getAccessTokenSilently]);
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
Reference in New Issue
Block a user