コード例 #1
0
        public async void AppleUserProfileAsync(string appleToken, string appleUserEmail, string userName)
        {
            var client          = new HttpClient();
            var socialLogInPost = new SocialLogInPost();

            socialLogInPost.email           = appleUserEmail;
            socialLogInPost.password        = "";
            socialLogInPost.token           = appleToken;
            socialLogInPost.signup_platform = "APPLE";

            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();

            System.Diagnostics.Debug.WriteLine(responseContent);
            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    if (responseContent.Contains(Constant.EmailNotFound))
                    {
                        Application.Current.MainPage = new SocialLogInSignUp(userName, "", appleUserEmail, appleToken, appleToken, "APPLE");
                    }
                    if (responseContent.Contains(Constant.AutheticatedSuccesful))
                    {
                        Application.Current.MainPage = new HomePage();
                    }
                }
            }
        }
コード例 #2
0
        public async void OnAppleSignInRequest()
        {
            var account = await appleSignInService.SignInAsync();

            if (account != null)
            {
                Preferences.Set(App.LoggedInKey, true);
                await SecureStorage.SetAsync(App.AppleUserIdKey, account.UserId);

                // System.Diagnostics.Debug.WriteLine($"Signed in!\n  Name: {account?.Name ?? string.Empty}\n  Email: {account?.Email ?? string.Empty}\n  UserId: {account?.UserId ?? string.Empty}");

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

                if (apple_token == null && apple_email == null)
                {
                    apple_token = account.Token.Substring(0, 500);
                    apple_email = account.Email;
                    AppleUserProfileAsync(apple_token, apple_email, account.Name);
                }

                if (!apple_token.Equals(account.Token) && apple_token != null)
                {
                    DateTime today          = DateTime.Now;
                    DateTime expirationDate = today.AddDays(Constant.days);
                    Application.Current.Properties["time_stamp"] = expirationDate;

                    apple_token = account.Token.Substring(0, 500);

                    UpdateTokensPost updateTokens = new UpdateTokensPost();
                    updateTokens.access_token     = apple_token;
                    updateTokens.refresh_token    = apple_token;
                    updateTokens.uid              = (string)Application.Current.Properties["uid"];
                    updateTokens.social_timestamp = expirationDate.ToString("yyyy-MM-dd HH:mm:ss");

                    var updatePostSerilizedObject = JsonConvert.SerializeObject(updateTokens);
                    var updatePostContent         = new StringContent(updatePostSerilizedObject, Encoding.UTF8, "application/json");
                    var RDSrespose = await client.PostAsync(Constant.UpdateTokensUrl, updatePostContent);

                    if (RDSrespose.IsSuccessStatusCode)
                    {
                        AppleUserProfileAsync(apple_token, apple_email, string.Empty);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("We were not able to update your APPLE token");
                    }
                }
            }
            else
            {
                AppleError?.Invoke(this, default(EventArgs));
            }
        }
コード例 #3
0
ファイル: LogIn.xaml.cs プロジェクト: infinite-options/login
        public async void FacebookUserProfileAsync(string accessToken)
        {
            // MECHANISM:

            // 1. RETRIVE TOKEN FROM SOCIAL LOGIN
            // 2. PASS THIS INFORMATION TO PARVA
            // 3. WAIT FOR A RESPONSE
            // 4. BASED ON THE RESPONSE I WOULD NEED TO REDIRECT THE USER TO THE CORRECT PAGE

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

            var facebookResponse = client.GetStringAsync(Constant.FacebookUserInfoUrl + accessToken);
            var userData         = facebookResponse.Result;

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

            socialLogInPost.email           = facebookData.email;
            socialLogInPost.password        = "";
            socialLogInPost.token           = accessToken;
            socialLogInPost.signup_platform = "FACEBOOK";

            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();

            System.Diagnostics.Debug.WriteLine(responseContent);
            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    if (responseContent.Contains(Constant.EmailNotFound))
                    {
                        Application.Current.MainPage = new SocialLogInSignUp(facebookData.name, "", facebookData.email, accessToken, accessToken, "FACEBOOK");
                    }
                    if (responseContent.Contains(Constant.AutheticatedSuccesful))
                    {
                        Application.Current.MainPage = new HomePage();
                    }
                }
            }
        }
