initAuth method
Initialize authentication by restoring the session from storage.
Returns true if authenticated. Safe to call on every app start —
it will not log the user out on network errors or server downtime,
only on explicit auth rejections (401/403).
Example:
final isAuthenticated = await db.auth.initAuth();
if (isAuthenticated) {
print('Logged in as: ${db.auth.getUser()?.email}');
}
Implementation
Future<bool> initAuth() async {
final token = await authStore?.getToken();
if (token == null || token.isEmpty) {
_token = null;
_user = null;
_fireAuthStateChange();
return false;
}
_token = token;
try {
await getCurrentUser();
} catch (e) {
// Only revoke the session when the server explicitly rejects the token.
// Network errors, timeouts, and 5xx do NOT mean the token is invalid.
if (e is UnauthorizedError || e is ForbiddenError) {
_token = null;
_user = null;
await authStore?.setToken('');
_fireAuthStateChange();
return false;
}
// For all other errors (network, timeout, 5xx): keep token, user may be
// null until the next successful getCurrentUser() call.
}
_fireAuthStateChange();
return _token != null;
}