Ejemplo n.º 1
0
        public async Task <ActionResult> ChangePasswordAsync([FromBody] PasswordChangeData data)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            var result = await _userManager.ChangePasswordAsync(user, data.OldPassword, data.NewPassword);

            if (!result.Succeeded)
            {
                if (result.Errors.First().Code == "PasswordMismatch")
                {
                    return(Unauthorized(new ProblemDetails
                    {
                        Status = 401,
                        Title = "Unauthorized",
                        Detail = "Invalid current password."
                    }));
                }

                return(BadRequest(new ProblemDetails
                {
                    Status = 400,
                    Title = "Bad Request",
                    Detail = "Invalid new password. The password must contain at least 6 characters, and at least one uppercase, one lowercase and on number."
                }));
            }

            return(Ok());
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> ChangePasswordAsync([FromBody] PasswordChangeData data)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            var result = await _userManager.ChangePasswordAsync(user, data.OldPassword, data.NewPassword);

            if (!result.Succeeded)
            {
                if (result.Errors.First().Code == "PasswordMismatch")
                {
                    return(Unauthorized(new ProblemDetails
                    {
                        Status = 401,
                        Title = "Unauthorized",
                        Detail = "Invalid current password."
                    }));
                }

                return(BadRequest(new ProblemDetails
                {
                    Status = 400,
                    Title = "Bad Request",
                    Detail = result.Errors.First().Description
                }));
            }

            return(Ok());
        }
Ejemplo n.º 3
0
        public async Task <BaseResponse> ChangePassword(PasswordChangeData passwordChangeData, string userId)
        {
            try
            {
                User user = await _userRepository.GetUserById(userId);

                if (_passwordHasher.GetHashedPassword(passwordChangeData.oldPassword) == user.Password)
                {
                    try
                    {
                        var newPassword = _passwordHasher.GetHashedPassword(passwordChangeData.newPassword);
                        await _userRepository.ChangePassword(newPassword, userId);

                        return(new BaseResponse(true, null, null));
                    }
                    catch (Exception ex)
                    {
                        return(GetErrorResponse(ex.Message));
                    }
                }
                else
                {
                    return(GetErrorResponse("Old password not match"));
                }
            }catch (Exception ex)
            {
                return(GetErrorResponse(ex.Message));
            }
        }
