コード例 #1
0
        public async Task <IActionResult> Edit(string id, string email, string password)
        {
            AppUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                user.Email = email;
                IdentityResult validEmail = await userValidator.ValidateAsync(userManager, user);

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                }
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, user, password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, password);
                    }
                    else
                    {
                        AddErrorsFromResult(validPass);
                    }
                }
                if ((validEmail.Succeeded && validPass == null) || (validEmail.Succeeded && password != string.Empty && validPass.Succeeded))
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user));
        }
コード例 #2
0
        public async Task <IActionResult> Edit(string Id, string Password, string Email)
        {
            var user = await userManager.FindByIdAsync(Id);

            if (user != null)
            {
                user.Email = Email;
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(Password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, user, Password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, Password);
                    }
                    else
                    {
                        foreach (var item in validPass.Errors)
                        {
                            ModelState.AddModelError("", item.Description);
                        }
                    }
                }
                if (validPass.Succeeded)
                {
                    var result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        foreach (var item in result.Errors)
                        {
                            ModelState.AddModelError("", item.Description);
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user));
        }
コード例 #3
0
        public async Task <IActionResult> Edit(string id, string Password)
        {
            IdentityUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(Password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, user, Password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, Password);
                    }
                    else
                    {
                        Errors(validPass);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Password cannot be empty");
                }

                if (validPass != null && validPass.Succeeded)
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        Errors(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }

            return(View(user));
        }
コード例 #4
0
    async Task <string> GeneratePassword()
    {
        var dummyUser = new MawUser();

        // limit to 100 tries
        for (int i = 0; i < 100; i++)
        {
            var password = CryptoUtils.GeneratePassword(12);
            var isValid  = await _pwdValidator.ValidateAsync(_userMgr, dummyUser, password);

            if (isValid == IdentityResult.Success)
            {
                return(password);
            }
        }

        throw new InvalidOperationException();
    }
コード例 #5
0
        /// <summary>
        ///     Changes the password.
        /// </summary>
        /// <param name="changeUserPasswordModel">The change password model.</param>
        /// <returns>
        ///     <see cref="Task" />
        /// </returns>
        public async Task ChangeUserPassword(ChangeUserPasswordModel changeUserPasswordModel)
        {
            var user = await _userManager.FindByIdAsync(changeUserPasswordModel.Id);

            if (user == null)
            {
                throw new NotFoundException();
            }

            var result =
                await _passwordValidator.ValidateAsync(_userManager, user, changeUserPasswordModel.NewPassword);

            result.Verify();

            result = await _userManager.ChangePasswordAsync(user, changeUserPasswordModel.CurrentPassword,
                                                            changeUserPasswordModel.NewPassword);

            result.Verify();
        }
コード例 #6
0
        public async Task <IActionResult> Edit(UserViewModel model)
        {
            AppUser user = await userManager.FindByIdAsync(model.Id);

            if (user == null)
            {
                ModelState.AddModelError("", "User Not Found");
                return(View(model));
            }
            if (ModelState.IsValid)
            {
                user.UserName = model.Username;
                user.Email    = model.Email;
                //var modelValidatorResult= await userValidator.ValidateAsync(userManager, user);

                // if (!modelValidatorResult.Succeeded)
                // {
                //     AddModelError(modelValidatorResult);

                // }

                var passwordValidateResult = await passwordValidator.ValidateAsync(userManager, user, model.Password);

                if (!passwordValidateResult.Succeeded)
                {
                    AddModelError(passwordValidateResult);
                }
                user.PasswordHash = passwordHasher.HashPassword(user, model.Password);


                IdentityResult result = await userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    AddModelError(result);
                }
            }
            return(View(model));
        }
