25-10-2/1

This commit is contained in:
Hamza-Ayed
2025-10-02 01:20:16 +03:00
parent 7595be8067
commit c48627a175
342 changed files with 15825 additions and 14862 deletions

View File

@@ -1,204 +1,149 @@
import 'dart:io';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/controller/auth/login_controller.dart';
import 'package:Intaleq/controller/functions/encrypt_decrypt.dart';
import 'package:Intaleq/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../onbording_page.dart';
import '../../print.dart';
import '../../main.dart';
import '../functions/crud.dart';
import '../../onbording_page.dart';
import 'login_controller.dart';
class GoogleSignInHelper {
static final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'profile',
],
);
// ✅ GoogleSignIn singleton
static final GoogleSignIn _signIn = GoogleSignIn.instance;
// Method to handle Google Sign-In
static GoogleSignInAccount? _lastUser;
/// 👇 استدعها في main() مرة واحدة
static Future<void> init() async {
await _signIn.initialize(
serverClientId:
'594687661098-2u640akrb3k7sak5t0nqki6f4v6hq1bq.apps.googleusercontent.com',
);
// Events listener
_signIn.authenticationEvents.listen((event) async {
if (event is GoogleSignInAuthenticationEventSignIn) {
_lastUser = event.user;
await _handleSignUp(event.user);
} else if (event is GoogleSignInAuthenticationEventSignOut) {
_lastUser = null;
}
});
// silent login if possible
try {
await _signIn.attemptLightweightAuthentication();
} catch (_) {}
}
/// ✅ تسجيل دخول عادي
static Future<GoogleSignInAccount?> signIn() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
await _handleSignUp(googleUser);
// if (box.read(BoxName.countryCode) == 'Egypt') {
// Get.to(() => EgyptCardAI());
// } else if (box.read(BoxName.countryCode) == 'Jordan') {
// Get.to(() => AiPage());
// }
final user =
await _signIn.authenticate(scopeHint: const ['email', 'profile']);
if (user != null) {
_lastUser = user;
await _handleSignUp(user);
// اطبع القيم (للتأكد)
print("Google ID: ${user.id}");
print("Email: ${user.email}");
print("Name: ${user.displayName}");
print("Photo: ${user.photoUrl}");
}
return googleUser;
} catch (error) {
return user;
} on PlatformException catch (e) {
if (e.code == 'sign_in_required') {
await showGooglePlayServicesError();
}
return null;
} catch (e) {
await addError("Google Sign-In error: $e", "signIn()");
return null;
}
}
Future<GoogleSignInAccount?> signInFromLogin() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
await _handleSignUp(googleUser);
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
}
return googleUser;
} catch (error) {
// if (error is GoogleSignInAuthenticationException) {
// // Handle authentication errors from Google Sign-In
// addError("Google sign-in authentication error: ${error.message}",
// '<GoogleSignInAccount?> signInFromLogin()');
// } else if (error is GoogleSignInAccountNotFoundException) {
// // Handle the case where the user is not found (if applicable)
// addError("Google sign-in account not found error: ${error.message}",
// '<GoogleSignInAccount?> signInFromLogin()');
// }
// else
if (error is SocketException) {
// Handle network issues, like SSL certificate issues
addError("Network error (SSL certificate issue): ${error.message}",
'<GoogleSignInAccount?> signInFromLogin()');
} else if (error is PlatformException) {
// Handle platform-specific errors, like Google Play Services issues
if (error.code == 'sign_in_required') {
// Google Play Services are required but not installed or outdated
showGooglePlayServicesError();
} else {
addError("Platform error: ${error.message}",
'<GoogleSignInAccount?> signInFromLogin()');
}
} else {
// Catch all other unknown errors
addError("Unknown error: ${error.toString()}",
'<GoogleSignInAccount?> signInFromLogin()');
}
return null;
}
}
void showGooglePlayServicesError() async {
const playStoreUrl =
'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
if (await canLaunchUrl(Uri.parse(playStoreUrl))) {
await launchUrl(Uri.parse(playStoreUrl));
} else {
// Fallback if the URL can't be opened
showDialog(
context: Get.context!,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'.tr),
content: Text(
'Could not open the Google Play Store. Please update Google Play Services manually.'
.tr),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Close'.tr),
),
],
);
},
/// ✅ تسجيل دخول مخصص لشاشة Login (مع استدعاء الكنترولر)
static Future<GoogleSignInAccount?> signInFromLogin() async {
await init();
final user = await signIn();
if (user != null) {
await Get.put(LoginController()).loginUsingCredentials(
box.read(BoxName.passengerID).toString(),
box.read(BoxName.email).toString(),
);
}
return user;
}
// Future<GoogleSignInAccount?> signInFromLogin() async {
// try {
// final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
// if (googleUser != null) {
// await _handleSignUp(googleUser);
// // if (box.read(BoxName.countryCode) == 'Egypt') {
// await Get.put(LoginController()).loginUsingCredentials(
// box.read(BoxName.passengerID).toString(),
// box.read(BoxName.email).toString(),
// );
// // } else if (box.read(BoxName.countryCode) == 'Jordan') {
// // // Get.to(() => AiPage());
// // }
// }
// return googleUser;
// } catch (error) {
// addError(error.toString(), '<GoogleSignInAccount?> signInFromLogin()');
// return null;
// }
// }
/// ✅ طلب سكوبات إضافية (بديل withScopes القديم)
static Future<void> requestExtraScopes(List<String> scopes) async {
final user = _lastUser;
if (user == null) return;
await user.authorizationClient.authorizeScopes(scopes);
}
addError(String error, where) async {
CRUD().post(link: AppLink.addError, payload: {
'error': error.toString(), // Example error description
'userId': box.read(BoxName.driverID) ??
box.read(BoxName.passengerID), // Example user ID
'userType': box.read(BoxName.driverID) != null
? 'Driver'
: 'passenger', // Example user type
'phone': box.read(BoxName.phone) ??
box.read(BoxName.phoneDriver), // Example phone number
/// ✅ تسجيل خروج
static Future<void> signOut() async {
await _signIn.signOut();
await _handleSignOut();
}
'device': where
static GoogleSignInAccount? getCurrentUser() => _lastUser;
// ================= Helpers ==================
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
box.write(BoxName.passengerID, user.id);
box.write(BoxName.email, user.email);
box.write(BoxName.name, user.displayName ?? '');
box.write(BoxName.passengerPhotoUrl, user.photoUrl ?? '');
}
static Future<void> _handleSignOut() async {
box.erase();
Get.offAll(OnBoardingPage());
}
static Future<void> addError(String error, String where) async {
await CRUD().post(link: AppLink.addError, payload: {
'error': error,
'userId': box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
'userType': box.read(BoxName.driverID) != null ? 'Driver' : 'Passenger',
'phone': box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver),
'device': where,
});
}
// Method to handle Google Sign-Out
static Future<void> signOut() async {
try {
await _googleSignIn.signOut();
await _handleSignOut();
} catch (error) {}
}
// Method to get the current signed-in user
static GoogleSignInAccount? getCurrentUser() {
return _googleSignIn.currentUser;
}
// Method to handle sign-up process
static Future<void> _handleSignUp(GoogleSignInAccount user) async {
// Store driver information
box.write(BoxName.passengerID, user.id);
box.write(BoxName.email, (user.email));
box.write(BoxName.name, (user.displayName.toString()));
box.write(BoxName.passengerPhotoUrl, (user.photoUrl.toString()));
// Perform any additional sign-up tasks or API calls here
// For example, you can send the user data to your server for registration
}
// Method to handle sign-out process
static Future<void> _handleSignOut() async {
// Clear stored driver information
box.erase();
// box.remove(BoxName.passengerPhotoUrl);
// box.remove(BoxName.driverID);
// box.remove(BoxName.email);
// box.remove(BoxName.lang);
// box.remove(BoxName.name);
// box.remove(BoxName.passengerID);
// box.remove(BoxName.phone);
// box.remove(BoxName.tokenFCM);
// box.remove(BoxName.tokens);
// box.remove(BoxName.addHome);
// box.remove(BoxName.addWork);
// box.remove(BoxName.agreeTerms);
// box.remove(BoxName.apiKeyRun);
// box.remove(BoxName.countryCode);
// box.remove(BoxName.accountIdStripeConnect);
// box.remove(BoxName.passengerWalletTotal);
// box.remove(BoxName.isVerified);
// box.remove(BoxName.firstTimeLoadKey);
Get.offAll(() => OnBoardingPage());
// Perform any additional sign-out tasks or API calls here
// For example, you can notify your server about the user sign-out
static Future<void> showGooglePlayServicesError() async {
const playStoreUrl =
'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
final uri = Uri.parse(playStoreUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri);
} else {
showDialog(
context: Get.context!,
builder: (context) => AlertDialog(
title: Text('Error'.tr),
content: Text(
'Could not open the Google Play Store. Please update Google Play Services manually.'
.tr,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Close'.tr),
),
],
),
);
}
}
}