コード例 #4
0
ファイル: LogIn.xaml.cs プロジェクト: infinite-options/login
        public async void GoogleUserProfileAsync(string accessToken, string refreshToken, AuthenticatorCompletedEventArgs e)
        {
            var client          = new HttpClient();
            var socialLogInPost = new SocialLogInPost();

            var request        = new OAuth2Request("GET", new Uri(Constant.GoogleUserInfoUrl), null, e.Account);
            var GoogleResponse = await request.GetResponseAsync();

            var userData = GoogleResponse.GetResponseText();

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

            socialLogInPost.email           = googleData.email;
            socialLogInPost.password        = "";
            socialLogInPost.token           = refreshToken;
            socialLogInPost.signup_platform = "GOOGLE";

            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();

            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    if (responseContent.Contains(Constant.EmailNotFound))
                    {
                        Application.Current.MainPage = new SocialLogInSignUp(googleData.given_name, googleData.family_name, googleData.email, accessToken, refreshToken, "GOOGLE");
                    }
                    if (responseContent.Contains(Constant.AutheticatedSuccesful))
                    {
                        Application.Current.MainPage = new HomePage();
                    }
                }
            }
        }
コード例 #5
0
        public async void AppleUserProfileAsync(string appleId, string appleToken, string appleUserEmail, string userName)
        {
            System.Diagnostics.Debug.WriteLine("LINE 95");
            var client          = new HttpClient();
            var socialLogInPost = new SocialLogInPost();

            socialLogInPost.email           = appleUserEmail;
            socialLogInPost.password        = "";
            socialLogInPost.social_id       = appleId;
            socialLogInPost.signup_platform = "APPLE";

            var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost);

            System.Diagnostics.Debug.WriteLine(socialLogInPostSerialized);

            var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json");
            var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent);

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

            System.Diagnostics.Debug.WriteLine(responseContent);

            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    if (responseContent.Contains(Constant.EmailNotFound))
                    {
                        var signUp = await Application.Current.MainPage.DisplayAlert("Message", "It looks like you don't have a MTYD account. Please sign up!", "OK", "Cancel");

                        if (signUp)
                        {
                            // HERE YOU NEED TO SUBSTITUTE MY SOCIAL SIGN UP PAGE WITH MTYD SOCIAL SIGN UP
                            // NOTE THAT THIS SOCIAL SIGN UP PAGE NEEDS A CONSTRUCTOR LIKE THE FOLLOWING ONE
                            // SocialSignUp(string socialId, string firstName, string lastName, string emailAddress, string accessToken, string refreshToken, string platform)
                            Application.Current.MainPage = new CarlosSocialSignUp(appleId, userName, "", appleUserEmail, appleToken, appleToken, "APPLE");
                        }
                    }
                    if (responseContent.Contains(Constant.AutheticatedSuccesful))
                    {
                        var data = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent);
                        Application.Current.Properties["user_id"] = data.result[0].customer_uid;

                        UpdateTokensPost updateTokesPost = new UpdateTokensPost();
                        updateTokesPost.uid = data.result[0].customer_uid;
                        updateTokesPost.mobile_access_token  = appleToken;
                        updateTokesPost.mobile_refresh_token = appleToken;

                        var updateTokesPostSerializedObject = JsonConvert.SerializeObject(updateTokesPost);
                        var updateTokesContent  = new StringContent(updateTokesPostSerializedObject, Encoding.UTF8, "application/json");
                        var updateTokesResponse = await client.PostAsync(Constant.UpdateTokensUrl, updateTokesContent);

                        var updateTokenResponseContent = await updateTokesResponse.Content.ReadAsStringAsync();

                        System.Diagnostics.Debug.WriteLine(updateTokenResponseContent);

                        if (updateTokesResponse.IsSuccessStatusCode)
                        {
                            DateTime today   = DateTime.Now;
                            DateTime expDate = today.AddDays(Constant.days);

                            Application.Current.Properties["time_stamp"] = expDate;
                            Application.Current.Properties["platform"]   = "APPLE";
                            // Application.Current.MainPage = new SubscriptionPage();
                            Application.Current.MainPage = new NavigationPage(new SubscriptionPage());

                            // THIS IS HOW YOU CAN ACCESS YOUR USER ID FROM THE APP
                            // string userID = (string)Application.Current.Properties["user_id"];
                        }
                        else
                        {
                            await Application.Current.MainPage.DisplayAlert("Oops", "We are facing some problems with our internal system. We weren't able to update your credentials", "OK");
                        }
                    }
                    if (responseContent.Contains(Constant.ErrorPlatform))
                    {
                        var RDSCode = JsonConvert.DeserializeObject <RDSLogInMessage>(responseContent);
                        await Application.Current.MainPage.DisplayAlert("Message", RDSCode.message, "OK");
                    }

                    if (responseContent.Contains(Constant.ErrorUserDirectLogIn))
                    {
                        await Application.Current.MainPage.DisplayAlert("Oops!", "You have an existing MTYD account. Please use direct login", "OK");
                    }
                }
            }
        }
