public IHttpActionResult SetUserPassword(SetPasswordModel passwordModel)
        {
            var user = _userManagement.FindByUserId(passwordModel.UserId);

            if (user != null)
            {
                var result = _userManagement.SetUserPassword(passwordModel);

                if (result.IsSuccess)
                {
                    return(Ok(result.Result));
                }
                else
                {
                    return(GetErrorResult(result));
                }
            }

            return(NotFound());
        }
        public async Task <HttpResponseMessage> PostSetPassword(SetPasswordModel model)
        {
            var result = await UserManager.ResetPasswordAsync(model.UserId, model.ResetCode, model.Password);

            if (result.Succeeded)
            {
                var lockedOut = await UserManager.IsLockedOutAsync(model.UserId);

                if (lockedOut)
                {
                    Logger.Info <AuthenticationController>(
                        "User {0} is currently locked out, unlocking and resetting AccessFailedCount",
                        () => model.UserId);

                    //var user = await UserManager.FindByIdAsync(model.UserId);
                    var unlockResult = await UserManager.SetLockoutEndDateAsync(model.UserId, DateTimeOffset.Now);

                    if (unlockResult.Succeeded == false)
                    {
                        Logger.Warn <AuthenticationController>("Could not unlock for user {0} - error {1}",
                                                               () => model.UserId, () => unlockResult.Errors.First());
                    }

                    var resetAccessFailedCountResult = await UserManager.ResetAccessFailedCountAsync(model.UserId);

                    if (resetAccessFailedCountResult.Succeeded == false)
                    {
                        Logger.Warn <AuthenticationController>("Could not reset access failed count {0} - error {1}",
                                                               () => model.UserId, () => unlockResult.Errors.First());
                    }
                }

                if (UserManager != null)
                {
                    UserManager.RaiseForgotPasswordChangedSuccessEvent(model.UserId);
                }
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            return(Request.CreateValidationErrorResponse(
                       result.Errors.Any() ? result.Errors.First() : "Set password failed"));
        }
Esempio n. 3
0
        public string SetNewPassword(SetPasswordModel setPasswordModel)
        {
            string msg  = string.Empty;
            var    user = _db.MstUsers.Where(x => x.IsActive && x.Email.Equals(setPasswordModel.Username)).FirstOrDefault();

            if (user == null)
            {
                msg = "User does not exists";
            }
            else
            {
                user.Password          = setPasswordModel.ConfirmPassword;
                user.ModifiedBy        = user.UserId;
                user.ModifiedDate      = DateTime.Now;
                user.IsPasswordReset   = false;
                user.PasswordResetCode = null;
                _db.Entry(user).State  = EntityState.Modified;
                msg = _db.SaveChanges() > 0 ? "set" : "Unable to set new password";
            }
            return(msg);
        }
Esempio n. 4
0
        public async Task <IActionResult> SetPassword()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var hasPassword = await _userManager.HasPasswordAsync(user);

            if (hasPassword)
            {
                return(RedirectToAction(nameof(ChangePassword)));
            }

            var model = new SetPasswordModel {
            };

            return(View(model));
        }
Esempio n. 5
0
        public async Task <HttpResponseMessage> SetPassword([FromBody] SetPasswordModel model)
        {
            try
            {
                //該当ユーザーを取得
                var ldapUser = await new LdapUserStore().FindByNameAsync(model.Id);

                //パスワードをハッシュ化
                var passwordHash = SSHASaltedGenerator.GenerateSaltedSHA1(model.Password);

                //パスワードを更新
                await new LdapUserStore().SetPasswordHashAsync(ldapUser, passwordHash);

                //更新した結果を返す
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, e));
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> SetPassword()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var hasPassword = await _userManager.HasPasswordAsync(user);

            if (hasPassword)
            {
                return(RedirectToAction("ChangePassword"));
            }

            var model = new SetPasswordModel();

            model.StatusMessage = StatusMessage;
            return(View(model));
        }
Esempio n. 7
0
        public async Task <IHttpActionResult> SetPassword(string userId, [FromBody] SetPasswordModel model)
        {
            var currentUser = ActionContext.RequestContext.Principal.Identity;

            if ((currentUser.GetUserId() != userId) && (!_userManager.IsInRole(currentUser.GetUserId(), "Admin")))
            {
                return(Unauthorized());
            }

            await _userManager.RemovePasswordAsync(userId);

            var result = await _userManager.AddPasswordAsync(userId, model.Password);

            var errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return(errorResult);
            }

            return(Ok("Password set"));
        }
