public async Task <AppleAccount> SignInAsync()
        {
            var appleIdProvider = new ASAuthorizationAppleIdProvider();
            var request         = appleIdProvider.CreateRequest();

            request.RequestedScopes = new[] { ASAuthorizationScope.Email, ASAuthorizationScope.FullName };

            var authorizationController = new ASAuthorizationController(new[] { request });

            authorizationController.Delegate = this;
            authorizationController.PresentationContextProvider = this;
            authorizationController.PerformRequests();

            tcsCredential = new TaskCompletionSource <ASAuthorizationAppleIdCredential>();

            var creds = await tcsCredential.Task;

            if (creds == null)
            {
                return(null);
            }

            var appleAccount = new AppleAccount();

            appleAccount.Token          = new NSString(creds.IdentityToken, NSStringEncoding.UTF8).ToString();
            appleAccount.Email          = creds.Email;
            appleAccount.UserId         = creds.User;
            appleAccount.Name           = NSPersonNameComponentsFormatter.GetLocalizedString(creds.FullName, NSPersonNameComponentsFormatterStyle.Default, NSPersonNameComponentsFormatterOptions.Phonetic);
            appleAccount.RealUserStatus = creds.RealUserStatus.ToString();

            return(appleAccount);
        }
Beispiel #2
0
        public async void FacebookAuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= FacebookAuthenticatorCompleted;
                authenticator.Error     -= FacebookAutheticatorError;
            }

            if (e.IsAuthenticated)
            {
                UserDialogs.Instance.ShowLoading("We are processing your request...");
                var authenticationStatus = await client.UserVerification(e, null, "FACEBOOK");

                if (authenticationStatus == "EMAIL WAS NOT FOUND")
                {
                    var account = new AppleAccount();
                    account.Email          = "*****@*****.**";
                    account.UserId         = "";
                    account.Name           = "";
                    account.RealUserStatus = "";
                    account.Token          = "";

                    authenticationStatus = await client.UserVerification(null, account, "APPLE");
                }

                ProcessRequest(authenticationStatus);
            }
        }
        public bool Callback(string url)
        {
            // Only handle the url with our callback uri scheme
            if (!url.StartsWith(CallbackUriScheme + "://"))
            {
                return(false);
            }

            // Ensure we have a task waiting
            if (tcsAccount != null && !tcsAccount.Task.IsCompleted)
            {
                try
                {
                    // Parse the account from the url the app opened with
                    var account = AppleAccount.FromUrl(url);

                    // IMPORTANT: Validate the nonce returned is the same as our originating request!!
                    if (!account.IdToken.Nonce.Equals(currentNonce))
                    {
                        tcsAccount.TrySetException(new InvalidOperationException("Invalid or non-matching nonce returned"));
                    }

                    // Set our account result
                    tcsAccount.TrySetResult(account);
                }
                catch (Exception ex)
                {
                    tcsAccount.TrySetException(ex);
                }
            }

            tcsAccount.TrySetResult(null);
            return(false);
        }
