Initial commit
This commit is contained in:
78
src/lib/AuthContext.jsx
Normal file
78
src/lib/AuthContext.jsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import React, { createContext, useState, useContext, useEffect } from 'react';
|
||||
import { base44 } from '@/api/base44Client';
|
||||
|
||||
/**
|
||||
* Auth context.
|
||||
*
|
||||
* The reference app resolves an identity provider before rendering. The demo
|
||||
* has no provider, so it resolves the seeded user immediately — but it keeps
|
||||
* the same context shape (`isLoadingAuth`, `isLoadingPublicSettings`,
|
||||
* `authError`, `navigateToLogin`, …) so `App.jsx`, `ProtectedRoute` and every
|
||||
* consumer stay unchanged.
|
||||
*/
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [isLoadingAuth, setIsLoadingAuth] = useState(true);
|
||||
const [authChecked, setAuthChecked] = useState(false);
|
||||
|
||||
const checkUserAuth = async () => {
|
||||
setIsLoadingAuth(true);
|
||||
try {
|
||||
const currentUser = await base44.auth.me();
|
||||
setUser(currentUser);
|
||||
setIsAuthenticated(true);
|
||||
} catch {
|
||||
setIsAuthenticated(false);
|
||||
} finally {
|
||||
setIsLoadingAuth(false);
|
||||
setAuthChecked(true);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
checkUserAuth();
|
||||
}, []);
|
||||
|
||||
const logout = (shouldRedirect = true) => {
|
||||
setUser(null);
|
||||
setIsAuthenticated(false);
|
||||
base44.auth.logout(shouldRedirect ? '/' : undefined);
|
||||
};
|
||||
|
||||
const navigateToLogin = () => {
|
||||
base44.auth.redirectToLogin();
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
isAuthenticated,
|
||||
isLoadingAuth,
|
||||
// No remote app settings to fetch in the demo.
|
||||
isLoadingPublicSettings: false,
|
||||
authError: null,
|
||||
appPublicSettings: null,
|
||||
authChecked,
|
||||
logout,
|
||||
navigateToLogin,
|
||||
checkUserAuth,
|
||||
checkAppState: checkUserAuth,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user