Example #1
0
        //Update user data
        private async void Update()
        {
            try
            {
                Label nombreUsuario = new Label();
                nombreUsuario.SetBinding(Label.TextProperty, new Binding("Nombre", source: AppShell.Inicio));
                string nombre  = nombreUsuario.Text;
                var    usuario = await FirebaseHelper.ObtenerUsuario(nombre);

                string passSinEspacios = Regex.Replace(NewPassword, @"\s", "");
                if (!string.IsNullOrEmpty(passSinEspacios))
                {
                    if ((passSinEspacios.Length < 8 && passSinEspacios.Length > 15) || !passSinEspacios.ToCharArray().Any(Char.IsDigit))
                    {
                        UserDialogs.Instance.Alert("La contraseña debe tener como mínimo 8 caracteres y un máximo de 15, incluyendo una letra minúscula, una mayúscula y un número.", "Error", "OK");
                    }
                    else
                    {
                        var authProvider = new FirebaseAuthProvider(new FirebaseConfig(Constantes.WebAPIkey));
                        try
                        {
                            //This is the saved firebaseauthentication that was saved during the time of login
                            var savedfirebaseauth = JsonConvert.DeserializeObject <Firebase.Auth.FirebaseAuth>(Preferences.Get("MyFirebaseRefreshToken", ""));
                            //Here we are Refreshing the token
                            var RefreshedContent = await authProvider.RefreshAuthAsync(savedfirebaseauth);

                            Preferences.Set("MyFirebaseRefreshToken", JsonConvert.SerializeObject(RefreshedContent));
                            //Now lets grab user information
                            string token = savedfirebaseauth.FirebaseToken;
                            await authProvider.ChangeUserPassword(token, passSinEspacios);

                            var isupdate = await FirebaseHelper.ActualizarUsuario(nombre, usuario.FirebaseToken, usuario.UsuarioId);

                            if (isupdate)
                            {
                                UserDialogs.Instance.Alert("", "Contraseña actualizada", "Ok");
                            }
                            else
                            {
                                UserDialogs.Instance.Alert("No se ha podido actualizar.", "Error", "Ok");
                            }
                        }
                        catch (Exception)
                        {
                            UserDialogs.Instance.Alert("Por favor, introduzca un nombre de usuario y una contraseña correctos", "Fallo cambio contraseña", "OK");
                        }
                    }
                }
                else
                {
                    UserDialogs.Instance.Alert("Por favor, introduzca una nueva contraseña.", "Inserte una contraseña válida", "Ok");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error catch:{e}");
            }
        }
Example #2
0
        public async Task <AuthToken> ChangePassword(AuthConfig authConfig, string token, string newPassoword)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(authConfig.ApiKey));
                    var authLink             = await firebaseAuthProvider.ChangeUserPassword(token, newPassoword);

                    var authToken = new AuthToken
                    {
                        Token     = authLink.FirebaseToken,
                        ExpiresAt = DateTime.Now.AddSeconds(authLink.ExpiresIn)
                    };

                    var handler  = new JwtSecurityTokenHandler();
                    var userInfo = handler.ReadJwtToken(authLink.FirebaseToken);
                    userInfo.Payload.TryGetValue("user_id", out object userId);
                    authToken.UserId = userId as string;
                    return(authToken);
                }
                catch (FirebaseAuthException e)
                {
                    switch (e.Reason)
                    {
                    case AuthErrorReason.MissingEmail: throw new AuthException(SignUpError.MissingEmail.ToDescription());

                    case AuthErrorReason.MissingPassword: throw new AuthException(SignUpError.MissingPassword.ToDescription());

                    case AuthErrorReason.WrongPassword: throw new AuthException(SignUpError.WrongPassowrd.ToDescription());

                    case AuthErrorReason.UserDisabled: throw new AuthException(SignUpError.DisabledUser.ToDescription());

                    case AuthErrorReason.InvalidEmailAddress: throw new AuthException(SignUpError.InvalidEmail.ToDescription());

                    case AuthErrorReason.Undefined: throw new AuthException(e.InnerException != null ? e.InnerException.Message : e.Message);

                    default: throw new AuthException(SignUpError.Other.ToDescription());
                    }
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
        }
Example #3
0
        async void change_pwd_btn_Clicked(System.Object sender, System.EventArgs e)
        {
            var user        = new MyUser();
            var userNewPwd  = new_pwd_entry.Text;
            var userConfPwd = repeat_pwd_entry.Text;


            var  authProvider = new FirebaseAuthProvider(new FirebaseConfig(WebAPIKey));
            bool passwordOk;

            void PasswordValidation()
            {
                //tra 8-20 cifre, un carattere maiuscolo, un carattere minuscolo, un numero e un carattere speciale
                var passwordPattern = "(?=.*[A-Z])(?=.*\\d)(?=.*[¡!@#$%*¿?\\-_.\\(\\)])[A-Za-z\\d¡!@#$%*¿?\\-\\(\\)&]{8,20}";

                if (userNewPwd != null)
                {
                    if (Regex.IsMatch(userNewPwd, passwordPattern))
                    {
                        passwordOk = true;
                        LabelPwdError.TextColor = Color.Transparent;
                    }

                    else
                    {
                        passwordOk = false;
                        LabelPwdError.TextColor = Color.Red;
                    }
                }
                else
                {
                    passwordOk = false;
                    LabelPwdError.TextColor = Color.Red;
                }
            }

            void PasswordConfirmationValidation()
            {
                if (!user.IsPasswordMatching(userNewPwd, userConfPwd))
                {
                    passwordOk = false;
                    LabelConfirmPwdError.TextColor = Color.Red;
                }
                else
                {
                    passwordOk = true;
                    LabelConfirmPwdError.TextColor = Color.Transparent;
                }
            }

            PasswordValidation();
            PasswordConfirmationValidation();

            if (passwordOk)
            {
                try
                {
                    //This is the saved firebaseauthentication that was saved during the time of login
                    var savedfirebaseauth = JsonConvert.DeserializeObject <Firebase.Auth.FirebaseAuth>(Preferences.Get("MyLoginToken", ""));
                    //Here we are Refreshing the token
                    var RefreshedContent = await authProvider.RefreshAuthAsync(savedfirebaseauth);

                    Preferences.Set("MyLoginToken", JsonConvert.SerializeObject(RefreshedContent));
                    //Cambio password utente
                    await authProvider.ChangeUserPassword(savedfirebaseauth.FirebaseToken, userNewPwd);

                    await App.Current.MainPage.DisplayAlert("Success.", "New password set correctly.", "Ok");

                    await Navigation.PushAsync(new LoginPage());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    await App.Current.MainPage.DisplayAlert("Ops... Something went wrong.", "Try to logout and log back in.", "Ok");
                }
            }
        }
Example #4
0
        void mudarSenha()
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyA0hQhaFdSKMTQfpSltAmDdqdMvDDG-aR4"));

            authProvider.ChangeUserPassword(User.Token, txtSenha.Text);
        }