コード例 #7
0
        /// <summary>
        /// Generates password for user. Generating until random password is valid against specified password policy or until it reaches max retries
        /// </summary>
        /// <param name="appUser">User</param>
        /// <returns>Generated password or null if reaches maximum number of retries</returns>
        private async Task <string> GeneratePasswordForUserAsync(ApplicationUser appUser)
        {
            var generateRetries = 0;

            while (generateRetries <= m_maxGeneratePasswordRetries)
            {
                var password   = m_userManager.GeneratePassword().Result;
                var passResult = await m_passwordManager.ValidateAsync(m_identityUserManager, appUser, password);

                if (passResult.Succeeded)
                {
                    return(password);
                }

                generateRetries++;
            }

            return(null);
        }
コード例 #8
0
        public async Task <ApiResult> ChangePassword(ChangePasswordDto model)
        {
            var userId = HttpContext.User.Identity.GetUserId <int>();
            var user   = await _userManager.FindByIdAsync(userId.ToString());

            var validOldPass = await _passwordValidator.ValidateAsync(_userManager, user, model.OldPassword);

            if (!validOldPass.Succeeded)
            {
                return(BadRequest("رمز عبور قبلی معتبر نمی باشد"));
            }

            if (!model.NewPassword.Equals(model.ConfirmPassword))
            {
                return(BadRequest("رمز عبور و تایید آن برابر نیست"));
            }

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

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            await _userManager.UpdateSecurityStampAsync(user);

            //var resultPass = await _passwordValidator.ValidateAsync(_userManager, user, model.OldPassword);

            await _signInManager.RefreshSignInAsync(user);

            // await _emailSender.SendEmailAsync(
            //     user.Email,
            //     "اطلاع رسانی تغییر کلمه‌ی عبور",
            //     "~/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
            //     new ChangePasswordNotificationViewModel
            //     {
            //         User = user,
            //         EmailSignature = _siteOptions.Value.Smtp.FromName,
            //         MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
            //     });

            return(Ok());
        }
コード例 #9
0
        public CreatePasswordCommandValidator(IConfirmationService confirmation, IPasswordValidator validator)
        {
            RuleFor(x => x)
            .CustomAsync(async(command, context, ct) =>
            {
                var data = await confirmation.GetAsync(command.ConfirmationId, ct);
                if (data is null)
                {
                    context.AddFailure(
                        new ValidationFailure(nameof(CreatePasswordCommand.ConfirmationCode), "Not found")
                    {
                        ErrorCode = ElwarkExceptionCodes.ConfirmationNotFound
                    });

                    return;
                }

                if (data.Code != command.ConfirmationCode)
                {
                    context.AddFailure(
                        new ValidationFailure(nameof(CreatePasswordCommand.ConfirmationCode), "Not match")
                    {
                        ErrorCode = ElwarkExceptionCodes.ConfirmationNotMatch
                    });
                }
            });

            RuleFor(x => x.Password)
            .NotEmpty()
            .CustomAsync(async(password, context, token) =>
            {
                var(isSuccess, error) = await validator.ValidateAsync(password, token);
                if (!isSuccess)
                {
                    context.AddFailure(
                        new ValidationFailure(nameof(SignUpByEmailCommand.Password), "Incorrect password")
                    {
                        ErrorCode = error
                    }
                        );
                }
            });
        }
コード例 #10
0
        public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await _userManager.FindByIdAsync(model.Id);

                if (user != null)
                {
                    IPasswordValidator <User> passwordValidator =
                        HttpContext.RequestServices.GetService(typeof(IPasswordValidator <User>)) as IPasswordValidator <User>;
                    IPasswordHasher <User> passwordHasher =
                        HttpContext.RequestServices.GetService(typeof(IPasswordHasher <User>)) as IPasswordHasher <User>;

                    if (passwordValidator != null)
                    {
                        IdentityResult result =
                            await passwordValidator.ValidateAsync(_userManager, user, model.NewPassword);

                        if (result.Succeeded)
                        {
                            if (passwordHasher != null)
                            {
                                user.PasswordHash = passwordHasher.HashPassword(user, model.NewPassword);
                            }

                            await _userManager.UpdateAsync(user);

                            return(RedirectToAction("Index", "Account"));
                        }

                        foreach (IdentityError error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "User not found.");
                }
            }
            return(View(model));
        }
