Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:convert';
- import 'package:get/get.dart';
- import 'package:ferry/ferry.dart';
- import 'package:hive/hive.dart';
- import 'package:myapp/app/routes/app_pages.dart';
- import 'package:myapp/graphql/TokenAuthAPI.req.gql.dart';
- import 'package:get_it/get_it.dart';
- import 'package:flutter_secure_storage/flutter_secure_storage.dart';
- class LoginController extends GetxController {
- //TODO: Implement LoginController
- final authState="".obs();
- @override
- void onInit() {
- super.onInit();
- }
- @override
- void onReady() {
- super.onReady();
- }
- @override
- void onClose() {}
- void signInWithEmailAndPassword(String email, String password) {
- final client= GetIt.instance<Client>(instanceName: 'authClient');
- final loginReq = GTokenAuthAPIReq(
- (b) => b
- ..vars.email = email.toLowerCase()
- ..vars.password = password
- );
- // final registerReq = GRegisterReq(
- // (b) => b
- // ..fetchPolicy = FetchPolicy.NetworkOnly
- // ..vars.r_email = "sumitisagodboy@gmail.com"
- // ..vars.r_password1 = "Sks1234@ak"
- // ..vars.r_password2 = "Sks1234@ak"
- // ..vars.r_username="Saran",
- // );
- client.request(loginReq).listen((response) async {if(response.hasErrors) {
- throw AuthenticationException(message: 'Wrong username or password');
- } else if (response.data!.tokenAuth!.success==true){
- var token = response.data!.tokenAuth!.token;
- print(["token is", response.data!.tokenAuth!.token]);
- var e= saveUserToken(token!);
- // final authBox = await Hive.openBox("auth");
- // authBox.put('token', token);
- Get.toNamed(Routes.HOME,arguments:[token,e]);
- authState("Authenticated");
- }
- else{
- throw AuthenticationException(message: 'Wrong username or password');
- }
- });
- }
- Future<void> saveUserToken(String token) async {
- try {
- final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
- var containsEncryptionKey = await secureStorage.containsKey(key: 'key');
- if (!containsEncryptionKey) {
- var key = Hive.generateSecureKey();
- await secureStorage.write(key: 'key', value: base64UrlEncode(key));
- }
- var encryptionKey = base64Url.decode((await secureStorage.read(key: 'key'))!);
- print('Encryption key: $encryptionKey');
- var encryptedBox = await Hive.openBox('auth', encryptionCipher: HiveAesCipher(encryptionKey));
- await encryptedBox.put('token', token);
- print(encryptedBox.get('token'));
- } on Exception catch (e) {
- throw Exception( e.toString());
- }
- }
- void signOut() {
- }
- }
- class AuthenticationException implements Exception {
- final String message;
- AuthenticationException({this.message = 'Unknown error occurred. '});
- }
Add Comment
Please, Sign In to add comment