Files
syncrow-app/lib/features/auth/bloc/auth_cubit.dart
Mohammad Salameh 79279180df 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.
2024-03-19 11:15:45 +03:00

111 lines
3.3 KiB
Dart

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/features/app_layout/bloc/nav_cubit.dart';
import 'package:syncrow_app/features/auth/model/login_with_email_model.dart';
import 'package:syncrow_app/features/auth/model/token.dart';
import 'package:syncrow_app/features/auth/model/user_model.dart';
import 'package:syncrow_app/services/api/authentication_api.dart';
import 'package:syncrow_app/services/api/network_exception.dart';
part 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
AuthCubit() : super(AuthInitial()) {
getTokenAndValidate();
}
static AuthCubit get(context) => BlocProvider.of(context);
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
bool isPasswordVisible = false;
static GlobalKey<FormState> formKey = GlobalKey<FormState>();
void changePasswordVisibility() {
isPasswordVisible = !isPasswordVisible;
emit(AuthPasswordVisibilityChanged());
}
bool agreeToTerms = false;
void changeAgreeToTerms() {
agreeToTerms = !agreeToTerms;
emit(AuthAgreeToTermsChanged());
}
static UserModel? user;
static Token token = Token.emptyConstructor();
// (FlutterSecureStorage().read(key :'token'));
login() async {
emit(AuthLoading());
try {
token = await AuthenticationAPI.loginWithEmail(
model: LoginWithEmailModel(
email: emailController.text.toLowerCase(),
password: passwordController.text,
),
);
if (token.accessTokenIsNotEmpty) {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write(
key: Token.loginAccessTokenKey, value: token.accessToken);
const FlutterSecureStorage().write(
key: UserModel.userUuidKey,
value: Token.decodeToken(token.accessToken)['uuid'].toString());
user = UserModel.fromToken(token);
emit(AuthSuccess());
} else {
emit(AuthError('Something went wrong'));
}
} on DioException catch (e) {
emit(AuthError(ServerFailure.fromDioError(e).errMessage));
}
}
logout() async {
emit(AuthLoading());
try {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.delete(key: Token.loginAccessTokenKey);
NavCubit.clear();
emit(AuthLoggedOut());
} on DioException catch (e) {
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"));
}
}
}