430 lines
16 KiB
Dart
430 lines
16 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:Tripz/constant/api_key.dart';
|
|
import 'package:Tripz/controller/functions/sss.dart';
|
|
import 'package:Tripz/env/env.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import 'package:Tripz/constant/info.dart';
|
|
import 'package:Tripz/controller/firebase/firbase_messge.dart';
|
|
import 'package:Tripz/controller/functions/add_error.dart';
|
|
import 'package:Tripz/views/auth/login_page.dart';
|
|
import 'package:Tripz/views/auth/sms_verfy_page.dart';
|
|
import 'package:Tripz/views/widgets/mydialoug.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:Tripz/constant/box_name.dart';
|
|
import 'package:Tripz/constant/links.dart';
|
|
import 'package:Tripz/controller/functions/crud.dart';
|
|
import 'package:Tripz/main.dart';
|
|
import 'package:Tripz/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 '../../constant/table_names.dart';
|
|
import '../../print.dart';
|
|
import '../functions/encrypt_decrypt.dart';
|
|
import '../functions/package_info.dart';
|
|
import '../functions/secure_storage.dart';
|
|
|
|
class LoginController extends GetxController {
|
|
final formKey = GlobalKey<FormState>();
|
|
final formKeyAdmin = GlobalKey<FormState>();
|
|
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 {
|
|
box.read(BoxName.isTest) == null ||
|
|
box.read(BoxName.isTest).toString() == '0'
|
|
? await getAppTester()
|
|
: null;
|
|
|
|
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());
|
|
update();
|
|
} else {
|
|
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 {
|
|
await SecurityHelper.performSecurityChecks();
|
|
String fingerPrint = await getDeviceFingerprint();
|
|
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,
|
|
);
|
|
Log.print('req: ${response1.request}');
|
|
Log.print('response: ${response1.body}');
|
|
Log.print('payload: ${payload}');
|
|
Log.print('decodedResponse1: ${jsonDecode(response1.body)}');
|
|
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 response0 = await http.post(
|
|
Uri.parse(AppLink.loginFirstTime),
|
|
body: {
|
|
'id': box.read(BoxName.passengerID) ?? AK.newId,
|
|
'password': AK.passnpassenger,
|
|
'aud': '${AK.allowed}$dev',
|
|
},
|
|
);
|
|
if (response0.statusCode == 200) {
|
|
final decodedResponse1 = jsonDecode(response0.body);
|
|
|
|
final jwt = decodedResponse1['jwt'];
|
|
final refreshToken = decodedResponse1['refresh_token'];
|
|
box.write(BoxName.jwt, X.c(X.c(X.c(jwt, cn), cC), cs));
|
|
// 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().getAIKey(Pasenger.payMobApikey);
|
|
await AppInitializer().getAIKey(Pasenger.FCM_PRIVATE_KEY);
|
|
await AppInitializer().getKey();
|
|
} else {}
|
|
} else {
|
|
await EncryptionHelper.initialize();
|
|
|
|
var payload = {
|
|
'id': box.read(BoxName.passengerID),
|
|
'password': AK.passnpassenger,
|
|
'aud': '${AK.allowed}$dev',
|
|
};
|
|
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, X.c(X.c(X.c(jwt, cn), cC), cs));
|
|
|
|
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(X
|
|
.r(X.r(X.r(box.read(BoxName.jwt), cn), cC), cs)
|
|
.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().contains('@')
|
|
? EncryptionHelper.instance.encryptData(email)
|
|
: email,
|
|
'id': passengerID,
|
|
"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 {
|
|
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.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,
|
|
EncryptionHelper.instance
|
|
.decryptData(d['inviteCode'].toString()) ??
|
|
'none')
|
|
: null;
|
|
|
|
var token = await CRUD().get(link: AppLink.getTokens, payload: {
|
|
'passengerID': box.read(BoxName.passengerID).toString()
|
|
});
|
|
var fingerPrint = await getDeviceFingerprint();
|
|
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
|
|
if (token != 'failure') {
|
|
if (EncryptionHelper.instance.decryptData(
|
|
jsonDecode(token)['data'][0]['token'].toString()) !=
|
|
box.read(BoxName.tokenFCM)) {
|
|
MyDialog().getDialog('change device'.tr, 'token change'.tr,
|
|
() async {
|
|
List<Future> updatetoken = [
|
|
CRUD().post(
|
|
link: "${AppLink.server}/ride/firebase/add.php",
|
|
payload: {
|
|
'token': box.read(BoxName.tokenFCM),
|
|
'passengerID': box.read(BoxName.passengerID).toString(),
|
|
'fingerPrint': (fingerPrint).toString()
|
|
}),
|
|
CRUD().post(
|
|
link:
|
|
"${AppLink.tripzAlexandriaServer}/ride/firebase/add.php",
|
|
payload: {
|
|
'token': box.read(BoxName.tokenFCM),
|
|
'passengerID': box.read(BoxName.passengerID).toString(),
|
|
'fingerPrint': (fingerPrint).toString()
|
|
}),
|
|
CRUD().post(
|
|
link: "${AppLink.tripzGizaServer}/ride/firebase/add.php",
|
|
payload: {
|
|
'token': box.read(BoxName.tokenFCM),
|
|
'passengerID': box.read(BoxName.passengerID).toString(),
|
|
'fingerPrint': (fingerPrint).toString()
|
|
}),
|
|
];
|
|
// cameras = await availableCameras();
|
|
await Future.wait(updatetoken);
|
|
Get.put(FirebaseMessagesController())
|
|
.sendNotificationToDriverMAP(
|
|
'token change'.tr,
|
|
'change device'.tr,
|
|
EncryptionHelper.instance.decryptData(
|
|
jsonDecode(token)['data'][0]['token'].toString()),
|
|
[],
|
|
'cancel.wav',
|
|
);
|
|
});
|
|
|
|
Future.delayed(const Duration(seconds: 1));
|
|
|
|
Get.defaultDialog(
|
|
title: 'Device Change Detected'.tr,
|
|
middleText:
|
|
'You can only use one device at a time. This device will now be set as your active device.'
|
|
.tr,
|
|
textConfirm: 'OK'.tr,
|
|
confirmTextColor: Colors.white,
|
|
onConfirm: () {
|
|
Get.back();
|
|
Get.offAll(() => const MapPagePassenger());
|
|
},
|
|
);
|
|
} else {}
|
|
} // 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": EncryptionHelper.instance
|
|
.encryptData(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-${EncryptionHelper.instance.decryptData(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': EncryptionHelper.instance.encryptData(emailController.text),
|
|
'id': passwordController.text
|
|
});
|
|
|
|
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.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<void> 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();
|
|
}
|
|
}
|