51 lines
1.2 KiB
Dart
51 lines
1.2 KiB
Dart
import 'package:bloc/bloc.dart';
|
|
import '../../../data/repositories/auth_repository.dart';
|
|
import 'auth_state.dart';
|
|
|
|
class AuthCubit extends Cubit<AuthState> {
|
|
final AuthRepository _authRepository;
|
|
|
|
AuthCubit(this._authRepository) : super(AuthInitial()) {
|
|
checkAuthStatus();
|
|
}
|
|
|
|
Future<void> checkAuthStatus() async {
|
|
emit(AuthLoading());
|
|
try {
|
|
final isLoggedIn = await _authRepository.isLoggedIn();
|
|
if (isLoggedIn) {
|
|
final user = await _authRepository.getCurrentUser();
|
|
if (user != null) {
|
|
emit(Authenticated(user));
|
|
} else {
|
|
emit(Unauthenticated());
|
|
}
|
|
} else {
|
|
emit(Unauthenticated());
|
|
}
|
|
} catch (e) {
|
|
emit(AuthError(e.toString()));
|
|
}
|
|
}
|
|
|
|
Future<void> login(String username, String password) async {
|
|
emit(AuthLoading());
|
|
try {
|
|
final user = await _authRepository.login(username, password);
|
|
emit(Authenticated(user));
|
|
} catch (e) {
|
|
emit(AuthError(e.toString()));
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
emit(AuthLoading());
|
|
try {
|
|
await _authRepository.logout();
|
|
emit(Unauthenticated());
|
|
} catch (e) {
|
|
emit(AuthError(e.toString()));
|
|
}
|
|
}
|
|
}
|