Example #1
0
        public async Task <BaseResponse> UpdateUserPasswordAsync(UserPasswordViewModel req, int Id)
        {
            var    userInfo = _user.Find(Id);
            string Password = EncryptData.EncryptPassword(req.OldPassword, userInfo.Salt);

            if (Password != userInfo.Password)
            {
                return(new BaseResponse {
                    Success = false, Message = "旧密码不正确"
                });
            }
            Password            = EncryptData.EncryptPassword(req.Password, userInfo.Salt);
            userInfo.Password   = Password;
            userInfo.Modify     = userInfo.Account;
            userInfo.ModifyTime = DateTime.Now;
            try
            {
                await _user.SaveAsync(userInfo);

                _log.LogInformation("用户修改密码成功");
                return(new BaseResponse {
                    Success = true, Message = "修改数据成功"
                });
            }
            catch (Exception ex)
            {
                _log.LogError($"用户修改密码失败:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
                return(new BaseResponse {
                    Success = false, Message = "用户修改密码失败,请联系管理员"
                });
            }
        }
Example #2
0
        public async Task <IActionResult> UpdatePassword([FromRoute] int id, [FromBody] UserPasswordViewModel userPass)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id <= 0)
            {
                return(BadRequest());
            }

            try
            {
                await _userService.ChangePassword(id, userPass);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(NotFound(ex));
            }
            catch (DbUpdateException ex)
            {
                return(BadRequest(ex));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
            return(Ok());
        }
Example #3
0
        public async Task <IActionResult> UpdatePassword([FromRoute] string id, [FromBody] UserPasswordViewModel viewModel)
        {
            User user = await repository.GetByIdAsync <User>(id, _includeProperties);

            if (user == null)
            {
                return(NotFound(new { message = "User does not exist!" }));
            }
            if (!HttpContext.User.IsInRole("admin"))
            {
                // only admin or current user can update current user's profile
                if (!HttpContext.User.HasClaim(c => c.Type == ClaimTypes.NameIdentifier && c.Value == user.Id))
                {
                    return(Forbid());
                }
            }
            var result = await repository.GetUserManager().ChangePasswordAsync(user, viewModel.Password, viewModel.NewPassword);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(BadRequest(ModelState));
            }
            user.ModifiedAt = DateTime.UtcNow;
            await repository.GetUserManager().UpdateAsync(user);

            return(NoContent());
        }
Example #4
0
        public async Task <string> ChangePassword(UserPasswordViewModel model)
        {
            User user = await _userManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                return("Not found user");
            }
            var isCorrectPassword = await _userManager.CheckPasswordAsync(user, model.CurrentPass);

            if (!isCorrectPassword)
            {
                if (model.CurrentPass.Equals("123456"))
                {
                    string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

                    await _userManager.ResetPasswordAsync(user, resetToken, model.NewPass);
                }
                else
                {
                    return(INCORRECT_PASS);
                }
            }
            else
            {
                await _userManager.ChangePasswordAsync(user, model.CurrentPass, model.NewPass);
            }
            //await _userManager.RemovePasswordAsync(user);
            //await _userManager.AddPasswordAsync(user, model.newPass);
            return(string.Empty);
        }
Example #5
0
        public async Task <IActionResult> ChangePassword(UserPasswordViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManagerService.GetUserAsync(User);

                if (user != null)
                {
                    var check = await _userManagerService.CheckPasswordAsync(user, vm.OldPassword);

                    if (check == true)
                    {
                        var changePassword = await _userManagerService.ChangePasswordAsync(user, vm.OldPassword, vm.NewPassword);

                        if (changePassword.Succeeded)
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError("", "Your Current Password is incorrect");
                            return(View(vm));
                        }
                    }
                }
                ModelState.AddModelError("", "unspecified error occured.");
                return(View(vm));
            }
            return(View(vm));
        }
Example #6
0
        public async Task <IActionResult> Password([Bind("Id,Password,PasswordConfirm")] UserPasswordViewModel m)
        {
            var user = _svc.GetUser(m.Id);

            if (!ModelState.IsValid || user == null)
            {
                return(View(m));
            }
            // update the password
            user.Password = m.Password;
            // save changes
            var updated = _svc.UpdateUser(user);

            if (updated == null)
            {
                Alert("There was a problem Updating the password. Please try again", AlertType.warning);
                return(View(m));
            }

            Alert("Successfully Updated Password", AlertType.info);
            // sign the user in with updated details)
            await SignIn(user);

            return(RedirectToAction("Index", "Home"));
        }