コード例 #6
0
        public async void AppleUserProfileAsync(string appleId, string appleToken, string appleUserEmail, string userName)
        {
            System.Diagnostics.Debug.WriteLine("LINE 95");
            var client          = new HttpClient();
            var socialLogInPost = new SocialLogInPost();

            socialLogInPost.email           = appleUserEmail;
            socialLogInPost.password        = "";
            socialLogInPost.social_id       = appleId;
            socialLogInPost.signup_platform = "APPLE";

            var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost);

            System.Diagnostics.Debug.WriteLine(socialLogInPostSerialized);

            var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json");
            var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent);

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

            System.Diagnostics.Debug.WriteLine(responseContent);

            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    var data5 = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent);
                    if (data5.code.ToString() == Constant.EmailNotFound)
                    {
                        var signUp = await Application.Current.MainPage.DisplayAlert("Message", "It looks like you don't have a MTYD account. Please sign up!", "OK", "Cancel");

                        if (signUp)
                        {
                            // HERE YOU NEED TO SUBSTITUTE MY SOCIAL SIGN UP PAGE WITH MTYD SOCIAL SIGN UP
                            // NOTE THAT THIS SOCIAL SIGN UP PAGE NEEDS A CONSTRUCTOR LIKE THE FOLLOWING ONE
                            // SocialSignUp(string socialId, string firstName, string lastName, string emailAddress, string accessToken, string refreshToken, string platform)
                            Preferences.Set("canChooseSelect", false);
                            Application.Current.MainPage = new CarlosSocialSignUp(appleId, userName, "", appleUserEmail, appleToken, appleToken, "APPLE");
                        }
                    }
                    else if (data5.code.ToString() == Constant.AutheticatedSuccesful)
                    {
                        var data = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent);
                        Application.Current.Properties["user_id"] = data.result[0].customer_uid;

                        UpdateTokensPost updateTokesPost = new UpdateTokensPost();
                        updateTokesPost.uid = data.result[0].customer_uid;
                        updateTokesPost.mobile_access_token  = appleToken;
                        updateTokesPost.mobile_refresh_token = appleToken;

                        var updateTokesPostSerializedObject = JsonConvert.SerializeObject(updateTokesPost);
                        Console.WriteLine("updateTokesPostSerializedObject: " + updateTokesPostSerializedObject.ToString());
                        var updateTokesContent = new StringContent(updateTokesPostSerializedObject, Encoding.UTF8, "application/json");
                        Console.WriteLine("updateTokesContent: " + updateTokesContent.ToString());
                        var updateTokesResponse = await client.PostAsync(Constant.UpdateTokensUrl, updateTokesContent);

                        Console.WriteLine("updateTokesResponse: " + updateTokesResponse.ToString());
                        var updateTokenResponseContent = await updateTokesResponse.Content.ReadAsStringAsync();

                        Console.WriteLine("updateTokenResponseContent: " + updateTokenResponseContent.ToString());
                        System.Diagnostics.Debug.WriteLine(updateTokenResponseContent);

                        if (updateTokesResponse.IsSuccessStatusCode)
                        {
                            DateTime today   = DateTime.Now;
                            DateTime expDate = today.AddDays(Constant.days);

                            Application.Current.Properties["time_stamp"] = expDate;
                            Application.Current.Properties["platform"]   = "APPLE";

                            var request = new HttpRequestMessage();
                            Console.WriteLine("user_id: " + (string)Application.Current.Properties["user_id"]);
                            string url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/customer_lplp?customer_uid=" + (string)Application.Current.Properties["user_id"];
                            //string url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/meals_selected?customer_uid=" + (string)Application.Current.Properties["user_id"];
                            //string url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/meals_selected?customer_uid=" + "100-000256";
                            Console.WriteLine("url: " + url);
                            request.RequestUri = new Uri(url);
                            //request.RequestUri = new Uri("https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/get_delivery_info/400-000453");
                            request.Method = HttpMethod.Get;
                            var client2 = new HttpClient();
                            HttpResponseMessage response = await client2.SendAsync(request);

                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                HttpContent content = response.Content;
                                Console.WriteLine("content: " + content);
                                var userString = await content.ReadAsStringAsync();

                                Console.WriteLine(userString);

                                //writing guid to db
                                if (Preferences.Get("setGuid" + (string)Application.Current.Properties["user_id"], false) == false)
                                {
                                    if (Device.RuntimePlatform == Device.iOS)
                                    {
                                        deviceId = Preferences.Get("guid", null);
                                        if (deviceId != null)
                                        {
                                            Debug.WriteLine("This is the iOS GUID from Log in: " + deviceId);
                                        }
                                    }
                                    else
                                    {
                                        deviceId = Preferences.Get("guid", null);
                                        if (deviceId != null)
                                        {
                                            Debug.WriteLine("This is the Android GUID from Log in " + deviceId);
                                        }
                                    }

                                    if (deviceId != null)
                                    {
                                        GuidPost notificationPost = new GuidPost();

                                        notificationPost.uid  = (string)Application.Current.Properties["user_id"];
                                        notificationPost.guid = deviceId.Substring(5);
                                        Application.Current.Properties["guid"] = deviceId.Substring(5);
                                        notificationPost.notification          = "TRUE";

                                        var notificationSerializedObject = JsonConvert.SerializeObject(notificationPost);
                                        Debug.WriteLine("Notification JSON Object to send: " + notificationSerializedObject);

                                        var notificationContent = new StringContent(notificationSerializedObject, Encoding.UTF8, "application/json");

                                        var clientResponse = await client.PostAsync(Constant.GuidUrl, notificationContent);

                                        Debug.WriteLine("Status code: " + clientResponse.IsSuccessStatusCode);

                                        if (clientResponse.IsSuccessStatusCode)
                                        {
                                            System.Diagnostics.Debug.WriteLine("We have post the guid to the database");
                                            Preferences.Set("setGuid" + (string)Application.Current.Properties["user_id"], true);
                                        }
                                        else
                                        {
                                            Debug.WriteLine("Something went wrong. We are not able to send you notification at this moment");
                                        }
                                    }
                                }
                                //written

                                if (userString.ToString()[0] != '{')
                                {
                                    url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/Profile/" + (string)Application.Current.Properties["user_id"];
                                    var request3 = new HttpRequestMessage();
                                    request3.RequestUri = new Uri(url);
                                    request3.Method     = HttpMethod.Get;
                                    HttpResponseMessage response2 = await client.SendAsync(request3);

                                    content = response2.Content;
                                    Console.WriteLine("content: " + content);
                                    userString = await content.ReadAsStringAsync();

                                    JObject info_obj3 = JObject.Parse(userString);
                                    this.NewMainPage.Clear();
                                    Preferences.Set("user_latitude", (info_obj3["result"])[0]["customer_lat"].ToString());
                                    Debug.WriteLine("user latitude" + Preferences.Get("user_latitude", ""));
                                    Preferences.Set("user_longitude", (info_obj3["result"])[0]["customer_long"].ToString());
                                    Debug.WriteLine("user longitude" + Preferences.Get("user_longitude", ""));

                                    Preferences.Set("profilePicLink", "");

                                    Console.WriteLine("go to SubscriptionPage");
                                    Preferences.Set("canChooseSelect", false);

                                    Application.Current.MainPage = new NavigationPage(new SubscriptionPage((info_obj3["result"])[0]["customer_first_name"].ToString(), (info_obj3["result"])[0]["customer_last_name"].ToString(), (info_obj3["result"])[0]["customer_email"].ToString()));
                                    return;
                                }

                                JObject info_obj2 = JObject.Parse(userString);
                                this.NewLogin.Clear();

                                //ArrayList item_price = new ArrayList();
                                //ArrayList num_items = new ArrayList();
                                //ArrayList payment_frequency = new ArrayList();
                                //ArrayList groupArray = new ArrayList();

                                //int counter = 0;
                                //while (((info_obj2["result"])[0]).ToString() != "{}")
                                //{
                                //    Console.WriteLine("worked" + counter);
                                //    counter++;
                                //}

                                Console.WriteLine("string: " + (info_obj2["result"]).ToString());
                                //check if the user hasn't entered any info before, if so put in the placeholders
                                if ((info_obj2["result"]).ToString() == "[]" || (info_obj2["result"]).ToString() == "204" || (info_obj2["result"]).ToString().Contains("ACTIVE") == false)
                                {
                                    url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/Profile/" + (string)Application.Current.Properties["user_id"];
                                    var request3 = new HttpRequestMessage();
                                    request3.RequestUri = new Uri(url);
                                    request3.Method     = HttpMethod.Get;
                                    response            = await client.SendAsync(request3);

                                    content = response.Content;
                                    Console.WriteLine("content: " + content);
                                    userString = await content.ReadAsStringAsync();

                                    JObject info_obj3 = JObject.Parse(userString);
                                    this.NewMainPage.Clear();
                                    Preferences.Set("user_latitude", (info_obj3["result"])[0]["customer_lat"].ToString());
                                    Debug.WriteLine("user latitude" + Preferences.Get("user_latitude", ""));
                                    Preferences.Set("user_longitude", (info_obj3["result"])[0]["customer_long"].ToString());
                                    Debug.WriteLine("user longitude" + Preferences.Get("user_longitude", ""));

                                    Preferences.Set("profilePicLink", "");

                                    Console.WriteLine("go to SubscriptionPage");
                                    Preferences.Set("canChooseSelect", false);
                                    Application.Current.MainPage = new NavigationPage(new SubscriptionPage((info_obj2["result"])[0]["customer_first_name"].ToString(), (info_obj2["result"])[0]["customer_last_name"].ToString(), (info_obj2["result"])[0]["customer_email"].ToString()));
                                }
                                else
                                {
                                    url = "https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/Profile/" + (string)Application.Current.Properties["user_id"];
                                    var request3 = new HttpRequestMessage();
                                    request3.RequestUri = new Uri(url);
                                    request3.Method     = HttpMethod.Get;
                                    response            = await client.SendAsync(request3);

                                    content = response.Content;
                                    Console.WriteLine("content: " + content);
                                    userString = await content.ReadAsStringAsync();

                                    JObject info_obj3 = JObject.Parse(userString);
                                    this.NewMainPage.Clear();
                                    Preferences.Set("user_latitude", (info_obj3["result"])[0]["customer_lat"].ToString());
                                    Debug.WriteLine("user latitude" + Preferences.Get("user_latitude", ""));
                                    Preferences.Set("user_longitude", (info_obj3["result"])[0]["customer_long"].ToString());
                                    Debug.WriteLine("user longitude" + Preferences.Get("user_longitude", ""));

                                    Preferences.Set("profilePicLink", "");
                                    Preferences.Set("canChooseSelect", true);
                                    Zones[] zones = new Zones[] { };
                                    Application.Current.MainPage = new NavigationPage(new Select(zones, (info_obj2["result"])[0]["customer_first_name"].ToString(), (info_obj2["result"])[0]["customer_last_name"].ToString(), (info_obj2["result"])[0]["customer_email"].ToString()));
                                }
                            }

                            // Application.Current.MainPage = new SubscriptionPage();
                            //Application.Current.MainPage = new NavigationPage(new SubscriptionPage());

                            // THIS IS HOW YOU CAN ACCESS YOUR USER ID FROM THE APP
                            // string userID = (string)Application.Current.Properties["user_id"];
                        }
                        else
                        {
                            await Application.Current.MainPage.DisplayAlert("Oops", "We are facing some problems with our internal system. We weren't able to update your credentials", "OK");
                        }
                    }
                    else if (data5.code.ToString() == Constant.ErrorPlatform)
                    {
                        var RDSCode = JsonConvert.DeserializeObject <RDSLogInMessage>(responseContent);
                        await Application.Current.MainPage.DisplayAlert("Message", RDSCode.message, "OK");
                    }

                    else if (data5.code.ToString() == Constant.ErrorUserDirectLogIn)
                    {
                        await Application.Current.MainPage.DisplayAlert("Oops!", "You have an existing MTYD account. Please use direct login", "OK");
                    }
                }
            }
        }
