This commit is contained in:
2025-11-09 15:42:50 +05:30
parent 5b7f3f0096
commit 3e88aad43f
11 changed files with 332 additions and 98 deletions

View File

@@ -1,14 +1,20 @@
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/api/services/user_service.dart';
import 'package:kmobile/core/errors/exceptions.dart';
import 'package:kmobile/data/models/user.dart';
import 'package:kmobile/features/auth/models/auth_token.dart';
import 'package:kmobile/security/secure_storage.dart';
import '../../../data/repositories/auth_repository.dart';
import 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
final AuthRepository _authRepository;
final UserService _userService;
final SecureStorage _secureStorage;
AuthCubit(this._authRepository, this._userService) : super(AuthInitial()) {
AuthCubit(this._authRepository, this._userService, this._secureStorage)
: super(AuthInitial()) {
checkAuthStatus();
}
@@ -29,22 +35,56 @@ class AuthCubit extends Cubit<AuthState> {
Future<void> refreshUserData() async {
try {
// emit(AuthLoading());
final users = await _userService.getUserDetails();
emit(Authenticated(users));
} catch (e) {
emit(AuthError('Failed to refresh user data: ${e.toString()}'));
// Optionally, re-emit the previous state or handle as needed
}
}
Future<void> login(String customerNo, String password) async {
emit(AuthLoading());
try {
final users = await _authRepository.login(customerNo, password);
emit(Authenticated(users));
final (users, authToken) = await _authRepository.login(customerNo, password);
if (authToken.tnc == false) {
// TNC not accepted, tell UI to show the dialog
emit(ShowTncDialog(authToken, users));
} else {
// TNC already accepted, emit Authenticated and then proceed to MPIN check
emit(Authenticated(users));
await _checkMpinAndNavigate();
}
} catch (e) {
emit(AuthError(e is AuthException ? e.message : e.toString()));
}
}
Future<void> onTncDialogResult(
bool agreed, AuthToken authToken, List<User> users) async {
if (agreed) {
try {
await _authRepository.acceptTnc();
// User agreed, emit Authenticated and then proceed to MPIN check
emit(Authenticated(users));
await _checkMpinAndNavigate();
} catch (e) {
emit(AuthError('Failed to accept TNC: $e'));
}
} else {
// User disagreed, tell UI to navigate to the required screen
emit(NavigateToTncRequiredScreen());
}
}
Future<void> _checkMpinAndNavigate() async {
final mpin = await _secureStorage.read('mpin');
if (mpin == null) {
// No MPIN, tell UI to navigate to MPIN setup
emit(NavigateToMpinSetupScreen());
} else {
// MPIN exists, tell UI to navigate to the dashboard
emit(NavigateToDashboardScreen());
}
}
}