コード例 #11
0
        public async Task <IActionResult> EditUser(string id, string PasswordHash, string email)
        {
            UserEntity userEntity = new UserEntity();

            if (ModelState.IsValid)
            {
                userEntity = await _userManager.FindByIdAsync(id);

                var validPass = await _passwordValidator.ValidateAsync(_userManager, userEntity, PasswordHash);

                if (validPass.Succeeded)
                {
                    userEntity.PasswordHash = _passwordHasher.HashPassword(userEntity, PasswordHash);
                    //userEntity.ModUser = (await CurrentUser).UserName; TODO
                    userEntity.ModDate = DateTime.Now;
                    var result = await _userManager.UpdateAsync(userEntity);

                    if (result.Succeeded)
                    {
                        RedirectToAction("UserList");
                    }
                    else
                    {
                        foreach (var item in result.Errors)
                        {
                            ModelState.AddModelError("", item.Description);
                        }
                    }
                }
                else
                {
                    foreach (var item in validPass.Errors)
                    {
                        ModelState.AddModelError("", item.Description);
                    }
                    return(RedirectToAction("EditUser", userEntity));
                }

                return(RedirectToAction("UserList"));
            }

            return(View(userEntity));
        }
コード例 #12
0
            public async Task <ValidatePasswordResult> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await _userManager.FindByEmailAsync(request.Email);

                if (user == null)
                {
                    throw new Exception("The email is not valid.");
                }

                var result = await _passwordValidator.ValidateAsync(
                    (UserManager <AppUser>) _userManager, user, request.Password);

                var errorDesc = result.Succeeded ? "" : string.Join("/n", result.Errors.Select(c => c.Description).ToList());

                return(new ValidatePasswordResult
                {
                    ErrorDescription = errorDesc,
                    Success = result.Succeeded
                });
            }
コード例 #13
0
        public async Task <IActionResult> ChangePassword(PasswordChangeViewModel pcVM)
        {
            if (!ModelState.IsValid)
            {
                return(View(pcVM));
            }

            IdentityUser currUser = await _userManager.GetUserAsync(User);

            bool truePassword = await _userManager.CheckPasswordAsync(currUser, pcVM.OldPassword);

            if (!truePassword)
            {
                ModelState.AddModelError("", "Неправильный старый пароль");
                return(View(pcVM));
            }

            if (pcVM.NewPassword != pcVM.RepeatNewPassword)
            {
                ModelState.AddModelError("", "Пароли не совпадают");
                return(View(pcVM));
            }

            IdentityResult result = await _passwordValidator.ValidateAsync(_userManager, currUser, pcVM.NewPassword);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Новый пароль не соответствует требованиям");
                return(View(pcVM));
            }

            result = await _userManager.ChangePasswordAsync(currUser, pcVM.OldPassword, pcVM.NewPassword);

            if (!result.Succeeded)
            {
                ModelState.AddModelError("", "Произошла ошибка, повторите попытку");
                return(View(pcVM));
            }

            return(RedirectToAction("Index", "PersonalAccount"));
        }
コード例 #14
0
      public async Task <IActionResult> UserInfo(UserInfoViewModel entry)
      {
          AppUser user = await userManager.GetUserAsync(User);

          if (user != null)
          {
              IdentityResult validPass = null;
              if (!string.IsNullOrEmpty(entry.NewPassword))
              {
                  validPass = await passwordValidator.ValidateAsync(userManager, user, entry.NewPassword);

                  if (validPass.Succeeded)
                  {
                      user.PasswordHash = passwordHasher.HashPassword(user, entry.NewPassword);
                  }
                  else
                  {
                      Errors(validPass);
                  }
              }
              else
              {
                  ModelState.AddModelError("", "Password cannot be empty");
              }

              if (!string.IsNullOrEmpty(entry.NewPassword) && validPass.Succeeded)
              {
                  IdentityResult result = await userManager.UpdateAsync(user);

                  if (result.Succeeded)
                  {
                      return(RedirectToAction(nameof(UserInfo)));
                  }
                  else
                  {
                      Errors(result);
                  }
              }
          }
          return(View(user));
      }
