@@ -9,8 +9,16 @@ import '../services/storage_service.dart';
99class AuthProvider with ChangeNotifier {
1010 final AuthService _authService = AuthService .instance;
1111 AuthProvider ._();
12+
1213 bool _isLoading = false ;
1314 bool get isLoading => _isLoading;
15+
16+ bool _isCheckingAuthState = false ;
17+ bool get isCheckingAuthState => _isCheckingAuthState;
18+
19+ bool _isAuthenticated = false ;
20+ bool get isAuthenticated => _isAuthenticated;
21+
1422 String _serverUrl = '' ;
1523 String get serverUrl => _serverUrl;
1624
@@ -25,9 +33,27 @@ class AuthProvider with ChangeNotifier {
2533 // Initialize AuthService (sets up Dio & loads any persisted cookies).
2634 await provider._authService.initialize (serverUrl: provider._serverUrl);
2735
36+ // Check if user is already authenticated
37+ await provider._checkAuthState ();
38+
2839 return provider;
2940 }
3041
42+ /// Check authentication state by making a test API call
43+ Future <void > _checkAuthState () async {
44+ _isCheckingAuthState = true ;
45+ notifyListeners ();
46+
47+ try {
48+ _isAuthenticated = await _authService.checkAuthState ();
49+ } catch (e) {
50+ _isAuthenticated = false ;
51+ }
52+
53+ _isCheckingAuthState = false ;
54+ notifyListeners ();
55+ }
56+
3157 /// Change serverUrl, persist it, and re-initialize Dio so its baseUrl updates.
3258 Future <void > updateServerUrl (String newUrl) async {
3359 if (newUrl == _serverUrl) return ;
@@ -50,9 +76,11 @@ class AuthProvider with ChangeNotifier {
5076
5177 try {
5278 await _authService.login (email: email, password: password);
79+ _isAuthenticated = true ;
5380 _isLoading = false ;
5481 notifyListeners ();
5582 } catch (e) {
83+ _isAuthenticated = false ;
5684 _isLoading = false ;
5785 notifyListeners ();
5886 rethrow ;
@@ -68,13 +96,32 @@ class AuthProvider with ChangeNotifier {
6896 email: email,
6997 password: password,
7098 );
99+ _isAuthenticated = true ;
71100 _isLoading = false ;
72101 notifyListeners ();
73102 return userId;
74103 } catch (e) {
104+ _isAuthenticated = false ;
75105 _isLoading = false ;
76106 notifyListeners ();
77107 rethrow ;
78108 }
79109 }
110+
111+ /// Logout user and clear authentication state
112+ Future <void > logout () async {
113+ _isLoading = true ;
114+ notifyListeners ();
115+
116+ try {
117+ await _authService.logout ();
118+ _isAuthenticated = false ;
119+ } catch (e) {
120+ // Even if logout fails, clear local state
121+ _isAuthenticated = false ;
122+ }
123+
124+ _isLoading = false ;
125+ notifyListeners ();
126+ }
80127}
0 commit comments