コード例 #7
0
        public async void FacebookUserProfileAsync(string accessToken)
        {
            var client          = new HttpClient();
            var socialLogInPost = new SocialLogInPost();

            // Actual call to Facebooks end point now that we have the token (appending accessToken to URL in constants file)
            var facebookResponse = client.GetStringAsync(Constant.FacebookUserInfoUrl + accessToken); // makes the call to Facebook and returns True/False
            var userData         = facebookResponse.Result;                                           // returns Facebook email and social ID

            System.Diagnostics.Debug.WriteLine(facebookResponse);
            System.Diagnostics.Debug.WriteLine(userData);


            // Deserializes JSON object from info provided by Facebook
            FacebookResponse facebookData = JsonConvert.DeserializeObject <FacebookResponse>(userData);

            socialLogInPost.email           = facebookData.email;
            socialLogInPost.password        = "";
            socialLogInPost.social_id       = facebookData.id;
            socialLogInPost.signup_platform = "FACEBOOK";

            // Create JSON object for Login Endpoint
            var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost);
            var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json");

            System.Diagnostics.Debug.WriteLine(socialLogInPostSerialized);

            // Call to RDS database with endpoint and JSON data
            var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent); //  True or False if Parva's endpoint ran preperly.

            var responseContent = await RDSResponse.Content.ReadAsStringAsync();      // Contains Parva's code containing all the user data including userid

            System.Diagnostics.Debug.WriteLine(RDSResponse.IsSuccessStatusCode);      // Response code is Yes/True if successful from httpclient system.net package
            System.Diagnostics.Debug.WriteLine(responseContent);                      // Response JSON that RDS returns

            if (RDSResponse.IsSuccessStatusCode)
            {
                if (responseContent != null)
                {
                    // Do I don't have the email in RDS
                    if (responseContent.Contains(Constant.EmailNotFound))
                    {
                        var signUp = await DisplayAlert("Message", "It looks like you don't have a MTYD account. Please sign up!", "OK", "Cancel");

                        if (signUp)
                        {
                            // HERE YOU NEED TO SUBSTITUTE MY SOCIAL SIGN UP PAGE WITH MTYD SOCIAL SIGN UP
                            // NOTE THAT THIS SOCIAL SIGN UP PAGE NEEDS A CONSTRUCTOR LIKE THE FOLLOWING ONE
                            // SocialSignUp(string socialId, string firstName, string lastName, string emailAddress, string accessToken, string refreshToken, string platform)
                            Application.Current.MainPage = new CarlosSocialSignUp(facebookData.id, facebookData.name, "", facebookData.email, accessToken, accessToken, "FACEBOOK");
                            // need to write new statment here ...
                        }
                    }


                    // if Response content contains 200
                    if (responseContent.Contains(Constant.AutheticatedSuccesful))
                    {
                        var data = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent);
                        Application.Current.Properties["user_id"] = data.result[0].customer_uid;  // converts RDS data into appication data.

                        UpdateTokensPost updateTokensPost = new UpdateTokensPost();
                        updateTokensPost.uid = data.result[0].customer_uid;
                        updateTokensPost.mobile_access_token  = accessToken;
                        updateTokensPost.mobile_refresh_token = accessToken;  // only get access token from Facebook so we store the data again

                        var updateTokensPostSerializedObject = JsonConvert.SerializeObject(updateTokensPost);
                        var updateTokensContent  = new StringContent(updateTokensPostSerializedObject, Encoding.UTF8, "application/json");
                        var updateTokensResponse = await client.PostAsync(Constant.UpdateTokensUrl, updateTokensContent);  // This calls the database and returns True or False

                        var updateTokenResponseContent = await updateTokensResponse.Content.ReadAsStringAsync();

                        System.Diagnostics.Debug.WriteLine(updateTokenResponseContent);

                        if (updateTokensResponse.IsSuccessStatusCode)
                        {
                            DateTime today   = DateTime.Now;
                            DateTime expDate = today.AddDays(Constant.days);  // Internal assignment - not from the database

                            Application.Current.Properties["time_stamp"] = expDate;
                            Application.Current.Properties["platform"]   = "FACEBOOK";
                            // Application.Current.MainPage = new SubscriptionPage();
                            Application.Current.MainPage = new NavigationPage(new SubscriptionPage());

                            // THIS IS HOW YOU CAN ACCESS YOUR USER ID FROM THE APP
                            //string userID = (string)Application.Current.Properties["user_id"];
                            //printing id for testing
                            //System.Diagnostics.Debug.WriteLine("user ID after success: " + userID);
                        }
                        else
                        {
                            await DisplayAlert("Oops", "We are facing some problems with our internal system. We weren't able to update your credentials", "OK");
                        }
                    }

                    // Wrong Platform message
                    if (responseContent.Contains(Constant.ErrorPlatform))
                    {
                        var RDSCode = JsonConvert.DeserializeObject <RDSLogInMessage>(responseContent);
                        await DisplayAlert("Message", RDSCode.message, "OK");
                    }


                    // Wrong LOGIN method message
                    if (responseContent.Contains(Constant.ErrorUserDirectLogIn))
                    {
                        await DisplayAlert("Oops!", "You have an existing MTYD account. Please use direct login", "OK");
                    }
                }
            }
        }
コード例 #8
0
        // 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);
        }
コード例 #9
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);
        }