restoreSession method
Restore a previously saved session on app launch.
The flow is offline-aware and optimistic:
- Read the persisted session from secure storage.
- If none exists → return RestoreResult.noSession.
- Populate the in-memory state immediately (accessToken, currentUser, expiry) and fire authStateChanges so apps render their authenticated UI without waiting for the network.
- If the access token is still valid → return RestoreResult.restored.
- Otherwise refresh against the server:
- Success → return RestoreResult.restored.
- Auth rejection (token revoked/expired/invalid) → clear session, return RestoreResult.expired.
- Network error → keep optimistic state, return RestoreResult.offline. The app can retry later via refreshSession.
Implementation
Future<RestoreResult> restoreSession() async {
final persisted = await _storage.readSession();
if (persisted == null) return RestoreResult.noSession;
// Optimistic restoration — populate state from disk before any network.
_accessToken = persisted.accessToken;
_accessTokenExpiresAt = persisted.expiresAt;
_currentUser = persisted.user;
_authStateController.add(persisted.user);
// If the access token is still valid, we're done — no network needed.
if (!persisted.isAccessTokenExpired) {
return RestoreResult.restored;
}
// Access token expired — attempt to refresh.
try {
final session = await _api.refresh(persisted.refreshToken);
await _setSession(session);
return RestoreResult.restored;
} on KoolbaseAuthException {
// Server rejected the refresh token — clear and require fresh login.
await _clearSession();
return RestoreResult.expired;
} catch (_) {
// Network error (timeout, DNS, connection refused). Keep the optimistic
// state — the app UI stays authenticated, API calls will fail until
// network returns. App can call [refreshSession] when connectivity is
// restored.
return RestoreResult.offline;
}
}