Esempio n. 8
0
        public async Task <SetPasswordModel> AddPassword(SetPasswordModel model)
        {
            var user = await GetUser(model.UserId, model);

            if (user == null)
            {
                return(LogErrorReturnModel(model));
            }

            var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword);

            if (addPasswordResult.Succeeded)
            {
                model.Succeeded = true;
                return(model);
            }

            model.Errors = addPasswordResult.Errors.ToList();
            LogErrors(model, "Failed to add password");

            return(model);
        }
        public async Task <IActionResult> SetPassword()
        {
            var user = await this.userManager.GetUserAsync(this.User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{this.userManager.GetUserId(this.User)}'.");
            }

            var hasPassword = await this.userManager.HasPasswordAsync(user);

            if (hasPassword)
            {
                return(this.RedirectToAction(nameof(this.ChangePassword)));
            }

            var model = new SetPasswordModel {
                StatusMessage = this.StatusMessage
            };

            return(this.View(model));
        }
Esempio n. 10
0
        public ActionResult SetPassword(Guid id, Guid accountId)
        {
            var tokenService = new TokenService(DbContext);
            var token        = tokenService.GetOneOrNullById(accountId, id);

            if (token == null)
            {
                return(View("LinkNotValid"));
            }

            var accountDbContext = DbContext.GetAccountDbContext(accountId);
            var userRepository   = accountDbContext.GetUserRepository();
            var user             = userRepository.GetById(token.UserId);

            var model = new SetPasswordModel()
            {
                TokenId   = id,
                UserName  = user.DisplayName,
                AccountId = accountId
            };

            return(View(model));
        }
Esempio n. 11
0
        public ActionResult SetPassword(SetPasswordModel model)
        {
            if (_workContext.CurrentProfile.IsAnonymous)
            {
                return(new HttpUnauthorizedResult());
            }

            if (ModelState.IsValid)
            {
                var result = _identityExternalAuthService.SetPassword(_workContext.CurrentProfile.Username, model.NewPassword);

                if (result)
                {
                    _session["message"] = "Your password has been successfully added. You can now can log onto Apollo with just your email address";
                }
                else
                {
                    _session["error"] = "Failed to set password. Please contact us for more information.";
                }
            }

            return(RedirectToAction("Account"));
        }
        public async Task <bool> setpasswordtouser(string userId, SetPasswordModel setpassword)
        {
            var user = await UserManager.FindByIdAsync(setpassword.Id);

            if (setpassword.NewPassword != "")
            {
                var newPasswordHash = UserManager.PasswordHasher.HashPassword(user, setpassword.NewPassword);
                user.PasswordHash = newPasswordHash;
                user.UpdateDate   = DateTime.Now;
                user.Uid          = userId;
                var res = await UserManager.UpdateAsync(user);

                if (res.Succeeded)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 13
0
        public IHttpActionResult SetPassword([FromBody] SetPasswordModel model)
        {
            var pwdreset = db.PasswordReset.Where(m => m.Id == model.PasswordResetId && m.UID == model.UID && m.IsReset == false).FirstOrDefault();

            if (pwdreset != null)
            {
                var user = db.UserAccount.Where(u => u.UserId == pwdreset.UserId).FirstOrDefault();

                if (user != null)
                {
                    //set password
                    Authentication.GeneratePassword(model.Password);

                    user.HashPassword = Authentication.HashPassword;
                    user.Salt         = Authentication.Salt;

                    db.UserAccount.Attach(user);
                    db.Entry(user).Property(e => e.HashPassword).IsModified = true;
                    db.Entry(user).Property(e => e.Salt).IsModified         = true;


                    //update password reset
                    pwdreset.IsReset   = true;
                    pwdreset.ResetDate = DateTime.Now;
                    db.PasswordReset.Attach(pwdreset);
                    db.Entry(pwdreset).Property(e => e.IsReset).IsModified   = true;
                    db.Entry(pwdreset).Property(e => e.ResetDate).IsModified = true;

                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();

                    return(Ok(true));
                }
            }

            return(NotFound());
        }
Esempio n. 14
0
        public async Task <IActionResult> SetPassword(SetPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await GetCurrentUserAsync();

            if (user != null)
            {
                var result = await _userManager.AddPasswordAsync(user, model.NewPassword);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }));
                }
                AddErrors(result);
                return(View(model));
            }
            return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }));
        }
        public async Task <IActionResult> SetPassword(SetPasswordModel setPasswordModel)
        {
            if (setPasswordModel.UserId == null || setPasswordModel.EmailConfirmationCode == null || setPasswordModel.PasswordCode == null)
            {
                return(RedirectToPage("Home", "Index"));
            }

            var user = await _userManager.FindByIdAsync(setPasswordModel.UserId);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{setPasswordModel.UserId}'."));
            }

            setPasswordModel.PasswordCode          = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(setPasswordModel.PasswordCode));
            setPasswordModel.EmailConfirmationCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(setPasswordModel.EmailConfirmationCode));
            var emailResult = await _userManager.ConfirmEmailAsync(user, setPasswordModel.EmailConfirmationCode);

            var resetPasswordResult = await _userManager.ResetPasswordAsync(user, setPasswordModel.PasswordCode, setPasswordModel.Password);

            await _userManager.SetUserNameAsync(user, setPasswordModel.Username);

            return(RedirectToAction("Login"));
        }
        public IHttpActionResult RecoverPassword(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return NotFound();
            }
            int status;
            var recoverpassword = _userProfileServices.GetRecoverPasswordByToken(token, out status);

            switch (status)
            {
                case 404:
                    return NotFound();
                case 400:
                    return BadRequest();
                default:
                    if (recoverpassword == null)
                    {
                        return BadRequest();
                    }

                    var result = new SetPasswordModel
                    {
                        UserName = recoverpassword.UserName,
                        Token = recoverpassword.Token
                    };
                    
                    return Ok(result);

            }
        }
