Files
2026-09-21 16:33:51 -04:00

101 lines
2.2 KiB
Dart

import 'package:mobx/mobx.dart';
import '../../data/models/auth_session_model.dart';
import '../../data/services/auth_service.dart';
part 'auth_store.g.dart';
// ignore: library_private_types_in_public_api
class AuthStore = _AuthStoreBase with _$AuthStore;
abstract class _AuthStoreBase with Store {
final AuthService authService;
_AuthStoreBase({AuthService? service})
: authService = service ?? AuthService();
@observable
bool isLoading = false;
@observable
bool isPasswordVisible = false;
@observable
AuthSessionModel? currentSession;
@observable
String? errorMessage;
@computed
bool get isAuthenticated => currentSession != null;
@action
void togglePasswordVisibility() {
isPasswordVisible = !isPasswordVisible;
}
@action
Future<bool> login({required String email, required String password}) async {
isLoading = true;
errorMessage = null;
currentSession = null;
try {
final session = await authService.login(email: email, password: password);
if (session != null) {
currentSession = session;
return true;
}
errorMessage = 'No se pudo iniciar sesión. Verifique sus credenciales.';
return false;
} catch (e) {
errorMessage = e.toString().replaceAll('Exception: ', '');
return false;
} finally {
isLoading = false;
}
}
@action
Future<void> checkInitialSession() async {
isLoading = true;
try {
final session = await authService.loadSavedSession();
currentSession = session;
} catch (_) {
currentSession = null;
} finally {
isLoading = false;
}
}
@action
Future<bool> refreshToken() async {
isLoading = true;
try {
final session = await authService.refreshToken();
if (session != null) {
currentSession = session;
return true;
}
currentSession = null;
return false;
} catch (_) {
currentSession = null;
return false;
} finally {
isLoading = false;
}
}
@action
Future<void> logout() async {
isLoading = true;
errorMessage = null;
try {
await authService.logout();
currentSession = null;
} finally {
isLoading = false;
}
}
}