Example #7
0
        public Result <bool> ChangePassword(int userId, UserPasswordViewModel password)
        {
            try
            {
                if (password.NewPassword != password.RepeatedNewPassword)
                {
                    throw new Exception(EResultMessage.InvalidData.ToString());
                }

                var user = Get(u => u.Id == userId);
                if (user == null)
                {
                    throw new Exception(EResultMessage.NotFound.ToString());
                }

                if (!Protected.Validate(password.OldPassword, user.HashPassword))
                {
                    throw new Exception(EResultMessage.WrongPassword.ToString());
                }

                user.HashPassword = Protected.CreatePasswordHash(password.NewPassword);
                Update(user);

                if (!SaveChanges())
                {
                    throw new Exception(EResultMessage.DatabaseError.ToString());
                }

                return(ResultHelper.Succeeded(true, message: EResultMessage.RegistrationDone.ToString()));
            }
            catch (Exception e)
            {
                return(ResultHelper.Failed <bool>(message: e.Message));
            }
        }
Example #8
0
        public IActionResult Password()
        {
            var user = _svc.GetUser((this.Identity()).Value);
            var passwordViewModel = new UserPasswordViewModel {
                Id              = user.Id,
                Password        = user.Password,
                PasswordConfirm = user.Password,
            };

            return(View(passwordViewModel));
        }
Example #9
0
        public IActionResult UpdatePassword()
        {
            // use BaseClass helper method to retrieve Id of signed in user
            var user = _svc.GetUser(GetSignedInUserId());
            var passwordViewModel = new UserPasswordViewModel {
                Id              = user.Id,
                Password        = user.Password,
                PasswordConfirm = user.Password,
            };

            return(View(passwordViewModel));
        }
Example #10
0
        public void Create_get_and_Delete()
        {
            UsersController controller = new UsersController();

            controller.Request       = new HttpRequestMessage();
            controller.Configuration = new HttpConfiguration();

            IPrincipal            FakeUser = new GenericPrincipal(new GenericIdentity("admin", "Forms"), null);
            UserPasswordViewModel testUser = new UserPasswordViewModel()
            {
                password = "******",
                username = "******",
                IsADMIN  = true,
                IsPAGE_1 = true,
                IsPAGE_2 = true,
                IsPAGE_3 = true
            };
            //Act 1
            HttpResponseMessage result = controller.Post(testUser, FakeUser);

            //Assert 1
            Assert.AreEqual(result.StatusCode, System.Net.HttpStatusCode.OK);
            //Act 2
            result = controller.Get("test", FakeUser);
            UserViewModel user = null;

            if (result != null)
            {
                result.TryGetContentValue(out user);
            }
            //Assert 2
            Assert.IsNotNull(result);
            Assert.IsNotNull(user);
            Assert.AreEqual(user.IsADMIN, user.IsADMIN);
            Assert.AreEqual(user.IsPAGE_1, user.IsPAGE_1);
            Assert.AreEqual(user.IsPAGE_2, user.IsPAGE_2);
            Assert.AreEqual(user.IsPAGE_3, user.IsPAGE_2);
            //Act 3
            result = controller.Delete("test", FakeUser);
            //Assert 3
            Assert.AreEqual(result.StatusCode, System.Net.HttpStatusCode.OK);
            result = controller.Get("test", FakeUser);
            user   = null;
            if (result != null)
            {
                result.TryGetContentValue(out user);
            }

            Assert.IsNull(user);
            Assert.IsNotNull(result);
            Assert.AreEqual(result.StatusCode, System.Net.HttpStatusCode.NotFound);
        }
        public void UpdatePassword(UserPasswordViewModel model)
        {
            var mapper = CustomMapperConfiguration.ConfigCreateMapper <UserPasswordViewModel, User>();
            //var config = new MapperConfiguration(c =>
            //{
            //    c.CreateMap<UserPasswordViewModel, User>();
            //    c.IgnoreUnmapped();
            //});
            //var mapper = config.CreateMapper();
            var user = mapper.Map <UserPasswordViewModel, User>(model);

            user.Password = Sha256HashGenerator.GenerateHash(model.Password);
            _usersRepository.UpdatePassword(user);
        }
        public IHttpActionResult PutUser(string userName, UserPasswordViewModel user_view_model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (string.IsNullOrWhiteSpace(user_view_model.Password))
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, "取消變更")));
            }

            if (userName != user_view_model.UserName)
            {
                return(BadRequest());
            }

            //把資料庫中的那筆資料讀出來
            var user_db = db.Users.Find(userName);

            if (user_db == null)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!")));
            }
            else
            {
                try
                {
                    user_db.Password = user_view_model.Password;
                    //db.Entry(user_db).OriginalValues["Timestamp"] = Convert.FromBase64String(user_view_model.TimestampString);
                    db.SaveChanges();

                    //寫入AccessLog
                    MPAccessLog.WriteEntry(User.Identity.Name, AccessAction.PasswordChanged, "User", user_db.UserName);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExists(userName))
                    {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!"));
                    }
                    else
                    {
                        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, "這筆資料已被其他人修改!"));// ""
                    }
                }
            }

            return(Ok(ToUserViewModel(user_db)));
        }
