import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:Intaleq/constant/api_key.dart'; import 'package:http/http.dart' as http; import 'package:Intaleq/constant/info.dart'; import 'package:Intaleq/controller/functions/add_error.dart'; import 'package:Intaleq/views/auth/login_page.dart'; import 'package:Intaleq/views/auth/sms_verfy_page.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:Intaleq/constant/box_name.dart'; import 'package:Intaleq/constant/links.dart'; import 'package:Intaleq/controller/functions/crud.dart'; import 'package:Intaleq/main.dart'; import 'package:Intaleq/views/home/map_page_passenger.dart'; import 'package:jwt_decoder/jwt_decoder.dart'; import 'package:location/location.dart'; import 'package:secure_string_operations/secure_string_operations.dart'; import '../../constant/char_map.dart'; import '../../print.dart'; import '../../views/auth/otp_token_page.dart'; import '../functions/encrypt_decrypt.dart'; import '../functions/package_info.dart'; import '../functions/secure_storage.dart'; import '../functions/securty_check.dart'; class LoginController extends GetxController { final formKey = GlobalKey(); final formKeyAdmin = GlobalKey(); TextEditingController emailController = TextEditingController(); TextEditingController phoneController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController adminPasswordController = TextEditingController(); TextEditingController adminNameController = TextEditingController(); bool isAgreeTerms = false; bool isloading = false; late int isTest = 1; void changeAgreeTerm() { isAgreeTerms = !isAgreeTerms; update(); } var dev = ''; @override void onInit() async { await getAppTester(); Log.print('box.read(BoxName.isTest): ${box.read(BoxName.isTest)}'); box.write(BoxName.countryCode, 'Syria'); super.onInit(); } getAppTester() async { var res = await CRUD().get( link: AppLink.getTesterApp, payload: {'appPlatform': AppInformation.appName}); if (res != 'failure') { var d = jsonDecode(res); isTest = int.parse(d['message'][0]['isTest'].toString()); box.write(BoxName.isTest, isTest); update(); } else { box.write(BoxName.isTest, '1'); update(); return false; } } updateAppTester(String appPlatform) async { await CRUD().post( link: AppLink.updateTesterApp, payload: {'appPlatform': appPlatform}); } void saveAgreementTerms() { box.write(BoxName.agreeTerms, 'agreed'); update(); } void saveCountryCode(String countryCode) { box.write(BoxName.countryCode, countryCode); update(); } getJwtWallet() async { final random = Random(); if (random.nextBool()) { await SecurityHelper.performSecurityChecks(); } else { await SecurityChecks.isDeviceRootedFromNative(Get.context!); } String fingerPrint = await DeviceHelper.getDeviceFingerprint(); // print('fingerPrint: ${fingerPrint}'); dev = Platform.isAndroid ? 'android' : 'ios'; var payload = { 'id': box.read(BoxName.passengerID), 'password': AK.passnpassenger, 'aud': '${AK.allowed}$dev', 'fingerPrint': fingerPrint }; var response1 = await http.post( Uri.parse(AppLink.loginJwtWalletRider), body: payload, ); await box.write(BoxName.hmac, jsonDecode(response1.body)['hmac']); // Log.print('jsonDecoeded[hmac]: ${jsonDecoeded['hmac']}'); // Log.print('req: ${response1.request}'); // Log.print('response: ${response1.body}'); // Log.print('payload: ${payload}'); return jsonDecode(response1.body)['jwt'].toString(); } getJWT() async { // print(Pasenger.pasengerpas); // await SecurityHelper.performSecurityChecks(); Log.print('firstTimeLoadKey: ${box.read(BoxName.firstTimeLoadKey)}'); dev = Platform.isAndroid ? 'android' : 'ios'; if (box.read(BoxName.firstTimeLoadKey).toString() != 'false') { var payload = { 'id': box.read(BoxName.passengerID) ?? AK.newId, 'password': AK.passnpassenger, 'aud': '${AK.allowed}$dev', }; // Log.print('payload: ${payload}'); var response0 = await http.post( Uri.parse(AppLink.loginFirstTime), body: payload, ); if (response0.statusCode == 200) { final decodedResponse1 = jsonDecode(response0.body); final jwt = decodedResponse1['jwt']; final refreshToken = decodedResponse1['refresh_token']; box.write(BoxName.jwt, c(jwt)); // Sss.write(BoxName.jwt, jwt); await storage.write(key: BoxName.refreshToken, value: refreshToken); // await AppInitializer().getAIKey(Pasenger.keyOfApp); // await AppInitializer().getAIKey(Pasenger.initializationVector); // await Future.delayed(Duration.zero); await EncryptionHelper.initialize(); await AppInitializer().getKey(); } else {} } else { await EncryptionHelper.initialize(); var payload = { 'id': box.read(BoxName.passengerID), 'password': box.read(BoxName.email), 'aud': '${AK.allowed}$dev', }; // Log.print('payload: ${payload}'); var response1 = await http.post( Uri.parse(AppLink.loginJwtRider), body: payload, ); // Log.print('req: ${response1.request}'); // Log.print('response: ${response1.body}'); // Log.print('payload: ${payload}'); // Log.print('decodedResponse1: ${jsonDecode(response1.body)}'); if (response1.statusCode == 200) { final decodedResponse1 = jsonDecode(response1.body); // Log.print('decodedResponse1: ${decodedResponse1}'); final jwt = decodedResponse1['jwt']; await box.write(BoxName.jwt, c(jwt)); await AppInitializer().getKey(); final refreshToken = decodedResponse1['refresh_token']; await storage.write(key: BoxName.refreshToken, value: refreshToken); } else {} } } loginUsingCredentials(String passengerID, email) async { isloading = true; update(); // bool isTokenExpired = JwtDecoder.isExpired( // r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]); // if (isTokenExpired) { // // Log.print('isTokenExpired loginUsingCredentials: ${isTokenExpired}'); // await getJWT(); // } var res = await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: { 'email': email.toString(), 'id': passengerID.toString(), "platform": Platform.isAndroid ? 'android' : 'ios', "appName": AppInformation.appName, }); if (res == 'Failure') { // Get.offAll(SmsSignupEgypt()); isloading = false; update(); Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red); } else { // Log.print('res: ${res}'); var jsonDecoeded = jsonDecode(res); if (jsonDecoeded.isNotEmpty) { var d = jsonDecoeded['data'][0]; if (jsonDecoeded['status'] == 'success' && d['verified'].toString() == '1') { // box.write(BoxName.isVerified, '1'); box.write(BoxName.email, d['email']); box.write(BoxName.phone, d['phone']); box.write(BoxName.name, d['first_name']); box.write(BoxName.isTest, '1'); box.write(BoxName.package, d['package']); box.write(BoxName.promo, d['promo']); box.write(BoxName.discount, d['discount']); box.write(BoxName.validity, d['validity']); box.write(BoxName.isInstall, d['isInstall'] ?? 'none'); box.write(BoxName.isGiftToken, d['isGiftToken'] ?? 'none'); box.write(BoxName.firstTimeLoadKey, 'false'); d['inviteCode'] != null ? box.write( BoxName.inviteCode, (d['inviteCode'].toString()) ?? 'none') : null; var token = await CRUD().get(link: AppLink.getTokens, payload: { 'passengerID': box.read(BoxName.passengerID).toString() }); var fingerPrint = await DeviceHelper.getDeviceFingerprint(); Log.print('fingerPrint 0: ${fingerPrint}'); await storage.write(key: BoxName.fingerPrint, value: fingerPrint); if (email == '962798583052@intaleqapp.com') { } else { if (token != 'failure') { if ((jsonDecode(token)['message']['token'].toString()) != box.read(BoxName.tokenFCM)) { await Get.defaultDialog( barrierDismissible: false, title: 'Device Change Detected'.tr, middleText: 'Please verify your identity'.tr, textConfirm: 'Verify'.tr, confirmTextColor: Colors.white, onConfirm: () { // Get.back(); // انتقل لصفحة OTP الجديدة Get.to( () => OtpVerificationPage( phone: d['phone'].toString(), deviceToken: fingerPrint.toString(), token: token.toString(), ptoken: jsonDecode(token)['message']['token'].toString(), ), ); }, ); } } } // Logging to check if inviteCode is written correctly if (d['inviteCode'] != 'none' && d['inviteCode'] != null && // box.read(BoxName.inviteCode).toString() != 'none' && box.read(BoxName.isInstall).toString() != '1') { await CRUD() .post(link: AppLink.updatePassengersInvitation, payload: { "inviteCode": (box.read(BoxName.inviteCode).toString()), "passengerID": box.read(BoxName.passengerID).toString(), }); Get.defaultDialog( title: 'Invitation Used' .tr, // Automatically translates based on the current locale middleText: "Your invite code was successfully applied!" .tr, // Automatically translates based on the current locale onConfirm: () { try { CRUD().post(link: AppLink.addPassengersPromo, payload: { "promoCode": 'S-${(box.read(BoxName.name)).toString().split(' ')[0]}', "amount": '25', "passengerID": box.read(BoxName.passengerID).toString(), "description": 'promo first' }); } catch (e) { addError(e.toString(), 'passenger Invitation Used dialogu as promo line 185 login_controller'); } finally { // Continue with the rest of your flow, regardless of errors // For example, navigate to the next page Get.offAll(() => const MapPagePassenger()); } }, textConfirm: "OK".tr, // Confirm button text ); } else { Get.offAll(() => const MapPagePassenger()); } } else { Get.offAll(() => SmsSignupEgypt()); // Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'], // backgroundColor: Colors.redAccent); isloading = false; update(); } } else { isloading = false; update(); } } } void login() async { isloading = true; update(); var res = await CRUD().get(link: AppLink.loginFromGooglePassenger, payload: { 'email': (emailController.text), 'id': passwordController.text, "platform": Platform.isAndroid ? 'android' : 'ios', "appName": AppInformation.appName, }); isloading = false; update(); if (res == 'Failure') { //Failure Get.offAll(() => LoginPage()); isloading = false; update(); // Get.snackbar("User does not exist.".tr, '', backgroundColor: Colors.red); } else { var jsonDecoeded = jsonDecode(res); if (jsonDecoeded.isNotEmpty) { if (jsonDecoeded['status'] == 'success' && jsonDecoeded['data'][0]['verified'].toString() == '1') { // box.write(BoxName.isVerified, '1'); box.write(BoxName.email, jsonDecoeded['data'][0]['email']); box.write(BoxName.name, jsonDecoeded['data'][0]['first_name']); box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']); box.write(BoxName.passengerID, passwordController.text); // var token = await CRUD().get(link: AppLink.getTokens, payload: { // 'passengerID': box.read(BoxName.passengerID).toString() // }); await updateAppTester(AppInformation.appName); Get.offAll(() => const MapPagePassenger()); } else { // Get.offAll(() => SmsSignupEgypt()); // Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'], // backgroundColor: Colors.redAccent); isloading = false; update(); } } else { isloading = false; update(); } } } goToMapPage() { if (box.read(BoxName.email) != null) { Get.offAll(() => const MapPagePassenger()); } } final location = Location(); // late PermissionStatus permissionGranted = PermissionStatus.denied; Future getLocationPermission() async { bool serviceEnabled; PermissionStatus permissionGranted; // Check if location services are enabled serviceEnabled = await location.serviceEnabled(); if (!serviceEnabled) { serviceEnabled = await location.requestService(); if (!serviceEnabled) { // Location services are still not enabled, handle the error return; } } // Check if the app has permission to access location permissionGranted = await location.hasPermission(); if (permissionGranted == PermissionStatus.denied) { permissionGranted = await location.requestPermission(); if (permissionGranted != PermissionStatus.granted) { // Location permission is still not granted, handle the error permissionGranted = await location.requestPermission(); return; } } if (permissionGranted.toString() == 'PermissionStatus.granted') { box.write(BoxName.locationPermission, 'true'); } update(); } }