コード例 #15
0
        public async Task <IActionResult> Update(UpdateValidtor validtor)
        {
            var user = await userManager.FindByIdAsync(validtor.Id);

            if (user != null)
            {
                user.Email = validtor.Email;
                IdentityResult myresult = null;
                if (!string.IsNullOrEmpty(validtor.Password))
                {
                    myresult = await passwordValidator.ValidateAsync(userManager, user, validtor.Password);

                    if (myresult.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, validtor.Password);
                    }
                    else
                    {
                        ErrorList(myresult);
                    }
                }
                if (myresult.Succeeded)
                {
                    var resulte = await userManager.UpdateAsync(user);

                    if (resulte.Succeeded)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        ErrorList(resulte);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Usern not found");
            }
            return(View(user));
        }
コード例 #16
0
        //If the password can't pass validation, the user object is returned with PasswordHash property
        //not set. Also, the ModelState Controller property is populated with validation errors.
        private async Task <AppUser> AddPasswordHashToUserAsync(AppUser user, string password)
        {
            IdentityResult result;

            if (!string.IsNullOrEmpty(password))
            {
                result = await passwordValidator.ValidateAsync(userManager, user, password);

                if (result.Succeeded)
                {
                    user.PasswordHash = passwordHasher.HashPassword(user, password);
                }
                else
                {
                    //ModelState is available through Controller context, so
                    //you don't need to return it to the calling method.
                    AddModelStateErrors(result);
                }
            }
            return(user);
        }
コード例 #17
0
        public UpdatePasswordCommandValidator(IPasswordValidator validator)
        {
            RuleFor(x => x.OldPassword)
            .NotEmpty();

            RuleFor(x => x.NewPassword)
            .NotEmpty()
            .CustomAsync(async(password, context, token) =>
            {
                var(isSuccess, error) = await validator.ValidateAsync(password, token);
                if (!isSuccess)
                {
                    context.AddFailure(
                        new ValidationFailure(nameof(SignUpByEmailCommand.Password), "Incorrect password")
                    {
                        ErrorCode = error
                    }
                        );
                }
            });
        }
コード例 #18
0
        public async Task <IActionResult> Edit(EditEmployeeModel editEmployeeModel)
        {
            var employeeUser = await userManager.FindByIdAsync(editEmployeeModel.EmployeeUser.Id);

            var employee = editEmployeeModel.Employee;

            if (!employee.EmployeeId.ToString().Equals(employeeUser.UserName))
            {
                return(View(editEmployeeModel));
            }
            if (!string.IsNullOrEmpty(editEmployeeModel.Password))
            {
                var validPass = await passwordValidator.ValidateAsync(userManager, employeeUser, editEmployeeModel.Password);

                if (validPass.Succeeded)
                {
                    employeeUser.PasswordHash =
                        passwordHasher.HashPassword(employeeUser, editEmployeeModel.Password);
                }
                else
                {
                    AddErrorsFromResult(validPass);
                }
            }

            repository.EditEmployee(employee);
            IdentityResult result = await userManager.UpdateAsync(employeeUser);

            if (result.Succeeded)
            {
                return(View("Index", new ViewEmployeesModel
                {
                    EmployeeUsers = userManager.Users,
                    Employees = repository.Employees
                }));
            }
            AddErrorsFromResult(result);

            return(View(editEmployeeModel));
        }