Example #13
0
        public async Task ChangePassword(int id, UserPasswordViewModel userPass)
        {
            var user = await _context.Users.FindAsync(id);

            if (!(CheckPassword(userPass.OldPassword, user.PasswordHash, user.PasswordSalt)))
            {
                throw new Exception("Password Denied");
            }

            CreatePassword(userPass.NewPassword, out byte[] passwordHash, out byte[] passwordSalt);
            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            await _context.SaveChangesAsync();
        }
Example #14
0
        public async Task <ActionResult> ChangePassword(UserPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid Request"));
            }

            var result = await _userService.ChangePassword(model);

            if (!string.IsNullOrEmpty(result))
            {
                return(StatusCode((int)HttpStatusCode.NotAcceptable, result));
            }
            return(Ok());
        }
Example #15
0
        public async Task <ActionResult <BaseResponse> > Password(UserPasswordViewModel req)
        {
            BaseResponse br = new BaseResponse();

            if (req.Password != req.PasswordAgain)
            {
                br.Success = false;
                br.Message = "两次输入的密码不一致";
                return(br);
            }
            var Id = Convert.ToInt32(User.Claims.FirstOrDefault(a => a.Type == "Id").Value);

            br = await _us.UpdateUserPasswordAsync(req, Id);

            return(br);
        }
        public ActionResult _PasswordEdit(UserPasswordViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentException("bad request");
            }

            UserManager.RemovePassword(model.UserId);
            var result = UserManager.AddPassword(model.UserId, model.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction("list"));
            }

            AddErrors(result);
            return(RedirectToAction("EditCredentials", new { @id = model.UserId }));
        }
        public HttpResponseMessage Post(UserPasswordViewModel userViewModel, System.Security.Principal.IPrincipal user)
        {
            var db = new ApplicationDbContext();

            db.Configuration.ProxyCreationEnabled = false;
            if (IsNotAuthorized(db, user.Identity.Name))
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

            if (!db.Users.Any(u => u.UserName == userViewModel.username))
            {
                var appUser = new ApplicationUser {
                    UserName = userViewModel.username
                };

                IdentityResult result = userManager.Create(appUser, userViewModel.password);

                if (!result.Succeeded)
                {
                    return(Request.CreateResponse(GetErrorResult(result)));
                }
                if (userViewModel.IsADMIN)
                {
                    userManager.AddToRole(appUser.Id, "ADMIN");
                }
                if (userViewModel.IsPAGE_1)
                {
                    userManager.AddToRole(appUser.Id, "PAGE_1");
                }
                if (userViewModel.IsPAGE_2)
                {
                    userManager.AddToRole(appUser.Id, "PAGE_2");
                }
                if (userViewModel.IsPAGE_3)
                {
                    userManager.AddToRole(appUser.Id, "PAGE_3");
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public async Task <IActionResult> UserPassword(UserPasswordViewModel userPasswordViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(userPasswordViewModel));
            }

            // ------- get user object from the storage
            var applicationUser = await _userManager.GetUserAsync(User);



            if (applicationUser?.Email == userPasswordViewModel.Email)
            {
                var result = await _userManager.CheckPasswordAsync(applicationUser, userPasswordViewModel.Password);

                if (result)
                {
                    var changePasswordResult = await _userManager.ChangePasswordAsync(applicationUser, userPasswordViewModel.Password, userPasswordViewModel.NewPassword);

                    if (changePasswordResult.Succeeded)
                    {
                        return(RedirectToAction(nameof(UserPasswordConfirm)));
                    }
                    else
                    {
                        return(BadRequest());
                    }
                }
                else
                {
                    ModelState.TryAddModelError("", "your credentials are incorrect");

                    return(View(userPasswordViewModel));
                }
            }


            ModelState.TryAddModelError("", "your credentials are incorrect");

            return(View(userPasswordViewModel));
        }
        public ActionResult LogOn(UserPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Message = Resources.Resource.ERROR_WrongPassword;
                return(View("ErrorView"));
            }

            var userRepo = new UsersRepository();
            var user     = userRepo.ValidateUser(model.Login, model.Password);

            if (user == null)
            {
                ViewBag.Message = Resources.Resource.ERROR_WrongPassword;
                return(View("ErrorView"));
            }

            FormsAuthentication.SetAuthCookie(user.Login, true);
            return(RedirectToAction("Rating", "User"));
        }
 public HttpResponseMessage Put(string id, [FromBody] UserPasswordViewModel user)
 {
     return(Put(id, user, User));
 }
        public HttpResponseMessage Put(string id, UserPasswordViewModel userViewModel, System.Security.Principal.IPrincipal user)
        {
            var db = new ApplicationDbContext();

            db.Configuration.ProxyCreationEnabled = false;
            if (IsNotAuthorized(db, user.Identity.Name))
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            UserStore <ApplicationUser>   store       = new UserStore <ApplicationUser>(db);
            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(store);

            var appUser = db.Users.Include("Roles").SingleOrDefault(u => u.UserName == id);

            if (appUser != null)
            {
                if (appUser.UserName != userViewModel.username)
                {
                    appUser.UserName = userViewModel.username;
                }
                if (userViewModel.password == null || userViewModel.password.Length < 6)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password format"));
                }
                PasswordVerificationResult verificationResult = userManager.PasswordHasher.VerifyHashedPassword(appUser.PasswordHash, userViewModel.password);

                if (verificationResult == PasswordVerificationResult.Failed)
                {
                    string hashedNewPassword = userManager.PasswordHasher.HashPassword(userViewModel.password);
                    store.SetPasswordHashAsync(appUser, hashedNewPassword);
                }

                if (userViewModel.IsADMIN && !appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.ADMIN))
                {
                    userManager.AddToRole(appUser.Id, "ADMIN");
                }
                else if (!userViewModel.IsADMIN && appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.ADMIN))
                {
                    userManager.RemoveFromRole(appUser.Id, "ADMIN");
                }
                if (userViewModel.IsPAGE_1 && !appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_1))
                {
                    userManager.AddToRole(appUser.Id, "PAGE_1");
                }
                else if (!userViewModel.IsPAGE_1 && appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_1))
                {
                    userManager.RemoveFromRole(appUser.Id, "PAGE_1");
                }
                if (userViewModel.IsPAGE_2 && !appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_2))
                {
                    userManager.AddToRole(appUser.Id, "PAGE_2");
                }
                else if (!userViewModel.IsPAGE_2 && appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_2))
                {
                    userManager.RemoveFromRole(appUser.Id, "PAGE_2");
                }
                if (userViewModel.IsPAGE_3 && !appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_3))
                {
                    userManager.AddToRole(appUser.Id, "PAGE_3");
                }
                else if (!userViewModel.IsPAGE_3 && appUser.Roles.Any(r => r.RoleId == AspNetRolesEnum.PAGE_3))
                {
                    userManager.RemoveFromRole(appUser.Id, "PAGE_3");
                }

                store.UpdateAsync(appUser);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Example #22
0
 public Result <bool> ChangePassword([FromBody] UserPasswordViewModel password)
 {
     return(_manager.ChangePassword(_requestAttributes.Id, password));
 }
 public HttpResponseMessage Post([FromBody] UserPasswordViewModel userViewModel)
 {
     return(Post(userViewModel, User));
 }