Ejemplo n.º 1
0
        async partial void SignInButton_TouchUpInside(UIButton sender)
        {
            string userEmail    = userEmailTextField.Text;
            string userPassword = userPasswordTextField.Text;

            // If email or password do not meet requirements
            if (!Validation.ValidationResult(userEmail, "email") || !Validation.ValidationResult(userPassword, "password"))
            {
                DisplayAlertMessage(Validation.Message);
                return;
            }

            // Show the loading overlay on the UI
            LoadingOverlay.ShowOverlay(View);

            // Create instance of table Users
            var user = new UsersModel()
            {
                Email    = userEmail.ToLower(),
                Password = userPassword
            };

            // Call REST service to send Json data
            RestService rs = new RestService();

            // Get Json data from server in JsonResponseModel format
            Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "login");

            // If there was an error in PostJsonDataAsync class, display message
            if (jsonResponeTask == null)
            {
                LoadingOverlay.RemoveOverlay();
                DisplayAlertMessage(rs.Message);
                return;
            }

            // Get user id from Json after login or display an error
            // Create instance of JsonResponseModel and pass jsonResponeTask there
            var jsonResponse = await jsonResponeTask;

            // Get user id from Json after login or display an error
            if (jsonResponse.Status == "Error")
            {
                LoadingOverlay.RemoveOverlay();
                DisplayAlertMessage(jsonResponse.Message);
            }
            else if (!string.IsNullOrEmpty(jsonResponse.Id))
            {
                LoginIsSuccessful(jsonResponse);
            }
        }
        async partial void SignUpButton_TouchUpInside(UIButton sender)
        {
            string userPassword       = userPasswordTextField.Text;
            string userRepeatPassword = userRepeatPasswordTextField.Text;

            // Check for empty fields
            if (string.IsNullOrWhiteSpace(userPassword) || string.IsNullOrWhiteSpace(userRepeatPassword))
            {
                // Display an alert message
                DisplayAlertMessage("All fields are required to fill in");
                return;
            }
            // If password do not meet requirements
            else if (!Validation.ValidationResult(userPassword, "password"))
            {
                DisplayAlertMessage(Validation.Message);
                return;
            }

            // Check if passwords match
            if (!userPassword.Equals(userRepeatPassword))
            {
                // Display an alert message
                DisplayAlertMessage("Passwords do not match");
                return;
            }

            // Show the loading overlay on the UI
            LoadingOverlay.ShowOverlay(View);

            // Add user
            // Create instance of table Users
            user = new UsersModel()
            {
                FirstName     = RegisterUserSharedData.UserFirstName,
                LastName      = RegisterUserSharedData.UserLastName,
                Email         = RegisterUserSharedData.UserEmail.ToLower(),
                Password      = userPassword,
                LoginProvider = "Email"
            };

            // Call REST service to send Json data
            RestService rs = new RestService();

            // Get Json data from server in JsonResponseModel format
            Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "register");

            // If there was an error in PostJsonDataAsync class, display message
            if (jsonResponeTask == null)
            {
                DisplayAlertMessage(rs.Message);
                return;
            }

            // Create instance of JsonResponseModel and pass jsonResponeTask there
            var jsonResponse = await jsonResponeTask;

            // Get user status (Success/Error)
            string statusUser   = jsonResponse.Status;
            string alertMessage = jsonResponse.Message;

            // Excecutes the given code in the background
            var alert    = UIAlertController.Create(title: "", message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert);
            var okAction = UIAlertAction.Create("Ok", UIAlertActionStyle.Cancel, (obj) =>
            {
                // If user has been added successfully, dismiss view controller
                if (statusUser == "Success")
                {
                    var loginController = this.Storyboard.InstantiateViewController("LoginUserViewController") as LoginUserViewController;
                    if (loginController != null)
                    {
                        this.PresentViewController(loginController, true, null);
                    }
                }
                else if (statusUser == "Error" && alertMessage == "Email already exists")
                {
                    //var registerController = this.Storyboard.InstantiateViewController("EnterEmailRegisterUser") as RegisterUserViewController;
                    //if (registerController != null)
                    this.NavigationController.PopViewController(true);
                }
            });

            alert.AddAction(okAction);
            this.PresentViewController(alert, true, null);

            // Remove overlay
            LoadingOverlay.RemoveOverlay();
        }
Ejemplo n.º 3
0
        // Facebook Authentification
        void FacebookAuthentication()
        {
            flag = false;
            // If was send true to Profile.EnableUpdatesOnAccessTokenChange method
            // this notification will be called after the user is logged in and
            // after the AccessToken is gotten
            Profile.Notifications.ObserveDidChange((sender, e) =>
            {
                if (e.NewProfile == null)
                {
                    return;
                }

                var accessToken = AccessToken.CurrentAccessToken.TokenString;
                var request     = new GraphRequest("/" + e.NewProfile.UserID, new NSDictionary("fields", "email,first_name,last_name,picture.type(large)"), accessToken, null, "GET");
                request.Start((connection, result, error) =>
                {
                    // Show the loading overlay on the UI
                    LoadingOverlay.ShowOverlay(View);

                    var userInfo = result as NSDictionary;

                    // Get Facebook avatar image from url
                    var avatarUrl = new NSUrl(userInfo["picture"].ValueForKey(new NSString("data")).ValueForKey(new NSString("url")).ToString());
                    var data      = NSData.FromUrl(avatarUrl);

                    facebookImageData = data;

                    // string facebookAvatar = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
                    // facebookAvatar = new NSString(eefacebookAvatar, NSStringEncoding.UTF8); //Encoding.ASCII.GetString(ToByteArray(data));

                    // Add Facebook user to database
                    var user = new UsersModel()
                    {
                        FirstName     = userInfo["first_name"].ToString(),
                        LastName      = userInfo["last_name"].ToString(),
                        Email         = userInfo["email"].ToString().ToLower(),
                        LoginProvider = "Facebook"
                    };

                    // Call REST service to send Json data
                    RestService rs = new RestService();

                    // Get Json data from server in JsonResponseModel format
                    Task <UsersModel> jsonResponeTask = rs.UserLoginAndRegisterJson(user, "register");

                    // If there was an error in PostJsonDataAsync class, display message
                    if (jsonResponeTask == null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        return;
                    }

                    // Get user id from Json after login or display an error
                    GetUserIdFromJson(jsonResponeTask, user);

                    if (error != null)
                    {
                        LoadingOverlay.RemoveOverlay();
                        Console.WriteLine("Error in request. Start Facebook login");
                        return;
                    }
                });
            });

            // Set the Read and Publish permissions you want to get
            loginView = new LoginButton(fbAuthButton.Frame)
            {
                LoginBehavior   = LoginBehavior.Native,
                ReadPermissions = readPermissions.ToArray()
            };

            // Handle actions once the user is logged in
            loginView.Completed += LoginView_Completed;

            // Handle actions once the user is logged out
            loginView.LoggedOut += (sender, e) =>
            {
                // Set logout User Defaults
                var plist = NSUserDefaults.StandardUserDefaults;
                plist.SetBool(false, "isUserLoggedIn"); // set flag that user logged out
                plist.SetString("", "userId");
                plist.Synchronize();
            };

            // Use your System Account of Settings
            //loginButton.LoginBehavior = LoginBehavior.SystemAccount;

            // Add views to main view
            View.AddSubview(loginView);
        }