Beispiel #4
0
        public async Task <AppleAccount> SignInAsync()
        {
            // Fallback to web for older iOS versions
            if (!Is13)
            {
                return(await webSignInService.SignInAsync());
            }

            AppleAccount appleAccount = default;

#if __IOS__13
            var provider = new ASAuthorizationAppleIdProvider();
            var req      = provider.CreateRequest();

            authManager = new AuthManager(UIApplication.SharedApplication.KeyWindow);

            req.RequestedScopes = new[] { ASAuthorizationScope.FullName, ASAuthorizationScope.Email };
            var controller = new ASAuthorizationController(new[] { req });

            controller.Delegate = authManager;
            controller.PresentationContextProvider = authManager;

            controller.PerformRequests();

            var creds = await authManager.Credentials;

            if (creds == null)
            {
                return(null);
            }

            appleAccount                = new AppleAccount();
            appleAccount.IdToken        = JwtToken.Decode(new NSString(creds.IdentityToken, NSStringEncoding.UTF8).ToString());
            appleAccount.Email          = creds.Email;
            appleAccount.UserId         = creds.User;
            appleAccount.Name           = NSPersonNameComponentsFormatter.GetLocalizedString(creds.FullName, NSPersonNameComponentsFormatterStyle.Default, NSPersonNameComponentsFormatterOptions.Phonetic);
            appleAccount.RealUserStatus = creds.RealUserStatus.ToString();
#endif

            return(appleAccount);
        }
        // This function evaluates direct user's userType based on role and whether or not
        // their profile was updated succesfully. (Overloading)

        //async Task<UserTypeEvaluation> EvaluateUserType(string role, string password)
        //{
        //    UserTypeEvaluation userType = new UserTypeEvaluation();

        //    try
        //    {
        //        if (role == "CUSTOMER" || role == "ADMIN")
        //        {
        //            userType.role = "CUSTOMER";
        //            userType.statusCode = true;
        //        }
        //        else if (role == "GUEST")
        //        {
        //            var didProfileUpdatedSucessfully = await UpdateUserProfile(password);

        //            if (didProfileUpdatedSucessfully)
        //            {
        //                userType.role = "CUSTOMER";
        //                userType.statusCode = true;
        //            }
        //            else
        //            {
        //                userType.role = "GUEST";
        //                userType.statusCode = false;
        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }

        //    return userType;

        //}

        // This function evaluates social media user's userType based on role and whether or not
        // their profile was updated succesfully. (Overloading)

        //async Task<UserTypeEvaluation> EvaluateUserType(string role, string mobile_access_token, string mobile_refresh_token, string social_id, string platform)
        //{
        //    UserTypeEvaluation userType = new UserTypeEvaluation();

        //    try
        //    {
        //        if (role == "CUSTOMER" || role == "ADMIN")
        //        {
        //            userType.role = "CUSTOMER";
        //            userType.statusCode = true;
        //        }
        //        else if (role == "GUEST")
        //        {
        //            var didProfileUpdatedSucessfully = await UpdateUserProfile(mobile_access_token, mobile_refresh_token, social_id, platform);

        //            if (didProfileUpdatedSucessfully)
        //            {
        //                userType.role = "CUSTOMER";
        //                userType.statusCode = true;
        //            }
        //            else
        //            {
        //                userType.role = "GUEST";
        //                userType.statusCode = false;
        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }

        //    return userType;

        //}

        // This function updates direct user's role from GUEST to CUSTOMER. (Overloading)

        //async Task<bool> UpdateUserProfile(string password)
        //{
        //    bool result = false;

        //    try
        //    {
        //        var clientSignUp = new SignUp();
        //        var content = clientSignUp.UpdateDirectUser(user, password);
        //        result = await SignUp.SignUpNewUser(content);
        //    }
        //    catch
        //    {
        //        Debug.Write("ERROR UPDATING DIRECT USER'S PROFILE FROM GUEST TO CUSTOMER");
        //    }

        //    return result;
        //}

        // This function updates social media user's role from GUEST to CUSTOMER. (Overloading)

        //async Task<bool> UpdateUserProfile(string mobile_access_token, string mobile_refresh_token, string social_id, string platform)
        //{
        //    bool result = false;

        //    try
        //    {
        //        var clientSignUp = new SignUp();
        //        var content = clientSignUp.UpdateSocialUser(user, mobile_access_token, mobile_refresh_token, social_id, platform);
        //        result = await SignUp.SignUpNewUser(content);
        //    }
        //    catch
        //    {
        //        Debug.Write("ERROR UPDATING SOCIAL MEDIA USER'S PROFILE FROM GUEST TO CUSTOMER");
        //    }

        //    return result;

        //}

        // EVALUATION FUNTIONS FOR DIRECT AND SOCIAL MEDIA ____________________

        // NOTIFICATION FUNCTION ______________________________________________

        // This function send GUID to database.

        //async Task<bool> SetUserRemoteNotification()
        //{
        //    bool result = false;

        //    try
        //    {
        //        deviceId = Preferences.Get("guid", null);

        //        if (deviceId != null)
        //        {
        //            var client = new HttpClient();
        //            NotificationPost notificationPost = new NotificationPost();

        //            notificationPost.uid = user.getUserID();
        //            notificationPost.guid = deviceId.Substring(5);
        //            user.setUserDeviceID(deviceId.Substring(5));
        //            notificationPost.notification = "TRUE";

        //            var notificationSerializedObject = JsonConvert.SerializeObject(notificationPost);
        //            var notificationContent = new StringContent(notificationSerializedObject, Encoding.UTF8, "application/json");
        //            var clientResponse = await client.PostAsync(Constant.NotificationsUrl, notificationContent);

        //            if (clientResponse.IsSuccessStatusCode)
        //            {
        //                result = true;
        //                Debug.WriteLine("GUID WAS WRITTEN SUCCESFULLY WERE SET SUCESSFULLY");
        //            }
        //            else
        //            {
        //                Debug.WriteLine("ERROR SETTING GUID FOR NOTIFICATIONS");
        //            }
        //        }
        //    }
        //    catch
        //    {

        //    }

        //    return result;
        //}

        // NOTIFICATION FUNCTION ______________________________________________

        // SOCIAL MEDIA VERIFICATION FUNCTION__________________________________

        // This function verifies if credentails exist and whether or not user is
        // authenticated by our system. (Overloading)

        public async Task <string> VerifyUserCredentials(string accessToken = "", string refreshToken = "", AuthenticatorCompletedEventArgs googleAccount = null, AppleAccount appleCredentials = null, string platform = "")
        {
            var isUserVerified = "";

            try
            {
                string _accessToken  = accessToken;
                string _refreshToken = refreshToken;

                var client          = new HttpClient();
                var socialLogInPost = new SocialLogInPost();

                var googleData   = new GoogleResponse();
                var facebookData = new FacebookResponse();

                if (platform == "GOOGLE")
                {
                    var request        = new OAuth2Request("GET", new Uri(Constant.GoogleUserInfoUrl), null, googleAccount.Account);
                    var GoogleResponse = await request.GetResponseAsync();

                    var googelUserData = GoogleResponse.GetResponseText();

                    googleData = JsonConvert.DeserializeObject <GoogleResponse>(googelUserData);

                    socialLogInPost.email     = googleData.email;
                    socialLogInPost.social_id = googleData.id;
                    //Debug.WriteLine("IMAGE: " + googleData.picture);
                    //user.setUserImage(googleData.picture);

                    _accessToken  = accessToken;
                    _refreshToken = refreshToken;
                }
                else if (platform == "FACEBOOK")
                {
                    var facebookResponse = client.GetStringAsync(Constant.FacebookUserInfoUrl + accessToken);
                    var facebookUserData = facebookResponse.Result;

                    Debug.WriteLine("FACEBOOK DATA: " + facebookUserData);
                    facebookData = JsonConvert.DeserializeObject <FacebookResponse>(facebookUserData);

                    socialLogInPost.email     = facebookData.email;
                    socialLogInPost.social_id = facebookData.id;

                    _accessToken  = accessToken;
                    _refreshToken = refreshToken;
                }
                else if (platform == "APPLE")
                {
                    socialLogInPost.email     = appleCredentials.Email;
                    socialLogInPost.social_id = appleCredentials.UserId;

                    _accessToken  = appleCredentials.Token;
                    _refreshToken = appleCredentials.Token;
                }

                socialLogInPost.password        = "";
                socialLogInPost.signup_platform = platform;

                var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost);
                var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json");

                var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent);

                var responseContent = await RDSResponse.Content.ReadAsStringAsync();

                var authetication = JsonConvert.DeserializeObject <RDSAuthentication>(responseContent);
                if (RDSResponse.IsSuccessStatusCode)
                {
                    if (responseContent != null)
                    {
                        if (authetication.code.ToString() == Constant.EmailNotFound)
                        {
                            // need to sign up
                            userToSignUp = new SignUpAccount();

                            if (platform == "GOOGLE")
                            {
                                userToSignUp.socialID     = googleData.id;
                                userToSignUp.email        = googleData.email;
                                userToSignUp.firstName    = googleData.given_name;
                                userToSignUp.lastName     = googleData.family_name;
                                userToSignUp.accessToken  = _accessToken;
                                userToSignUp.refreshToken = _refreshToken;
                                userToSignUp.platform     = platform;
                            }
                            else if (platform == "FACEBOOK")
                            {
                                userToSignUp.socialID     = facebookData.id;
                                userToSignUp.email        = facebookData.email;
                                userToSignUp.firstName    = facebookData.name;
                                userToSignUp.accessToken  = _accessToken;
                                userToSignUp.refreshToken = _refreshToken;
                                userToSignUp.platform     = platform;
                            }
                            else if (platform == "APPLE")
                            {
                                userToSignUp.socialID     = appleCredentials.UserId;
                                userToSignUp.email        = appleCredentials.Email;
                                userToSignUp.firstName    = appleCredentials.Name;
                                userToSignUp.accessToken  = _accessToken;
                                userToSignUp.refreshToken = _refreshToken;
                                userToSignUp.platform     = platform;
                            }

                            isUserVerified = "USER NEEDS TO SIGN UP";
                        }
                        if (authetication.code.ToString() == Constant.AutheticatedSuccesful)
                        {
                            try
                            {
                                DateTime today   = DateTime.Now;
                                DateTime expDate = today.AddDays(Constant.days);

                                user             = new User();
                                user.id          = authetication.result[0].driver_uid;
                                user.sessionTime = expDate;
                                user.platform    = platform;
                                user.email       = "";
                                user.socialId    = "";
                                user.route_id    = "";

                                var statusUpdatingTokens = await UpdateAccessRefreshToken(user.id, accessToken, refreshToken);

                                isUserVerified = EvaluteUserUpdates(statusUpdatingTokens);

                                SaveUser(user);
                            }
                            catch (Exception second)
                            {
                                Debug.WriteLine(second.Message);
                            }
                        }
                        if (authetication.code.ToString() == Constant.ErrorPlatform)
                        {
                            //var RDSCode = JsonConvert.DeserializeObject<RDSLogInMessage>(responseContent);

                            isUserVerified = "WRONG SOCIAL MEDIA TO SIGN IN";
                        }

                        if (authetication.code.ToString() == Constant.ErrorUserDirectLogIn)
                        {
                            isUserVerified = "SIGN IN DIRECTLY";
                        }
                    }
                }
            }
            catch (Exception errorVerifyUserCredentials)
            {
                //var client = new Diagnostic();
                //client.parseException(errorVerifyUserCredentials.ToString(), user);

                Debug.WriteLine("ERROR IN 'errorVerifyUserCredentials' FUNCTION");

                isUserVerified = "ERROR";
            }

            return(isUserVerified);
        }
