Untitled
unknown
dart
a year ago
39 kB
1
Indexable
Never
import 'dart:ui'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/services.dart'; import 'package:localize_and_translate/localize_and_translate.dart'; import 'package:mybynore/Screens/AppScreens/NavigationHub.dart'; import 'package:mybynore/Services/Utilities.dart'; import 'package:mybynore/Services/usermanagment.dart'; import 'package:mybynore/Widgets/WidgetAssets.dart'; import 'package:mybynore/Constants/appColors.dart'; import 'package:mybynore/Constants/strings.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:flutter_facebook_login/flutter_facebook_login.dart'; import 'package:mybynore/Screens/AppScreens/SignUp.dart'; import 'package:mybynore/models/user.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart'; class SignIn extends StatefulWidget { @override _SignInState createState() => _SignInState(); } class _SignInState extends State<SignIn> with SingleTickerProviderStateMixin { UserData me; final FirebaseFirestore fireStore = FirebaseFirestore.instance; UserManagment userManagement = new UserManagment(); AnimationController shakeCont; final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance; final Utilities _utilities = Utilities(); final _textEmail = TextEditingController(), _textPassword = TextEditingController(), _textEmailReset = TextEditingController(); bool loadingBefore = true, loading = false, activeAccount = false, resetPassword = false; String myUID, myDocID, devToken, email, password, majNameLogin; Timer _timer; @override void initState() { super.initState(); loadingOff(); shakeCont = AnimationController(duration: const Duration(milliseconds: 500), vsync: this); _firebaseMessaging.getToken().then((String token) { assert(token != null); devToken = "$token"; }); } @override dispose() { _timer.cancel(); super.dispose(); } @override Widget build(BuildContext context) { final double width = MediaQuery.of(context).size.width; final Animation<double> offsetAnimation = Tween(begin: 0.0, end: 24.0).chain(CurveTween(curve: Curves.elasticIn)).animate(shakeCont) ..addStatusListener((status) { if (status == AnimationStatus.completed) { shakeCont.reverse(); } }); return GestureDetector( onTap: () { FocusScopeNode currentFocus = FocusScope.of(context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } }, child: Scaffold( backgroundColor: GlobalUniversal.whiteBG, appBar: AppBar( automaticallyImplyLeading: false, brightness: Brightness.light, backgroundColor: Colors.transparent, elevation: 0.0, ), body: Stack( children: [ SafeArea( child: Container( alignment: Alignment.center, child: ListView( shrinkWrap: true, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( margin: EdgeInsets.only(bottom: 50.0), child: Image( image: AssetImage( 'assets/images/BigPurppleSecSh.png', ), height: width * 0.23, width: width * 0.46, ), ), Container( margin: EdgeInsets.only(bottom: 20.0), child: Text(translator.translate('login_title'), style: TextStyle( color: GlobalUniversal.blackColor, fontSize: 26.0, fontFamily: translator.translate('font'), fontWeight: FontWeight.bold, ), ), ), AnimatedBuilder( animation: offsetAnimation, builder: (buildContext, child) { return Container( padding: EdgeInsets.only( left: offsetAnimation.value + 24.0, right: 24.0 - offsetAnimation.value), child: Container( margin: EdgeInsets.only(bottom: 15.0), decoration: BoxDecoration( border: Border.all( color: GlobalUniversal.greyColorDark .withOpacity(0.4), // width: 1.0, ), ), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextField( controller: _textEmail, inputFormatters: [ WhitelistingTextInputFormatter( RegExp(r'[a-zA-Z0-9@._-]')) ], style: TextStyle( color: Colors.black, ), autofocus: false, autocorrect: false, decoration: InputDecoration( prefixIcon: Icon( Icons.email, color: GlobalUniversal.purple, ), border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15), fillColor: GlobalUniversal.whiteBG, filled: true, hintText: translator.translate('your_email'), hintStyle: TextStyle( color: GlobalUniversal.greyColorDark, fontSize: 15, fontFamily: translator.translate('font')), ), keyboardType: TextInputType .emailAddress, cursorColor: GlobalUniversal.darkBlue, onChanged: (val) { setState(() => email = val); }, ), Container(height: 1, color: GlobalUniversal.greyColorDark .withOpacity(0.4),), TextField( controller: _textPassword, style: TextStyle( color: Colors.black, ), autofocus: false, autocorrect: false, decoration: InputDecoration( prefixIcon: Icon( Icons.lock, color: GlobalUniversal.purple, ), border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15), fillColor: GlobalUniversal.whiteBG, filled: true, hintText: translator.translate('password'), hintStyle: TextStyle( color: GlobalUniversal.greyColorDark, fontSize: 15, fontFamily: translator.translate('font')), ), cursorColor: GlobalUniversal.darkBlue, obscureText: true, onChanged: (val) { setState(() => password = val); }, ), ], ), ), ); }), Container( width: width * 0.78, height: width * 0.1, margin: EdgeInsets.only(bottom: 20.0), child: RaisedButton( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(5.0), ), color: GlobalUniversal.purple, child: Text( translator.translate('login'), textScaleFactor: 1.0, style: TextStyle( color: GlobalUniversal.whiteBG, fontSize: 16, fontWeight: FontWeight.bold, fontFamily: translator.translate('font'))), onPressed: () async { FocusScopeNode currentFocus = FocusScope.of( context); if (!currentFocus.hasPrimaryFocus) { currentFocus.unfocus(); } if (_textEmail.text.isEmpty) { shakeCont.forward(from: 0.0); _utilities.showSnackWarning(context, translator.translate('enter_email')); return; } if (_textPassword .text.isEmpty) { shakeCont.forward(from: 0.0); _utilities.showSnackWarning(context, translator.translate('enter_password')); return; } if (password.length < 6) { _utilities.showSnackWarning(context, translator.translate('password_wrong_message')); return; } _textEmail.text = _textEmail.text.replaceAll( new RegExp(r"\s+"), ""); setState(() { email = _textEmail.text.replaceAll( new RegExp(r"\s+"), ""); }); setState(() => loading = true); try { UserCredential userCredential = await FirebaseAuth .instance.signInWithEmailAndPassword( email: email.trim(), password: password); // Activated if (userCredential.user.emailVerified) { fireStore .collection( USERS_COLLECTION) .where(UID_FIELD, isEqualTo: userCredential.user.uid) .get() .then((docs) { fireStore .doc( '/$USERS_COLLECTION/${docs.docs[0] .id}') .update({ DEV_TOKEN_FIELD: devToken, DEV_LANG_FIELD: translator.currentLanguage, EMAIL_VERIFY_FIELD: 'YES', }).then((val) { setUser(null).then((value) { Navigator .pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => NavigationHub( me: me, )), ModalRoute .withName( "/$PAGE_NAVIGATION")); _utilities.showSnackWarning(context, translator.translate('logged_in')); }); }).catchError((e) { FirebaseAuth.instance .signOut() .then((value) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); }); }); }); } // Not Activated else { FirebaseAuth.instance .signOut() .then((val) { setState(() { loading = false; activeAccount = true; }); }).catchError((e) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); }); } } on FirebaseAuthException catch (e) { setState(() => loading = false); if (e.code == 'user-not-found') { _utilities.showSnackWarning(context, translator.translate('user_not_found')); print('No user found for that email.'); } else if (e.code == 'wrong-password') { _utilities.showSnackWarning(context, translator.translate('wrong_password')); } print(e); } }, ), ), Container( margin: EdgeInsets.only(right: 10.0, left: 10), child: Align( alignment: Alignment.center, child: Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), // side: BorderSide(color: GlobalUniversal.purple,width: 2.0) ), elevation: 0.0, color: GlobalUniversal.whiteBG, child: Ink( child: Text( translator.translate('you_dont_have_account'), textScaleFactor: 1.0, textAlign: TextAlign.center, style: TextStyle( color: GlobalUniversal.secondaryText, fontSize: 13, fontFamily: translator.translate('font'), ), ), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SignUp( devToken: devToken, ))); }, ), RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), // side: BorderSide(color: GlobalUniversal.purple,width: 2.0) ), elevation: 0.0, color: GlobalUniversal.whiteBG, child: Ink( child: Text(translator.translate('forget_password_question'), textScaleFactor: 1.0, textAlign: TextAlign.center, style: TextStyle( color: GlobalUniversal.secondaryText, fontSize: 13, fontFamily: translator.translate('font'), ), ), ), onPressed: () { setState(() => resetPassword = true); }, ), ], ), ), ), Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(translator.translate('login_using'), style: new TextStyle( fontFamily: translator.translate('font'), color: GlobalUniversal.greyColorDark, fontSize: 15.0),), SizedBox(height: 5.0,), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: width * 0.1, height: width * 0.1, margin: EdgeInsets.all(5.0), decoration: BoxDecoration( shape: BoxShape.circle, color: GlobalUniversal.whiteBG, border: Border.all( color: GlobalUniversal.kGreyColor) ), child: InkWell( onTap: () { facebookSignIn(); }, customBorder: CircleBorder(), child: Padding( padding: EdgeInsets.all(8.0), child: Image.asset( "assets/icon/face_login.png", color: GlobalUniversal.faceColor,), ), ), ), Container( width: width * 0.1, height: width * 0.1, margin: EdgeInsets.all(5.0), decoration: BoxDecoration( shape: BoxShape.circle, color: GlobalUniversal.whiteBG, border: Border.all( color: GlobalUniversal.kGreyColor) ), child: InkWell( onTap: () { googleSignIn(); }, customBorder: CircleBorder(), child: Padding( padding: EdgeInsets.all(8.0), child: Image.asset( "assets/icon/google_login.png", color: Colors.red,), ), ) ), Visibility( visible: _utilities.platformUserDevice() == "iOS", child: Container( width: width * 0.1, height: width * 0.1, margin: EdgeInsets.all(5.0), decoration: BoxDecoration( shape: BoxShape.circle, color: GlobalUniversal.whiteBG, border: Border.all( color: GlobalUniversal .kGreyColor) ), child: InkWell( onTap: () { appleSignIn(); }, customBorder: CircleBorder(), child: Padding( padding: EdgeInsets.all(8.0), child: Image.asset( "assets/icon/apple_login.png"), ), ) ), ), ], ), ], ), Container( width: width * 0.1, height: width * 0.1, child: Visibility( visible: loading, child: CupertinoActivityIndicator(), ), ), ], ), ], ), ), ), Visibility( visible: activeAccount, child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 3.0, sigmaY: 3.0), child: Container( width: width, color: GlobalUniversal.blackColor.withOpacity(0.8), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: width * 0.3, height: width * 0.3, margin: EdgeInsets.only(bottom: 20.0), decoration: BoxDecoration( image: DecorationImage( image: AssetImage( "assets/icon/ic_warning.png"), ) ), ), Container( width: width * 0.8, child: Column( children: [ Text(translator.translate('inactive_account_message'), textScaleFactor: 1.2, textAlign: TextAlign.center, style: TextStyle( color: GlobalUniversal.whiteBG, fontSize: 15.0, fontFamily: translator.translate('font'), fontWeight: FontWeight.w700), ), Text( '\n"$email"', textScaleFactor: 1.2, textAlign: TextAlign.center, style: TextStyle( color: GlobalUniversal.whiteBG, fontSize: 15.0, fontFamily: translator.translate('font'), fontWeight: FontWeight.w700), ), ], ), ), Container( width: width * 0.5, child: RaisedButton( elevation: 5.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(40.0), side: BorderSide(color: Colors.transparent)), onPressed: () { setState(() => activeAccount = false); }, color: GlobalUniversal.whiteBG, textColor: GlobalUniversal.whiteBG.withOpacity( 0.5), child: Text(translator.translate('ok'), textScaleFactor: 1.2, style: new TextStyle( fontFamily: translator.translate('font'), color: GlobalUniversal.purple, fontSize: 15.0),), ), ), ], ), ), ),), Visibility(visible: loadingBefore, child: loadingBeforeToPrepare(width)), ], ), ) ); } void loadingOff() { const oneSec = const Duration(milliseconds: 1200); _timer = new Timer.periodic( oneSec, (Timer timer) => setState( () { loadingBefore = false; _timer.cancel(); }, ), ); } Future<void> completeSignIn(String accountType, String uID, String email, String fullName, String uPic) async { setState(() => loading = true); final QuerySnapshot emailCheck = await fireStore.collection(USERS_COLLECTION).where( 'email', isEqualTo: email.toLowerCase()).get(); final List <DocumentSnapshot> emailDocuments = emailCheck.docs; if (emailDocuments.length == 0) { DateTime time = DateTime.now(); fireStore .collection(USERS_COLLECTION) .add({ 'devtoken': devToken, 'devlang': translator.currentLanguage, 'accountType': accountType, 'email': email, 'password': null, 'uid': uID, 'name': fullName, 'uname': null, BIO_FIELD: "", 'uni_id': null, 'gender': null, 'genderAr': null, 'UniOrColl': null, 'wherestudy': "", 'wherestydyAr': null, 'uniname': "", 'majname': "", 'majnameAr': "", 'natname': null, 'natnameAr': null, 'searchKeyUname': null, 'uimg': "https://firebasestorage.googleapis.com/v0/b/bynore-retixn.appspot.com/o/AdminAssets%2Ficon_profile.png?alt=media&token=f9adde62-bc66-4d07-9e17-2960211c4365", 'email_verify': 'YES', 'identity_verify': 'NO', 'checkVerifyFirst': 'NO', 'searchKey': fullName.substring(0, 1).toUpperCase(), 'TotalFileUploaded': 0, 'FileCount': 0, 'UserPostsCount': 0, 'PostMajCount': 0, 'PostUniCount': 0, 'CommentMajCount': 0, 'CommentUniCount': 0, 'activeNoti': 0, 'allNoti': 0, 'faceLink': '', 'linkedInLink': '', 'instalink': '', 'date': time, }).then((value) { setUser(null).then((value) { Navigator .pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => NavigationHub( me: me, )), ModalRoute .withName( "/$PAGE_NAVIGATION")); _utilities.showSnackWarning(context, translator.translate('logged_in')); }); }).catchError((e) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); return; }); } else { fireStore .collection( USERS_COLLECTION) .where('uid', isEqualTo: uID) .get() .then((docs) { fireStore .doc( '/users/${docs.docs[0].id}') .update({ 'email_verify': 'YES', 'devtoken': devToken, 'devlang': translator.currentLanguage, }).then((val) { setUser(null).then((value) { Navigator .pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => NavigationHub( me: me, )), ModalRoute .withName( "/$PAGE_NAVIGATION")); _utilities.showSnackWarning(context, translator.translate('logged_in')); }); }).catchError((e) { FirebaseAuth.instance .signOut() .then((value) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); return; }); }); }).catchError((e) { FirebaseAuth.instance .signOut() .then((value) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); return; }); }); } } Future<void> resetPasswordByEmail(String email) async { await FirebaseAuth.instance.sendPasswordResetEmail(email: email).then(( value) { setState(() { resetPassword = false; loading = false; }); _utilities.showSnackWarning(context, translator.translate('check_your_inbox_link_mess')); }).catchError((e) { setState(() { resetPassword = false; loading = false; }); print(e); if (e.message.contains("There is no user record corresponding")) _utilities.showSnackWarning(context,translator.translate('email_not_linked_mess')); else if (e.message.contains("badly formatted")) _utilities.showSnackWarning(context, translator.translate('email_incorrect')); else _utilities.showSnackWarning(context, e.message); }); } Future<void> setUser(String id) async { me = await userManagement.getUser(id); setState(() => me = me); } Future <void> facebookSignIn() async { try { final FacebookLoginResult result = await FacebookLogin().logIn(["email"]); final String token = result.accessToken.token; // final response = await http.get('https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=${token}'); // final profile = jsonDecode(response.body); if (result.status == FacebookLoginStatus.loggedIn) { setState(() => loading = true); final AuthCredential credential = FacebookAuthProvider.credential( result.accessToken.token, ); UserCredential user = await FirebaseAuth.instance.signInWithCredential( credential); return completeSignIn( "Facebook", user.user.uid, user.user.email, user.user.displayName, user.user.photoURL); } else { setState(() => loading = false); } } catch (e) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); return; } } Future<void> googleSignIn() async { try { final GoogleSignIn _googleSignIn = GoogleSignIn( scopes: [ 'email' ], ); final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser .authentication; final GoogleAuthCredential googleCredential = GoogleAuthProvider .credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final UserCredential user = await FirebaseAuth.instance.signInWithCredential(googleCredential); return completeSignIn( "Google", user.user.uid, user.user.email, user.user.displayName, user.user.photoURL); } catch (e) { setState(() => loading = false); _utilities.showSnackWarning(context, e.message); } } Future<void> appleSignIn() async { final rawNonce = _utilities.generateNonce(); final nonce = _utilities.sha256ofString(rawNonce); try { final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], nonce: nonce, ); final oauthCredential = OAuthProvider("apple.com").credential( idToken: credential.identityToken, rawNonce: rawNonce, ); setState(() => loading = true); final UserCredential user = await FirebaseAuth.instance .signInWithCredential(oauthCredential); print(user.user.email); completeSignIn( "Apple", user.user.uid, user.user.email, user.user.displayName, ""); } catch (error) { print(error); setState(() => loading = false); _utilities.showSnackWarning(context, error.message, ); return; } } }