mirror of
https://github.com/SyncrowIOT/syncrow-app.git
synced 2025-07-16 10:06:16 +00:00
71 lines
2.0 KiB
Dart
71 lines
2.0 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter/cupertino.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.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';
|
|
import 'package:syncrow_app/utils/helpers/decode_base64.dart';
|
|
|
|
part 'auth_state.dart';
|
|
|
|
class AuthCubit extends Cubit<AuthState> {
|
|
AuthCubit() : super(AuthInitial());
|
|
|
|
static AuthCubit get(context) => BlocProvider.of(context);
|
|
|
|
TextEditingController emailController = TextEditingController();
|
|
TextEditingController passwordController = TextEditingController();
|
|
bool isPasswordVisible = false;
|
|
|
|
GlobalKey<FormState> formKey = GlobalKey<FormState>();
|
|
|
|
void changePasswordVisibility() {
|
|
isPasswordVisible = !isPasswordVisible;
|
|
emit(AuthPasswordVisibilityChanged());
|
|
}
|
|
|
|
bool agreeToTerms = false;
|
|
|
|
void changeAgreeToTerms() {
|
|
agreeToTerms = !agreeToTerms;
|
|
emit(AuthAgreeToTermsChanged());
|
|
}
|
|
|
|
UserModel? user;
|
|
|
|
Token token = Token.emptyConstructor();
|
|
|
|
// (FlutterSecureStorage().read(key :'token'));
|
|
|
|
login() async {
|
|
emit(AuthLoading());
|
|
try {
|
|
token = await AuthenticationAPI.loginWithEmail(
|
|
email: emailController.text.toLowerCase(),
|
|
password: passwordController.text,
|
|
);
|
|
|
|
if (token.accessTokenIsNotEmpty) {
|
|
final parts = token.accessToken.split('.');
|
|
if (parts.length != 3) {
|
|
throw Exception('invalid access token');
|
|
}
|
|
final payload = decodeBase64(parts[1]);
|
|
final payloadMap = json.decode(payload); //Map dictionary
|
|
user = UserModel.fromToken(payloadMap);
|
|
emit(AuthSuccess());
|
|
} else {
|
|
emit(AuthError('Something went wrong'));
|
|
}
|
|
} catch (e) {
|
|
if (e is ServerFailure) {
|
|
emit(AuthError(e.errMessage));
|
|
}
|
|
emit(AuthError(e.toString()));
|
|
}
|
|
}
|
|
}
|