Esempio n. 17
0
        public async Task <HttpResponseMessage> PostSetPassword(SetPasswordModel model)
        {
            var result = await UserManager.ResetPasswordAsync(model.UserId, model.ResetCode, model.Password);

            if (result.Succeeded)
            {
                var lockedOut = await UserManager.IsLockedOutAsync(model.UserId);

                if (lockedOut)
                {
                    Logger.Info <AuthenticationController>("User {UserId} is currently locked out, unlocking and resetting AccessFailedCount", model.UserId);

                    //var user = await UserManager.FindByIdAsync(model.UserId);
                    var unlockResult = await UserManager.SetLockoutEndDateAsync(model.UserId, DateTimeOffset.Now);

                    if (unlockResult.Succeeded == false)
                    {
                        Logger.Warn <AuthenticationController>("Could not unlock for user {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First());
                    }

                    var resetAccessFailedCountResult = await UserManager.ResetAccessFailedCountAsync(model.UserId);

                    if (resetAccessFailedCountResult.Succeeded == false)
                    {
                        Logger.Warn <AuthenticationController>("Could not reset access failed count {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First());
                    }
                }

                //They've successfully set their password, we can now update their user account to be confirmed
                //if user was only invited, then they have not been approved
                //but a successful forgot password flow (e.g. if their token had expired and they did a forgot password instead of request new invite)
                //means we have verified their email
                if (!UserManager.IsEmailConfirmed(model.UserId))
                {
                    await UserManager.ConfirmEmailAsync(model.UserId, model.ResetCode);
                }

                //if the user is invited, enable their account on forgot password
                var identityUser = await UserManager.FindByIdAsync(model.UserId);

                //invited is not approved, never logged in, invited date present

                /*
                 * if (LastLoginDate == default && IsApproved == false && InvitedDate != null)
                 *  return UserState.Invited;
                 */
                if (identityUser != null && !identityUser.IsApproved)
                {
                    var user = Services.UserService.GetByUsername(identityUser.UserName);
                    //also check InvitedDate and never logged in, otherwise this would allow a disabled user to reactivate their account with a forgot password
                    if (user.LastLoginDate == default && user.InvitedDate != null)
                    {
                        user.IsApproved  = true;
                        user.InvitedDate = null;
                        Services.UserService.Save(user);
                    }
                }

                UserManager.RaiseForgotPasswordChangedSuccessEvent(model.UserId);
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            return(Request.CreateValidationErrorResponse(
                       result.Errors.Any() ? result.Errors.First() : "Set password failed"));
        }
Esempio n. 18
0
        public async Task <IActionResult> PostSetPassword(SetPasswordModel model)
        {
            var identityUser = await _userManager.FindByIdAsync(model.UserId.ToString(CultureInfo.InvariantCulture));

            var result = await _userManager.ResetPasswordAsync(identityUser, model.ResetCode, model.Password);

            if (result.Succeeded)
            {
                var lockedOut = await _userManager.IsLockedOutAsync(identityUser);

                if (lockedOut)
                {
                    _logger.LogInformation("User {UserId} is currently locked out, unlocking and resetting AccessFailedCount", model.UserId);

                    //// var user = await UserManager.FindByIdAsync(model.UserId);
                    var unlockResult = await _userManager.SetLockoutEndDateAsync(identityUser, DateTimeOffset.Now);

                    if (unlockResult.Succeeded == false)
                    {
                        _logger.LogWarning("Could not unlock for user {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First().Description);
                    }

                    var resetAccessFailedCountResult = await _userManager.ResetAccessFailedCountAsync(identityUser);

                    if (resetAccessFailedCountResult.Succeeded == false)
                    {
                        _logger.LogWarning("Could not reset access failed count {UserId} - error {UnlockError}", model.UserId, unlockResult.Errors.First().Description);
                    }
                }

                // They've successfully set their password, we can now update their user account to be confirmed
                // if user was only invited, then they have not been approved
                // but a successful forgot password flow (e.g. if their token had expired and they did a forgot password instead of request new invite)
                // means we have verified their email
                if (!await _userManager.IsEmailConfirmedAsync(identityUser))
                {
                    await _userManager.ConfirmEmailAsync(identityUser, model.ResetCode);
                }

                // invited is not approved, never logged in, invited date present

                /*
                 * if (LastLoginDate == default && IsApproved == false && InvitedDate != null)
                 *  return UserState.Invited;
                 */
                if (identityUser != null && !identityUser.IsApproved)
                {
                    var user = _userService.GetByUsername(identityUser.UserName);
                    // also check InvitedDate and never logged in, otherwise this would allow a disabled user to reactivate their account with a forgot password
                    if (user.LastLoginDate == default && user.InvitedDate != null)
                    {
                        user.IsApproved  = true;
                        user.InvitedDate = null;
                        _userService.Save(user);
                    }
                }

                _userManager.NotifyForgotPasswordChanged(User, model.UserId.ToString(CultureInfo.InvariantCulture));
                return(Ok());
            }

            return(new ValidationErrorResult(result.Errors.Any() ? result.Errors.First().Description : "Set password failed"));
        }
 public async Task <IHttpActionResult> SetPassword(SetPasswordModel model)
 {
     return(await RunTask(() => AccountManager.AddPasswordAsync(User, model)));
 }
Esempio n. 20
0
 public ResponseModel SetPassword(SetPasswordModel user)
 {
     throw new NotImplementedException();
 }
Esempio n. 21
0
 public async Task SetPassword(SetPasswordModel model)
 {
     await PutAsync <string>($"api/users/{model.Id}/password", model);
 }
 public GenericActionResult <string> SetUserPassword(SetPasswordModel model)
 {
     return(_userManager.SetPassword(model));
 }
        public async Task <IActionResult> SetPassword()
        {
            var model = new SetPasswordModel(_currentUserAccessor.User.Id);

            return(View(model));
        }
Esempio n. 24
0
 public async Task <SetPasswordModel> AddPasswordAsync(SetPasswordModel model)
 {
     return(await _apiHelper.PostAsync(model, "api/Account/Manage/AddPassword"));
 }
        public async Task <IHttpActionResult> SetPassword(SetPasswordModel model)
        {
            var result = await userManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);

            return(Ok(result));
        }
Esempio n. 26
0
        public async Task <IActionResult> SetPassword([FromBody] SetPasswordModel model)
        {
            await _service.SetPasswordAsync(model);

            return(Ok());
        }
Esempio n. 27
0
        //TODO REFACTOR THIS METHOD
        public GenericActionResult <string> SetPassword(SetPasswordModel model)
        {
            try
            {
                var checkPasswordResult = this.PasswordValidator.ValidateAsync(model.ConfirmPassword);

                if (checkPasswordResult.Result.Succeeded)
                {
                    var removePasswordresult = this.RemovePassword(model.UserId);

                    if (removePasswordresult.Succeeded)
                    {
                        var result = this.AddPassword(model.UserId, model.ConfirmPassword);

                        if (result.Succeeded)
                        {
                            return(new GenericActionResult <string>
                            {
                                IsSuccess = true,
                                Result = "Password updated sucessfully!"
                            });
                        }
                        else
                        {
                            return(new GenericActionResult <string>
                            {
                                IsSuccess = true,
                                Result = null,
                                Errors = result.Errors
                            });
                        }
                    }
                    else
                    {
                        return(new GenericActionResult <string>()
                        {
                            Errors = checkPasswordResult.Result.Errors,
                            IsSuccess = false
                        });
                    }
                }
                else
                {
                    return(new GenericActionResult <string>()
                    {
                        Errors = checkPasswordResult.Result.Errors,
                        IsSuccess = false
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Updated password failed", ex);
                return(new GenericActionResult <string>()
                {
                    Errors = new List <string>()
                    {
                        "Password updates failed!"
                    },
                    IsSuccess = false
                });
            }
        }
        private async void BtnSend_TouchUpInside(object sender, EventArgs e)
        {
            if (string.Empty.Equals(txtCode.Text))
            {
                Utils.ShowToast("Please fill in the code", 3000);
            }
            else if (txtCode.Text.Length != 4)
            {
                Utils.ShowToast("Please fill in the 4-digit code", 3000);
            }
            else if (string.Empty.Equals(txtPassword.Text))
            {
                Utils.ShowToast("Please fill in the new password", 3000);
            }
            else if (string.Empty.Equals(txtConfirmPassword.Text))
            {
                Utils.ShowToast("Please fill in the password confirmation", 3000);
            }
            else if (!txtPassword.Text.Equals(txtConfirmPassword.Text))
            {
                Utils.ShowToast("Passwords must match", 3000);
            }
            else
            {
                try
                {
                    BTProgressHUD.Show("Validating...", -1, ProgressHUD.MaskType.Clear);

                    DateTime dt  = DateTime.ParseExact(NSUserDefaults.StandardUserDefaults.StringForKey("AskkerPwdTimeStamp"), "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                    DateTime now = DateTime.Now;

                    TimeSpan span = now.Subtract(dt);

                    if (!txtCode.Text.Equals(NSUserDefaults.StandardUserDefaults.StringForKey("AskkerPwdCode")))
                    {
                        BTProgressHUD.ShowErrorWithStatus("Invalid code", 3000);
                    }
                    else if (span.Seconds > 300)
                    {
                        BTProgressHUD.ShowErrorWithStatus("Code expired, please request another code.", 3000);
                    }

                    SetPasswordModel model = new SetPasswordModel(Email, txtPassword.Text, txtConfirmPassword.Text);

                    await new LoginManager().SetPasswordFromApp(model);

                    BTProgressHUD.ShowSuccessWithStatus("Everything OK!\nPlease login");

                    NSUserDefaults.StandardUserDefaults.RemoveObject("AskkerPwdCode");
                    NSUserDefaults.StandardUserDefaults.RemoveObject("AskkerPwdTimeStamp");

                    var loginController = this.Storyboard.InstantiateViewController("LoginController");
                    if (loginController != null)
                    {
                        this.NavigationController.PushViewController(loginController, true);
                    }
                }
                catch (Exception ex)
                {
                    BTProgressHUD.Dismiss();

                    Utils.ShowAlertOk("Something went wrong", ex.Message);
                }
            }
        }
 public async Task <IdentityResult> AddPasswordAsync(IPrincipal user, SetPasswordModel model)
 {
     return(await UserManager.AddPasswordAsync(user.Identity.GetUserId(), model.NewPassword));
 }
 public async Task<IHttpActionResult> SetPassword(SetPasswordModel model)
 {
     return await this.RunTask(() => AccountManager.AddPasswordAsync(User, model));
 }
 public bool SetAuthenticationPwd(SetPasswordModel user)
 {
     throw new NotImplementedException();
 }