@@ -4,6 +4,16 @@ import { api } from "../api/client"
44
55const AuthContext = createContext ( null )
66
7+ /**
8+ * Global Authentication Provider.
9+ *
10+ * Manages the user's session state, including login, logout, and token validation.
11+ *
12+ * Architecture:
13+ * - **Initialization**: Checks `/api/me` on mount to re-hydrate session from HTTP-only cookie.
14+ * - **Security**: Uses `AbortController` to prevent memory leaks during async auth checks.
15+ * - **Error Handling**: fails gracefully to "Unauthenticated" state on API errors (401/500).
16+ */
717export const AuthProvider = ( { children } ) => {
818 const [ isAuthenticated , setIsAuthenticated ] = useState ( false )
919 const [ user , setUser ] = useState ( null )
@@ -12,7 +22,7 @@ export const AuthProvider = ({ children }) => {
1222
1323 useEffect ( ( ) => {
1424 const controller = new AbortController ( )
15-
25+
1626 const checkAuth = async ( ) => {
1727 try {
1828 const userData = await api . me ( ) ;
@@ -28,17 +38,17 @@ export const AuthProvider = ({ children }) => {
2838 // but for the purpose of UI state, we treat them as not authenticated.
2939 // However, if it's a 401, the api client might have already cleared it or we should ensure it's cleared.
3040 if ( err ?. status === 401 ) {
31- api . setToken ( null ) ;
41+ api . setToken ( null ) ;
3242 }
3343 } finally {
3444 if ( ! controller . signal . aborted ) {
3545 setLoading ( false )
3646 }
3747 }
3848 }
39-
49+
4050 checkAuth ( )
41-
51+
4252 return ( ) => {
4353 controller . abort ( )
4454 }
@@ -48,27 +58,27 @@ export const AuthProvider = ({ children }) => {
4858 try {
4959 setError ( null )
5060 setLoading ( true )
51-
61+
5262 const sanitizedUsername = username . trim ( )
5363 const response = await api . login ( sanitizedUsername , password )
54-
64+
5565 if ( ! response ?. user ) {
5666 throw new Error ( 'Ungueltige Antwort vom Server' )
5767 }
58-
68+
5969 api . setToken ( response . token ?? null )
6070 setIsAuthenticated ( true )
6171 setUser ( response . user )
62-
72+
6373 return { success : true }
6474 } catch ( err ) {
6575 api . setToken ( null )
6676 setIsAuthenticated ( false )
6777 setUser ( null )
68-
78+
6979 const message = err . message || 'Ungueltige Anmeldedaten'
7080 setError ( message )
71-
81+
7282 return { success : false , error : message }
7383 } finally {
7484 setLoading ( false )
@@ -101,10 +111,10 @@ AuthProvider.propTypes = {
101111
102112export const useAuth = ( ) => {
103113 const context = useContext ( AuthContext )
104-
114+
105115 if ( ! context ) {
106116 throw new Error ( 'useAuth must be used within AuthProvider' )
107117 }
108-
118+
109119 return context
110120}
0 commit comments