コード例 #19
0
        public async Task <IActionResult> UpdateUser([FromBody] RegisterViewModel registerView)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(registerView.Id);

                if (user != null)
                {
                    user.Email          = registerView.Email;
                    user.UserName       = registerView.Email;
                    user.IdentityNumber = registerView.IdentityNumber;
                    user.NameSurname    = registerView.NameSurname;

                    if (registerView.CompanyId != 0)
                    {
                        var comp = _companyRepository.GetCompany(registerView.CompanyId);
                        user.Company = comp;
                    }

                    if (registerView.Password != null)
                    {
                        IdentityResult validResult = await _passwordValidator.ValidateAsync(_userManager, user, registerView.Password);

                        if (validResult.Succeeded)
                        {
                            user.PasswordHash = _passwordHasher.HashPassword(user, registerView.Password);
                        }
                    }

                    var result = await _userManager.UpdateAsync(user);

                    return(Ok(registerView));
                }
                return(BadRequest("Böyle bir kullanıcı bulunmamaktadır"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #20
0
        public async Task <IActionResult> EditUser(string id, EditUserModel editUserModel)
        {
            User user = await userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NoContent());
            }

            user.UserName = editUserModel.Name;
            user.Email    = editUserModel.Email;

            IdentityResult identityResult = await userValidator.ValidateAsync(userManager, user);

            if (!identityResult.Succeeded ||
                string.IsNullOrEmpty(editUserModel.NewPassword))
            {
                return(BadRequest());
            }

            var checkPasswordHash = await userManager.CheckPasswordAsync(user, editUserModel.Password);

            if (!checkPasswordHash)
            {
                return(BadRequest());
            }

            var validPass = await passwordValidator.ValidateAsync(userManager, user, editUserModel.NewPassword);

            if (!validPass.Succeeded)
            {
                return(BadRequest());
            }

            user.PasswordHash = passwordHasher.HashPassword(user, editUserModel.NewPassword);

            await userManager.UpdateAsync(user);

            return(Ok());
        }
