4a93bd1c44
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
62 lines
1.8 KiB
Dart
62 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import '../../features/auth/config/auth_config.dart';
|
|
import '../../features/auth/domain/auth_session.dart';
|
|
|
|
class SessionStore {
|
|
SessionStore._();
|
|
|
|
static final ValueNotifier<AuthSession?> _current = ValueNotifier<AuthSession?>(null);
|
|
|
|
static ValueListenable<AuthSession?> get listenable => _current;
|
|
static AuthSession? get current => _current.value;
|
|
static bool get isSignedIn => _current.value?.isAuthenticated ?? false;
|
|
|
|
static Future<void> hydrate() async {
|
|
if (!AuthConfig.persistSession) {
|
|
return;
|
|
}
|
|
final preferences = await SharedPreferences.getInstance();
|
|
final raw = preferences.getString(AuthConfig.sessionStorageKey);
|
|
if (raw == null || raw.isEmpty) {
|
|
return;
|
|
}
|
|
try {
|
|
final decoded = jsonDecode(raw);
|
|
if (decoded is Map<String, dynamic>) {
|
|
final session = AuthSession.fromJson(decoded);
|
|
if (session.isAuthenticated) {
|
|
_current.value = session;
|
|
} else {
|
|
_current.value = null;
|
|
await preferences.remove(AuthConfig.sessionStorageKey);
|
|
}
|
|
}
|
|
} catch (_) {
|
|
_current.value = null;
|
|
await preferences.remove(AuthConfig.sessionStorageKey);
|
|
}
|
|
}
|
|
|
|
static Future<void> save(AuthSession session) async {
|
|
_current.value = session;
|
|
if (!AuthConfig.persistSession) {
|
|
return;
|
|
}
|
|
final preferences = await SharedPreferences.getInstance();
|
|
await preferences.setString(AuthConfig.sessionStorageKey, jsonEncode(session.toJson()));
|
|
}
|
|
|
|
static Future<void> clear() async {
|
|
_current.value = null;
|
|
if (!AuthConfig.persistSession) {
|
|
return;
|
|
}
|
|
final preferences = await SharedPreferences.getInstance();
|
|
await preferences.remove(AuthConfig.sessionStorageKey);
|
|
}
|
|
}
|