kmobile/lib/features/auth/controllers/auth_cubit.dart

109 lines
3.0 KiB
Dart

import 'package:bloc/bloc.dart';
import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.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()));
}
}
Future<void> checkFirstLaunch() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final isFirstLaunch = prefs.getBool('isFirstLaunch') ?? true;
if (isFirstLaunch) {
emit(ShowBiometricPermission());
} else {
// Continue to authentication logic (e.g., check token)
emit(AuthLoading()); // or Unauthenticated/Authenticated
}
}
Future<void> handleBiometricChoice(bool enabled) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('biometric_opt_in', enabled);
await prefs.setBool('isFirstLaunch', false);
// Then continue to auth logic or home
if (enabled) {
authenticateBiometric(); // implement biometric logic
} else {
emit(Unauthenticated());
}
}
Future<void> authenticateBiometric() async {
final LocalAuthentication auth = LocalAuthentication();
try {
final isAvailable = await auth.canCheckBiometrics;
final isDeviceSupported = await auth.isDeviceSupported();
if (isAvailable && isDeviceSupported) {
final authenticated = await auth.authenticate(
localizedReason: 'Touch the fingerprint sensor',
options: const AuthenticationOptions(
biometricOnly: true,
stickyAuth: true,
),
);
if (authenticated) {
// Continue to normal auth logic (e.g., auto login)
emit(AuthLoading());
await checkAuthStatus(); // Your existing method to verify token/session
} else {
emit(Unauthenticated());
}
} else {
emit(Unauthenticated());
}
} catch (e) {
emit(Unauthenticated());
}
}
}