Ejemplo n.º 4
0
        public async Task ChangePassword(Guid token, PasswordChangeData passwordChangeData)
        {
            UserModel user = await _context.Users.FirstOrDefaultAsync(x => x.Token == token && x.IsActive);

            if (user != null)
            {
                if (passwordChangeData.newPassword != passwordChangeData.newPasswordRepeat)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ex.Data.Add("message", "PASSWORS_EQUAL_ERROR");
                    throw ex;
                }

                if (user.Password != passwordChangeData.oldPassword)
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ex.Data.Add("message", "PASSWORD_INCORRECT");
                    throw ex;
                }

                user.Password = passwordChangeData.newPassword;
                _context.Update(user);
                await _context.SaveChangesAsync();
            }
            else
            {
                NullReferenceException ex = new NullReferenceException();
                ex.Data.Add("message", "USER_NOT_FOUND");
                throw ex;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sends a new password to server
        /// </summary>
        public void ChangePassword(PasswordChangeData data, SuccessCallback callback, ErrorCallback errorCallback)
        {
            if (!Client.IsConnected)
            {
                errorCallback.Invoke("Not connected to server");
                return;
            }

            var dictionary = new Dictionary <string, string>()
            {
                { "email", data.Email },
                { "code", data.Code },
                { "password", data.NewPassword }
            };

            Client.SendMessage((ushort)OpCodes.PasswordChange, dictionary.ToBytes(), (status, response) =>
            {
                if (status != ResponseStatus.Success)
                {
                    errorCallback.Invoke(response.AsString("Unknown error"));
                    return;
                }

                callback.Invoke();
            });
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> ChangePassword([FromBody] PasswordChangeData passwordChangeData)
        {
            var principal = HttpContext.User;
            var userId    = principal.FindFirstValue(ClaimTypes.NameIdentifier);

            var response = await _userService.ChangePassword(passwordChangeData, userId);

            return(Ok(response));
        }
Ejemplo n.º 7
0
        public async Task <IHttpActionResult> UserPasswordChange(PasswordChangeData passwordChangeData)
        {
            //PasswordChangeData passwordChangeData = JsonConvert.DeserializeObject<PasswordChangeData>(body);

            User user = db.Users.Where(u => u.Id == passwordChangeData.Id).FirstOrDefault();

            if (user != null)
            {
                byte[]       hashBytes = Util.StringToByteArray(user.PasswordHash);
                PasswordHash hash      = new PasswordHash(hashBytes);
                if (!hash.Verify(passwordChangeData.OldPwd))
                {
                    return(InternalServerError(new Exception("Incorrect current password")));
                }

                hashBytes = new PasswordHash(passwordChangeData.NewPwd).ToArray();
                string strBase64 = Util.ByteArrayToString(hashBytes);
                user.PasswordHash = strBase64;

                DbEntityEntry entry = db.Entry(user);
                entry.State = EntityState.Modified;

                // Marking properties to update by compareing default object
                User defaultUser = new User();
                entry = Util.GetUpdatedProperties(defaultUser, user, entry);

                try
                {
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(passwordChangeData.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                return(Ok(user));
            }
            else
            {
                return(InternalServerError(new Exception("User ID not found.")));
            }
        }
        public async Task <IActionResult> ChangePassword([FromBody] PasswordChangeData passwordChangeData, [FromQuery] Guid token)
        {
            try
            {
                await _authService.ChangePassword(token, passwordChangeData);

                return(Ok());
            }

            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
        async void ChangePassword()
        {
            if (string.IsNullOrEmpty(User))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe capturar su usuario.");

                return;
            }

            if (string.IsNullOrEmpty(Password))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe capturar su contraseña.");

                return;
            }

            if (string.IsNullOrEmpty(NewPassword))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe capturar su nueva contraseña.");

                return;
            }

            if (string.IsNullOrEmpty(NewPassword2))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe capturar repetir su nueva contraseña.");

                return;
            }

            if (Password == NewPassword)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "La nueva contraseña no puede ser igual a la actual.");

                return;
            }

            if (NewPassword != NewPassword2)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Capture la misma nueva contraseña.");

                return;
            }

            if (string.IsNullOrEmpty(City))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe seleccionar una ciudad.");

                return;
            }


            IsRunning = true;
            IsEnabled = false;

            var connection = await apiService.CheckConnection();

            if (connection == null)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", "No se puede contactar al servidor.");

                return;
            }

            if (!connection.IsSuccess)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", connection.Message);

                return;
            }

            var urlAPI = Application.Current.Resources["URLAPI"].ToString();

            var response = await apiService.GetToken(
                urlAPI,
                User,
                Password,
                ToCity());

            if (response == null)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", "No se puede contactar al servidor.");

                Password = null;
                return;
            }

            if (string.IsNullOrEmpty(response.AccessToken))
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", response.ErrorDescription);

                Password = null;
                return;
            }

            /*
             * response.IsRemembered = IsToggled;
             * response.Password = Password;
             * dataService.DeleteAllTokensAndInsert(response);
             */

            PasswordChangeData newData = new PasswordChangeData {
                City    = response.City,
                User    = User,
                Pwd     = Password,
                NewPwd  = NewPassword,
                NewPwd2 = NewPassword2
            };

            var userResponse = await apiService.Put2 <User>(urlAPI, "users", response.City, response.TokenType, response.AccessToken, newData);

            //Get all data for current user
            //var userResponse = await apiService.Get<Models.User>(urlAPI, "users", response.City, response.TokenType, response.AccessToken, response.Login);

            if (userResponse == null)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", "No se puede contactar al servidor.");

                Password     = null;
                NewPassword  = null;
                NewPassword2 = null;
                return;
            }

            if (!userResponse.IsSuccess)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", userResponse.Message);

                Password = null;
                return;
            }

            /*
             * Models.User CurrentUser = (Models.User)userResponse.Result;
             * dataService.DeleteAllUsersAndInsert(CurrentUser);
             *
             * var mainViewModel = MainViewModel.GetInstance();
             * mainViewModel.Token = response;
             * mainViewModel.User = CurrentUser;
             * mainViewModel.RegisterDevice();
             * mainViewModel.Home = new HomeViewModel();
             *
             * mainViewModel.Home.CurrentStatistics = dataService.LoadStatistics();
             * navigationService.SetMainPage("MasterView");
             */

            User     = null;
            Password = null;

            IsRunning = false;
            IsEnabled = true;
            await navigationService.BackOnLogin();
        }