first commit
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user