コード例 #21
0
        public static async Task <IdentityResult> CustomValidateAsync(this IPasswordValidator <VesizleUser> validator,
                                                                      UserManager <VesizleUser> userManager, VesizleUser user, string password)
        {
            var identityResult = await validator.ValidateAsync(userManager, user, password);

            List <IdentityError> errors = identityResult.Succeeded ? new List <IdentityError>() : identityResult.Errors.ToList();

            if (password.ToLower().Contains(user.UserName.ToLower()))
            {
                errors.Add(new IdentityError
                {
                    Description = "Password cannot contain username"
                });
            }
            if (password.Contains("123"))
            {
                errors.Add(new IdentityError
                {
                    Description = "Password cannot contain 123 numeric sequence"
                });
            }
            return(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
        }
コード例 #22
0
 public IActionResult SignIn(SignInModel model)
 {
     if (ModelState.IsValid)
     {
         try
         {
             var user = _userManeger.FindByEmailAsync(model.Email).Result;
             if (user != null)
             {
                 var result = _pswValidator.ValidateAsync(_userManeger, user, model.Password);
                 if (result.Result.Succeeded)
                 {
                     _maneger.SignInAsync(user, true).GetAwaiter().GetResult();
                 }
             }
         }
         catch
         {
             throw new Exception("SignIN ugursuzdur");
         }
     }
     return(RedirectToAction("Index", "Home", new { Area = "null" }));
 }
コード例 #23
0
        public async Task <IActionResult> Login(LoginModel login)
        {
            if (!ModelState.IsValid)
            {
                return(View(nameof(Login)));
            }

            AppUser currentuser = await userManager.FindByEmailAsync(login.Email);

            var pass = await validator.ValidateAsync(userManager, currentuser, login.Password);

            if (currentuser != null && pass.Succeeded)
            {
                if (await signInManager.UserManager.IsInRoleAsync(currentuser, "Admin"))
                {
                    return(Content("Admin"));
                }
                else
                {
                    return(Content("User"));
                }
                //NCV.SignInResult signInResult = await signInManager.PasswordSignInAsync(currentuser, login.Password, true, false);

                //if (signInResult.Succeeded)
                //{
                //    return RedirectToAction("Index", "Home");
                //}
                //else
                //{
                //    return View(nameof(Registr));
                //}
            }



            return(View());
        }
コード例 #24
0
        public async Task <IActionResult> Update(UserUpdate data)
        {
            var user = await _userManager.FindByIdAsync(data.Id);

            if (user != null)
            {
                user.Email = data.Email;
                IdentityResult identityResult = null;
                if (!string.IsNullOrEmpty(data.Password))
                {
                    identityResult = await passwordValidator.ValidateAsync(_userManager, user, data.Password);

                    if (identityResult.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, data.Password);
                    }
                    else
                    {
                        foreach (IdentityError item in identityResult.Errors)
                        {
                            ModelState.AddModelError("", item.Description);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(data.UserName))
                {
                    identityResult = await _userManager.SetUserNameAsync(user, data.UserName);
                }
                if (identityResult.Succeeded)
                {
                    await _userManager.UpdateAsync(user);

                    return(RedirectToAction("Index"));
                }
            }
            return(View(data));
        }
コード例 #25
0
ファイル: AdminController.cs プロジェクト: aeson85/Users
        public async Task <IActionResult> Edit(string id, string email, string password)
        {
            var appUser = await _userManager.FindByIdAsync(id);

            if (appUser != null)
            {
                appUser.Email = email;
                var userValiResult = await _userValidator.ValidateAsync(_userManager, appUser);

                IdentityResult passValiResult = null;
                if (!string.IsNullOrEmpty(password))
                {
                    passValiResult = await _passValidator.ValidateAsync(_userManager, appUser, password);

                    if (passValiResult.Succeeded)
                    {
                        appUser.PasswordHash = _passHasher.HashPassword(appUser, password);
                    }
                    else
                    {
                        AddErrorToModelState(passValiResult);
                    }
                }
                if (userValiResult.Succeeded && (passValiResult?.Succeeded ?? true))
                {
                    await _userManager.UpdateAsync(appUser);

                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                ModelState.AddModelError("", "User not found");
            }
            return(View(appUser));
        }
コード例 #26
0
        public async Task <string> Login(LoginModel loginModel)
        {
            var currentuser = await _userManager.FindByEmailAsync(loginModel.Email);

            var checkPass = _passwordValidator.ValidateAsync(_userManager, currentuser, loginModel.Password);

            if (checkPass != null && checkPass.Result.Succeeded)
            {
                SignInNS.SignInResult signInResult = await _signInManager.PasswordSignInAsync(currentuser, loginModel.Password, true, false);

                if (signInResult.Succeeded)
                {
                    return("Sing Prosses is okey");
                }
                else
                {
                    return("Email or Password  incorrect");
                }
            }
            else
            {
                return("Email or Password  incorrect");
            }
        }
コード例 #27
0
        //public async Task<IActionResult> Edit(string username, string email, string password, IFormFile image)
        public async Task <IActionResult> Edit(EditModel newedit)
        {
            AppUser user = await userManager.FindByNameAsync(User.Identity.Name);

            //Console.WriteLine("PROFILE: " + newedit.Name + newedit.Email + newedit.Password + newedit.ImageFile.FileName);
            if (newedit.ImageFile != null)
            {
                //Console.WriteLine("PROFILE: " + newedit.ImageFile.FileName);
                string wwwRootPath = hostEnvironment.WebRootPath;
                string fileName    = Path.GetFileNameWithoutExtension(newedit.ImageFile.FileName);
                string extension   = Path.GetExtension(newedit.ImageFile.FileName);
                fileName       = fileName + DateTime.Now.ToString("yymmss") + extension;
                user.ImageName = fileName;
                string path = Path.Combine(wwwRootPath + "/Image/", fileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await newedit.ImageFile.CopyToAsync(fileStream);
                }
            }

            if (user != null)
            {
                user.UserName = newedit.Name;
                user.Email    = newedit.Email;
                IdentityResult validEmail
                    = await userValidator.ValidateAsync(userManager, user);

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                }
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(newedit.Password))
                {
                    validPass = await passwordValidator.ValidateAsync(userManager,
                                                                      user, newedit.Password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user,
                                                                        newedit.Password);
                    }
                    else
                    {
                        AddErrorsFromResult(validPass);
                    }
                }
                if ((validEmail.Succeeded && validPass == null) ||
                    (validEmail.Succeeded &&
                     newedit.Password != string.Empty && validPass.Succeeded))
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View("~/Views/Identity/Account/Edit.cshtml", user));
        }