View File

@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:Intaleq/constant/api_key.dart';
import 'package:Intaleq/views/auth/otp_page.dart';
import 'package:http/http.dart' as http;
import 'package:Intaleq/constant/info.dart';
@@ -173,149 +174,161 @@ class LoginController extends GetxController {
await AppInitializer().getKey();
final refreshToken = decodedResponse1['refresh_token'];
await storage.write(key: BoxName.refreshToken, value: refreshToken);
} else {}
// final refreshToken = decodedResponse1['refresh_token'];
// await storage.write(key: BoxName.refreshToken, value: refreshToken);
}
}
}
loginUsingCredentials(String passengerID, email) async {
Future<void> loginUsingCredentials(String passengerID, String email) async {
isloading = true;
update();
// bool isTokenExpired = JwtDecoder.isExpired(
// r(box.read(BoxName.jwt)).toString().split(AppInformation.addd)[0]);
await getJWT();
// if (isTokenExpired) {
// // Log.print('isTokenExpired loginUsingCredentials: ${isTokenExpired}');
// await getJWT();
// }
try {
// 1) استعلام تسجيل الدخول
final res = await CRUD().get(
link: AppLink.loginFromGooglePassenger,
payload: {
'email': email,
'id': passengerID, // استخدم المعامل مباشرة
'platform': Platform.isAndroid ? 'android' : 'ios',
'appName': AppInformation.appName,
},
);
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());
if (res == 'Failure') {
Get.snackbar("User does not exist.".tr, '',
backgroundColor: Colors.red);
return;
}
// 2) فك JSON مرة واحدة
final decoded = jsonDecode(res);
if (decoded is! Map || decoded.isEmpty) return;
final status = (decoded['status'] ?? '').toString();
final data = (decoded['data'] as List?)?.firstOrNull as Map? ?? {};
if (status != 'success' || data['verified'].toString() != '1') {
// غير مُفعل -> أذهب للتسجيل بالـ SMS
Get.offAll(() => PhoneNumberScreen());
return;
}
// 3) كتابة القيم (خفيفة)
box.write(BoxName.isVerified, '1');
box.write(BoxName.email, data['email']);
box.write(BoxName.phone, data['phone']);
box.write(BoxName.name, data['first_name']);
box.write(BoxName.isTest, '1');
box.write(BoxName.package, data['package']);
box.write(BoxName.promo, data['promo']);
box.write(BoxName.discount, data['discount']);
box.write(BoxName.validity, data['validity']);
box.write(BoxName.isInstall, data['isInstall'] ?? 'none');
box.write(BoxName.isGiftToken, data['isGiftToken'] ?? 'none');
if (data['inviteCode'] != null) {
box.write(BoxName.inviteCode, data['inviteCode'].toString());
}
// مهم: تأكد من passengerID في الـ box
box.write(BoxName.passengerID, passengerID);
// 4) نفّذ عمليات مكلفة بالتوازي: getTokens + fingerprint
final results = await Future.wait([
CRUD().get(link: AppLink.getTokens, payload: {
'passengerID': passengerID, // FIX: لا تستخدم box هنا
}),
DeviceHelper.getDeviceFingerprint(),
]);
await box.write(BoxName.firstTimeLoadKey, 'false');
final tokenResp = results[0];
final fingerPrint = (results[1] ?? '').toString();
await storage.write(key: BoxName.fingerPrint, value: fingerPrint);
if (email != '962798583052@intaleqapp.com' && tokenResp != 'failure') {
final tokenJson = jsonDecode(tokenResp);
final serverToken = tokenJson['message']?['token']?.toString() ?? '';
// Log.print('serverToken: ${serverToken}');
final localFcm = (box.read(BoxName.tokenFCM) ?? '').toString();
// Log.print('localFcm: ${localFcm}');
// 5) اختلاف الجهاز -> تحقّق OTP
if (serverToken.isNotEmpty && serverToken != localFcm) {
final goVerify = await _confirmDeviceChangeDialog();
if (goVerify == true) {
await Get.to(() => OtpVerificationPage(
phone: data['phone'].toString(),
deviceToken: fingerPrint,
token: tokenResp.toString(),
ptoken: serverToken,
));
// بعد العودة من OTP (نجح/فشل)، أخرج من الميثود كي لا يحصل offAll مرتين
return;
}
}
}
// 6) منطق الدعوة (إن وُجد) ثم الانتقال
final invite = box.read(BoxName.inviteCode)?.toString() ?? 'none';
final isInstall = box.read(BoxName.isInstall)?.toString() ?? '0';
if (invite != 'none' && isInstall != '1') {
try {
await CRUD().post(link: AppLink.updatePassengersInvitation, payload: {
"inviteCode": invite,
"passengerID": passengerID,
});
await Get.defaultDialog(
title: 'Invitation Used'.tr,
middleText: "Your invite code was successfully applied!".tr,
textConfirm: "OK".tr,
confirmTextColor: Colors.white,
onConfirm: () async {
try {
await CRUD().post(link: AppLink.addPassengersPromo, payload: {
"promoCode":
'I-${(box.read(BoxName.name)).toString().split(' ').first}',
"amount": '25',
"passengerID": passengerID,
"description": 'promo first'
});
} catch (e) {
addError(
e.toString(), 'promo on invitation in login_controller');
} finally {
Get.offAll(() => const MapPagePassenger());
}
},
);
return;
} catch (_) {
// حتى لو فشل، كمل للصفحة الرئيسية
}
}
Get.offAll(() => const MapPagePassenger());
} catch (e, st) {
addError('$e', 'loginUsingCredentials');
Get.snackbar('Error', e.toString(), backgroundColor: Colors.redAccent);
} finally {
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();
}
}
}
Future<bool?> _confirmDeviceChangeDialog() {
return Get.defaultDialog<bool>(
barrierDismissible: false,
title: 'Device Change Detected'.tr,
middleText: 'Please verify your identity'.tr,
textConfirm: 'Verify'.tr,
confirmTextColor: Colors.white,
onConfirm: () => Get.back(result: true),
textCancel: 'Cancel'.tr,
onCancel: () => Get.back(result: false),
);
}
void login() async {
isloading = true;
update();

View File

@@ -7,6 +7,7 @@ import '../../../print.dart';
import '../../views/auth/otp_page.dart';
import '../../views/widgets/error_snakbar.dart';
import '../functions/crud.dart';
import '../functions/package_info.dart';
import 'login_controller.dart';
// --- Helper Class for Phone Authentication ---
@@ -83,6 +84,24 @@ class PhoneAuthHelper {
}
}
static Future<void> _addTokens() async {
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
await CRUD()
.post(link: "${AppLink.server}/ride/firebase/add.php", payload: {
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint
});
await CRUD().post(
link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
payload: {
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint
});
}
static Future<void> registerUser({
required String phoneNumber,
required String firstName,
@@ -102,6 +121,7 @@ class PhoneAuthHelper {
final data = (response);
if (data != 'failure') {
// Registration successful, log user in
await _addTokens();
await _handleSuccessfulLogin(data['message']['data']);
} else {
mySnackeBarError(

View File

@@ -9,6 +9,7 @@ import 'package:get/get.dart';
import '../../print.dart';
import '../../views/home/map_page_passenger.dart';
import '../firebase/firbase_messge.dart';
import '../functions/package_info.dart';
class OtpVerificationController extends GetxController {
final String phone;
@@ -49,6 +50,7 @@ class OtpVerificationController extends GetxController {
}
Future<void> sendOtp() async {
if (isLoading.value) return;
isLoading.value = true;
try {
final response = await CRUD().post(
@@ -60,48 +62,60 @@ class OtpVerificationController extends GetxController {
);
if (response != 'failure') {
isLoading.value = true;
// بإمكانك عرض رسالة نجاح هنا
} else {
// Get.snackbar('Error', 'Failed to send OTP');
Get.snackbar('Error'.tr, 'Failed to send OTP'.tr);
}
} catch (e) {
Get.snackbar('Error', e.toString());
} finally {
isLoading.value = false;
// isLoading.value = false;
}
}
Future<void> verifyOtp(String ptoken) async {
isVerifying.value = true;
var finger = await storage.read(key: BoxName.fingerPrint);
try {
String fingerPrint = await DeviceHelper.getDeviceFingerprint();
final response = await CRUD().post(
link: '${AppLink.server}/auth/token_passenger/verify_otp.php',
payload: {
'phone_number': phone,
'otp': otpCode.value,
'token': box.read(BoxName.tokenFCM).toString(),
'fingerPrint': finger.toString(),
'fingerPrint': fingerPrint.toString(),
},
);
if (response != 'failure' && response['status'] == 'success') {
Get.back(); // توجه إلى الصفحة التالية
await Get.put(FirebaseMessagesController()).sendNotificationToDriverMAP(
final fcm = Get.isRegistered<FirebaseMessagesController>()
? Get.find<FirebaseMessagesController>()
: Get.put(FirebaseMessagesController());
await fcm.sendNotificationToDriverMAP(
'token change',
'change device'.tr,
ptoken.toString(),
[],
'cancel.wav',
);
CRUD().post(
link:
'${AppLink.seferPaymentServer}/auth/token/update_passenger_token.php',
await CRUD().post(
link: "${AppLink.seferPaymentServer}/ride/firebase/add.php",
payload: {
'token': box.read(BoxName.tokenDriver).toString(),
'fingerPrint': finger.toString(),
'token': (box.read(BoxName.tokenFCM.toString())),
'passengerID': box.read(BoxName.passengerID).toString(),
"fingerPrint": fingerPrint.toString(),
});
// CRUD().post(
// link:
// '${AppLink.seferPaymentServer}/auth/token/update_passenger_token.php',
// payload: {
// 'token': box.read(BoxName.tokenFCM).toString(),
// 'fingerPrint': fingerPrint.toString(),
// 'passengerID': box.read(BoxName.passengerID).toString(),
// });
Get.offAll(() => const MapPagePassenger());
} else {
Get.snackbar('Verification Failed', 'OTP is incorrect or expired');