Beispiel #6
0
        public async Task <string> UserVerification(AuthenticatorCompletedEventArgs user = null, AppleAccount appleCredentials = null, string platform = "")
        {
            string result = "";

            try
            {
                var client          = new HttpClient();
                var socialLogInPost = new SocialLogInPost();
                var googleData      = new GoogleResponse();
                var facebookData    = new FacebookResponse();
                var localTimeZone   = TimeZoneInfo.Local;
                var _accessToken    = "";
                var _refreshToken   = "";
                socialLogInPost.time_zone = localTimeZone.Id;

                if (platform == "GOOGLE")
                {
                    var request        = new OAuth2Request("GET", new Uri(AppConstants.GoogleUserInfoUrl), null, user.Account);
                    var GoogleResponse = await request.GetResponseAsync();

                    var googelUserData = GoogleResponse.GetResponseText();

                    googleData = JsonConvert.DeserializeObject <GoogleResponse>(googelUserData);

                    socialLogInPost.email                = googleData.email;
                    socialLogInPost.social_id            = googleData.id;
                    socialLogInPost.mobile_access_token  = user.Account.Properties["access_token"];
                    socialLogInPost.mobile_refresh_token = user.Account.Properties["refresh_token"];
                    socialLogInPost.user_first_name      = googleData.given_name;
                    socialLogInPost.user_last_name       = googleData.family_name;
                }
                else if (platform == "FACEBOOK")
                {
                    var facebookResponse = client.GetStringAsync(AppConstants.FacebookUserInfoUrl + user.Account.Properties["access_token"]);
                    var facebookUserData = facebookResponse.Result;

                    facebookData = JsonConvert.DeserializeObject <FacebookResponse>(facebookUserData);

                    socialLogInPost.email                = facebookData.email;
                    socialLogInPost.social_id            = facebookData.id;
                    socialLogInPost.mobile_access_token  = user.Account.Properties["access_token"];
                    socialLogInPost.mobile_refresh_token = user.Account.Properties["access_token"];
                    socialLogInPost.user_first_name      = facebookData.name;
                    socialLogInPost.user_last_name       = "";
                }
                else if (platform == "APPLE")
                {
                    socialLogInPost.email                = appleCredentials.Email;
                    socialLogInPost.social_id            = appleCredentials.UserId;
                    socialLogInPost.mobile_access_token  = appleCredentials.Token;
                    socialLogInPost.mobile_refresh_token = appleCredentials.Token;
                    socialLogInPost.user_first_name      = appleCredentials.Name == null ? "" : appleCredentials.Name;
                    socialLogInPost.user_last_name       = "";
                }


                socialLogInPost.signup_platform = platform;

                _accessToken  = socialLogInPost.mobile_access_token;
                _refreshToken = socialLogInPost.mobile_refresh_token;

                var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost);
                var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json");

                var RDSResponse = await client.PostAsync(AppConstants.BaseUrl + AppConstants.login, postContent);

                //var RDSResponse = await client.PostAsync(AppConstants.BaseUrl + AppConstants.UserIdFromEmailUrl, postContent);

                var responseContent = await RDSResponse.Content.ReadAsStringAsync();

                Debug.WriteLine(responseContent);
                var authetication = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent);
                var session       = JsonConvert.DeserializeObject <Session>(responseContent);
                if (RDSResponse.IsSuccessStatusCode)
                {
                    if (responseContent != null)
                    {
                        if (authetication.code.ToString() == AppConstants.EmailNotFound)
                        {
                            // Missing a Oops message you don't have an account
                            //Application.Current.MainPage = new LogInPage();
                            result = "EMAIL WAS NOT FOUND";
                            return(result);
                        }
                        if (authetication.code.ToString() == AppConstants.AutheticatedSuccesful)
                        {
                            Debug.WriteLine("USER AUTHENTICATED");
                            DateTime today   = DateTime.Now;
                            DateTime expDate = today.AddDays(AppConstants.days);

                            MainPage.account               = SetAccount();
                            MainPage.account.userID        = session.result[0].user_unique_id;
                            MainPage.account.sessionTime   = expDate;
                            MainPage.account.accessToken   = _accessToken;
                            MainPage.account.refreshToken  = _refreshToken;
                            MainPage.account.platform      = platform;
                            MainPage.account.isGoalsActive = true;

                            if (platform == "GOOGLE")
                            {
                                MainPage.account.isCalendarActive = true;
                            }

                            var notificationStatus = await SetUserRemoteNotification(MainPage.account.userID);

                            if (notificationStatus)
                            {
                                result = "USER SIGNED IN SUCCESSFULLY AND DEVICE ID WAS REGISTERED SUCCESSFULLY";
                            }
                            else
                            {
                                result = "USER SIGNED IN SUCCESSFULLY AND DEVICE ID WAS NOT REGISTERED SUCCESSFULLY";
                            }

                            SaveUser(MainPage.account);
                        }
                        if (authetication.code.ToString() == AppConstants.ErrorPlatform)
                        {
                            result = "SIGN IN WITH THE CORRECT VIA SOCIAL MEDIA ACCOUNT";
                        }
                    }
                }

                return(result);
            }
            catch (Exception UserVerificationIssue)
            {
                Debug.WriteLine("ERROR IN 'UserVerification' FUNCTION: " + UserVerificationIssue.Message);
                result = "SOMETHING FAILED IN THE USER VERIFICATION METHOD";
            }

            return(result);
        }