mirror of
https://github.com/SyncrowIOT/syncrow-app.git
synced 2026-10-24 16:07:56 +00:00
Refactor code for better readability and maintainability
- Add method to get token and validate in AuthCubit - Update AuthState with loading, success, and error states for token - Use BlocBuilder in SplashView for token validation and navigation This commit refactors the code in AuthCubit to include a method to get the token and validate it. It also updates the AuthState with loading, success, and error states for token handling. In SplashView, BlocBuilder is now used to handle token validation and navigation based on the token status.
This commit is contained in:
@@ -13,7 +13,9 @@ import 'package:syncrow_app/services/api/network_exception.dart';
|
||||
part 'auth_state.dart';
|
||||
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
AuthCubit() : super(AuthInitial());
|
||||
AuthCubit() : super(AuthInitial()) {
|
||||
getTokenAndValidate();
|
||||
}
|
||||
|
||||
static AuthCubit get(context) => BlocProvider.of(context);
|
||||
|
||||
@@ -79,4 +81,30 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
emit(AuthError(ServerFailure.fromDioError(e).errMessage));
|
||||
}
|
||||
}
|
||||
|
||||
getTokenAndValidate() async {
|
||||
emit(AuthTokenLoading());
|
||||
final value =
|
||||
await const FlutterSecureStorage().read(key: Token.loginAccessTokenKey);
|
||||
|
||||
if (value == null) {
|
||||
emit(AuthTokenError("Token not found"));
|
||||
return;
|
||||
}
|
||||
|
||||
final tokenData = Token.decodeToken(value);
|
||||
|
||||
if (tokenData.containsKey('exp')) {
|
||||
final exp = tokenData['exp'] ?? 0;
|
||||
final currentTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
|
||||
if (currentTime < exp) {
|
||||
emit(AuthTokenSuccess());
|
||||
} else {
|
||||
emit(AuthTokenError("Token expired"));
|
||||
}
|
||||
} else {
|
||||
emit(AuthTokenError("Something went wrong"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,3 +21,13 @@ class AuthLoggedOut extends AuthState {}
|
||||
class AuthPasswordVisibilityChanged extends AuthState {}
|
||||
|
||||
class AuthAgreeToTermsChanged extends AuthState {}
|
||||
|
||||
class AuthTokenLoading extends AuthState {}
|
||||
|
||||
class AuthTokenSuccess extends AuthState {}
|
||||
|
||||
class AuthTokenError extends AuthState {
|
||||
final String message;
|
||||
|
||||
AuthTokenError(this.message);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user