コード例 #28
0
        public async Task <IActionResult> UpdateUser(string userId, string newEmail, string password, string roleName)
        {
            AppUser appUser = await userManager.FindByIdAsync(userId);

            AppRole appRole = await roleManager.FindByNameAsync(roleName);

            if (appUser != null)
            {
                if (newEmail != null)
                {
                    appUser.Email = newEmail;
                }
                if (appRole != null)
                {
                    await userManager.AddToRoleAsync(appUser, appRole.Name);

                    appUser.RoleName = appRole.Name;
                }

                IdentityResult identityResultEmail = await userValidator.ValidateAsync(userManager, appUser);

                if (identityResultEmail.Succeeded)
                {
                    //There is nothing to do, the email has been changed early
                }
                else
                {
                    AddErrorsFormResult(identityResultEmail);
                }

                IdentityResult identityResultPassword = null;

                if (string.IsNullOrEmpty(password))
                {
                    //There is nothing to do, the password will be left previous
                }
                else
                {
                    identityResultPassword = await passwordValidator.ValidateAsync(userManager, appUser, password);

                    if (identityResultPassword.Succeeded)
                    {
                        appUser.PasswordHash = passwordHasher.HashPassword(appUser, password);
                    }
                    else
                    {
                        AddErrorsFormResult(identityResultPassword);
                    }
                }

                if ((identityResultEmail.Succeeded && identityResultPassword == null) ||
                    (identityResultEmail.Succeeded && identityResultPassword.Succeeded && password != string.Empty))
                {
                    IdentityResult identityResult = await userManager.UpdateAsync(appUser);

                    if (identityResult.Succeeded)
                    {
                        return(RedirectToAction(nameof(Index)));
                    }
                    else
                    {
                        AddErrorsFormResult(identityResult);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }

            return(View(nameof(Index), userManager.Users));
        }
コード例 #29
0
        public async Task <IdentityResult> ValidatePassword(UserModel user, string password)
        {
            var appUser = _mapper.Map <AppUser, UserModel>(user);

            return(await _passwordValidator.ValidateAsync(_repository.GetUserManager(), appUser, password));
        }
コード例 #30
0
        public async Task <IActionResult> Edit(string id, string email,
                                               string password)
        {
            User user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                user.Email = email;
                IdentityResult validEmail
                    = await userValidator.ValidateAsync(userManager, user);

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                }
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(password))
                {
                    var validNewPass = await passwordValidator.ValidateAsync(userManager, user, password);

                    if (validNewPass.Succeeded)
                    {
                        await userManager.RemovePasswordAsync(user);

                        await userManager.AddPasswordAsync(user, password);

                        ViewBag.Message = "Password Updated";
                    }
                    else
                    {
                        ViewBag.Message = "An Error Has Occured: ";
                        foreach (IdentityError s in validNewPass.Errors.ToList())
                        {
                            ViewBag.Message += s.Description + " ";
                        }

                        return(View(user));
                    }
                }
                if ((validEmail.Succeeded && validPass == null) ||
                    (validEmail.Succeeded &&
                     password != string.Empty && validPass.Succeeded))
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        ViewBag.Message = "Account Updated!";

                        return(View("ViewUsers", userManager.Users));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            ViewBag.Message = "An Error has Occured, Please Try Again";

            return(View(user));
        }