コード例 #1
0
        public async Task <IActionResult> Edit(string id, string userName, string email, string password)
        {
            ApplicationUser user = await GetCurrentUserAsync();

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

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                }

                user.UserName = userName;
                IdentityResult validUserName = await userValidator.ValidateAsync(userManager, user);

                if (!validUserName.Succeeded)
                {
                    AddErrorsFromResult(validUserName);
                }



                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", "Home"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Utilizador nao encontrado!");
            }

            return(View(user));
        }
コード例 #2
0
        // создание заявки студента
        public async Task <OperationDetailDTO> CreateStudentRegisterRequestAsync(StudentRegisterDTO dto)
        {
            List <string> errorMessages = new List <string>();

            try
            {
                if (!UserValidator.Validate(dto, out errorMessages))
                {
                    return(new OperationDetailDTO {
                        Succeeded = false, ErrorMessages = errorMessages
                    });
                }
                if (await _context.StudentRegisterRequests.AnyAsync(x => x.UserName == dto.UserName) ||
                    await _context.TeacherRegisterRequests.AnyAsync(x => x.UserName == dto.UserName) ||
                    await _userManager.FindByNameAsync(dto.UserName) != null)
                {
                    errorMessages.Add("Пользователь с таким имененем пользователем уже существует. Пожалуйста, выберите другое.");
                    return(new OperationDetailDTO {
                        Succeeded = false, ErrorMessages = errorMessages
                    });
                }

                var testUser = new User
                {
                    Email        = dto.Email,
                    UserName     = dto.UserName,
                    PasswordHash = dto.Password
                };
                var userValidateRes = await _userValidator.ValidateAsync(_userManager, testUser);

                if (!userValidateRes.Succeeded)
                {
                    errorMessages.Add("Введенные данные не прошли валидацию. Подробнее далее.");
                    foreach (var error in userValidateRes.Errors.ToList())
                    {
                        errorMessages.Add(error.Description);
                    }
                    return(new OperationDetailDTO {
                        Succeeded = false, ErrorMessages = errorMessages
                    });
                }

                await _context.StudentRegisterRequests.AddAsync(GetStudentRegEntityFromDTO(dto));

                await _context.SaveChangesAsync();

                return(new OperationDetailDTO {
                    Succeeded = true
                });
            }
            catch (Exception e)
            {
                return(new OperationDetailDTO {
                    Succeeded = false, ErrorMessages = { _serverErrorMessage + e.Message }
                });
            }
        }
コード例 #3
0
        public async Task <IActionResult> EditUser(string id, [FromBody] EditUser model)
        {
            AppUser user = await _userManager.FindByNameAsync(id);

            if (user != null)
            {
                user.Email = model.Email;
                IdentityResult validEmail = await _userValidator.ValidateAsync(_userManager, user);

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                    return(BadRequest("Email not valid"));
                }
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(model.Password))
                {
                    validPass = await _passwordValidator.ValidateAsync(_userManager, user, model.Password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, model.Password);
                    }
                    else
                    {
                        AddErrorsFromResult(validPass);
                        return(BadRequest("Password not valid"));
                    }
                }
                if ((validEmail.Succeeded && validPass == null) ||
                    (validEmail.Succeeded &&
                     model.Password != string.Empty && validPass.Succeeded))
                {
                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(Ok("true"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                        return(BadRequest("Error in IdentiyResult"));
                    }
                }
                else
                {
                    return(BadRequest("Password or email invalid"));
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
                return(BadRequest("User not found"));
            }
        }
コード例 #4
0
        public async Task <IdentityResult> Put(string password, [FromBody] UserViewModel model)
        {
            User user = await _userManager.FindByIdAsync(model.Id);

            if (user != null)
            {
                user.UserName = model.Name;
                user.SurName  = model.SurName;
                user.Email    = model.Email;
                user.TimeZone = model.TimeZone;
                user.Language = model.Language;
                user.Balance  = model.Balance;

                var validEmail = await _userValidator.ValidateAsync(_userManager, user);

                if (!validEmail.Succeeded)
                {
                    return(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
                    {
                        return(validPass);
                    }
                }

                if ((validEmail.Succeeded && validPass == null) || (validEmail.Succeeded && password != string.Empty && validPass.Succeeded))
                {
                    var result = await _userManager.UpdateAsync(user);

                    return(result);
                }
            }

            var identityError = new IdentityError
            {
                Code        = "UpdateError",
                Description = "User not found",
            };

            return(IdentityResult.Failed(identityError));
        }
コード例 #5
0
        public async Task CreateAsync(User user, string password)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            await _userValidator.ValidateAsync(user, UserAction.Create);

            user.PasswordHash = _passwordHasher.HashPassword(user, password);

            _userRepository.Create(user);

            await _unitOfWork.SaveAsync();
        }
コード例 #6
0
        public async Task <JsonResult> ValidateUsername(string username)
        {
            AppUser user = await userManager.FindByNameAsync(username);

            if (user != null)
            {
                return(Json("This username is already taken."));
            }
            else
            {
                user = new AppUser {
                    UserName = username
                };
                IdentityResult result = await userValidator.ValidateAsync(userManager, user);

                if (result.Succeeded)
                {
                    return(Json(true));
                }
                else
                {
                    return(Json("Username is not valid."));
                }
            }
        }
コード例 #7
0
        public async Task <ActionResult> ChangeUserPassword([FromBody] ChangePasswordModel model)
        {
            User user = GetCurrentLoggedUser().Result;

            if (user.Email == model.Email)
            {
                user.PasswordHash = _passwordHasher.HashPassword(user, model.Password);
                IdentityResult validPass = await _userValidator.ValidateAsync(_userManager, user);

                if (validPass.Succeeded)
                {
                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(Ok());
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
                else
                {
                    return(BadRequest(validPass.Errors));
                }
            }
            return(BadRequest("Wrong Email"));
        }
コード例 #8
0
        public async Task <(bool saved, IEnumerable <string> errors)> SaveUserProfile(ClaimsPrincipal loggedInUser, string email, string phoneNumber)
        {
            var user = await GetUserOrThrow(loggedInUser);

            user.Email       = email;
            user.PhoneNumber = phoneNumber;

            var result = await _userValidator.ValidateAsync(userManager, user);

            if (result.Succeeded)
            {
                var saved = await _uow.CommitAsync();

                if (saved)
                {
                    await signInManager.RefreshSignInAsync(user);

                    logger.LogInformation("User successfully saved changes to profile for user ID '{userId}'", loggedInUser.GetUserId());

                    return(saved, Enumerable.Empty <string>());
                }

                logger.LogError("A general error occurred while trying to save a user profile for User ID '{userId}'.", loggedInUser.GetUserId());
                return(false, new List <string> {
                    "A general error occurred while saving to the database."
                });
            }

            return(false, result.Errors.Select(x => x.Description));
        }
コード例 #9
0
        public static User Create(
            IUserValidator userValidator,
            IUserPasswordService userPasswordService,
            string email,
            string displayName,
            string plainPassword,
            string postalCode,
            int timeZoneId)
        {
            AsyncHelper.RunSync(() => userValidator.ValidateAsync(null, email, displayName, plainPassword, postalCode));

            byte[] passwordHash;
            byte[] passwordSalt;
            userPasswordService.CreateHash(plainPassword, out passwordHash, out passwordSalt);

            var user = new User
            {
                Id             = Guid.NewGuid(),
                Email          = email,
                DisplayName    = displayName,
                PasswordHash   = passwordHash,
                PasswordSalt   = passwordSalt,
                PostalCode     = postalCode,
                UserTimeZoneId = timeZoneId
            };

            return(user);
        }
コード例 #10
0
        public async Task <IActionResult> EditUser(string id, string email, string password, string firstName, string lastName, string address,
                                                   string city, string zip, string state)
        {
            AppUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                //user.Email = email;
                user.FirstName = firstName;
                user.LastName  = lastName;
                user.Address   = address;
                user.City      = city;
                user.Zip       = zip;
                user.State     = state;

                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("AdminUser"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user));
        }
コード例 #11
0
        public async Task <SaveResponse> SaveAsync(IUser user)
        {
            var response = new SaveResponse();

            try
            {
                var validateResponse = await _userValidator.ValidateAsync(user);

                if (validateResponse.IsValid)
                {
                    response = await _userRepository.SaveAsync(user);
                }
                else
                {
                    response.AddErrors(validateResponse.Errors);
                }
            }
            catch (Exception e)
            {
                response.AddError(e);
                Console.WriteLine(e);
            }

            return(response);
        }
コード例 #12
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user           = _mapper.Map <VesizleUser>(model);
                var identityResult = await _passwordValidator.ValidateAsync(_userManager, user, model.Password);

                if (identityResult.Succeeded)
                {
                    var validateResult = await _userValidator.ValidateAsync(_userManager, user);

                    if (validateResult.Succeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, model.Password);
                        var createResult = await _userManager.CreateAsync(user);

                        var roleAddResult = await _userManager.AddToRoleAsync(user, UserRoleNames.Standard);

                        if (createResult.Succeeded && roleAddResult.Succeeded)
                        {
                            return(RedirectToAction("Index", "Home"));
                        }
                        ModelState.AddIdentityError(createResult.Errors);
                        ModelState.AddIdentityError(roleAddResult.Errors);
                        return(View(model));
                    }
                    ModelState.AddIdentityError(validateResult.Errors);
                    return(View(model));
                }
                ModelState.AddIdentityError(nameof(model.Password), identityResult.Errors);
                return(View(model));
            }

            return(View(model));
        }
コード例 #13
0
        public async Task <IActionResult> Index(AppUserViewModel viewModel)
        {
            AppUser appUser = await userManager.GetUserAsync(User);

            appUser.UserName = viewModel.Name;
            appUser.Surname  = viewModel.Surname;

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

            if (result.Succeeded)
            {
                await userManager.UpdateAsync(appUser);
            }
            else
            {
                foreach (IdentityError error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

                return(View(viewModel));
            }

            return(RedirectToAction("Index", "Account"));
        }
コード例 #14
0
        public async Task <IActionResult> ValidateUsername(string username, string email)
        {
            var result = await _userValidator.ValidateAsync(
                (UserManager <User>) _userManager, new User { UserName = username, Email = email });

            return(Json(result.Succeeded ? "true" : result.DumpErrors(useHtmlNewLine: true)));
        }
コード例 #15
0
        public async Task <IActionResult> Edit(string id, string email, string password)
        {
            var user = await _userManager.FindByIdAsync(id);

            if (user != null)
            {
                if (string.IsNullOrWhiteSpace(email))
                {
                    ModelState.AddModelError("Email error", "Email is required!");
                }
                if (string.IsNullOrWhiteSpace(password))
                {
                    ModelState.AddModelError("Password error", "Password is required!");
                }
                if (!(string.IsNullOrWhiteSpace(email)) && !(string.IsNullOrWhiteSpace(password)))
                {
                    var userValidation = await _userValidator.ValidateAsync(_userManager, user);

                    if (userValidation.Succeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, password);
                    }
                    else
                    {
                        SetIdentityErrorsToModelState(userValidation.Errors);
                    }

                    var passwordValidation = await _passwordValidator.ValidateAsync(_userManager, user, password);

                    if (passwordValidation.Succeeded)
                    {
                        user.Email = email;
                    }
                    else
                    {
                        SetIdentityErrorsToModelState(passwordValidation.Errors);
                    }

                    if (userValidation.Succeeded && passwordValidation.Succeeded)
                    {
                        var result = await _userManager.UpdateAsync(user);

                        if (result.Succeeded)
                        {
                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            SetIdentityErrorsToModelState(result.Errors);
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User not found!");
            }

            return(View(user));
        }
コード例 #16
0
        async Task <bool> TryUpdateEmail(string email, AppUser appUser)
        {
            if (!string.IsNullOrEmpty(email))
            {
                IdentityResult validationResult = await _userValidator
                                                  .ValidateAsync(_userManager, appUser);

                if (validationResult.Succeeded)
                {
                    appUser.Email = email;
                    return(true);
                }
                else
                {
                    foreach (IdentityError err in validationResult.Errors)
                    {
                        ModelState.AddModelError("", err.Description);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Email cannot be empty");
            }
            return(false);
        }
コード例 #17
0
        public async Task <ApiResult <string> > ValidateUsername(string username, string email, string pid)
        {
            pid = _protectionProviderService.Decrypt(pid);
            if (string.IsNullOrWhiteSpace(pid))
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByIdAsync(pid);

            user.UserName = username;
            user.Email    = email;

            var result = await _userValidator.ValidateAsync((UserManager <User>) _userManager, user);

            return(result.DumpErrors(true));
        }
コード例 #18
0
        public async Task <IActionResult> ValidateUsername(string username, string email, string pid)
        {
            pid = _protectionProviderService.Decrypt(pid);
            if (string.IsNullOrWhiteSpace(pid))
            {
                return(Json("اطلاعات وارد شده معتبر نیست."));
            }

            var user = await _userManager.FindByIdAsync(pid);

            user.UserName = username;
            user.Email    = email;

            var result = await _userValidator.ValidateAsync((UserManager <User>) _userManager, user);

            return(Json(result.Succeeded ? "true" : result.DumpErrors(useHtmlNewLine: true)));
        }
コード例 #19
0
        public async Task <IActionResult> Edit(EditUserViewModel _user)
        {
            AppUser user = await userManager.FindByIdAsync(_user.Id);

            if (user != null)
            {
                //validate Email
                user.Email = _user.Email;
                IdentityResult emailResult = await userValidator.ValidateAsync(userManager, user);

                if (!emailResult.Succeeded)
                {
                    foreach (IdentityError err in emailResult.Errors)
                    {
                        ModelState.AddModelError("", err.Description);
                    }
                }
                //validate Password
                IdentityResult passwordResult = null;
                if (!string.IsNullOrEmpty(_user.Password))
                {
                    passwordResult = await passwordValidator.ValidateAsync(userManager, user, _user.Password);

                    if (passwordResult.Succeeded)
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, _user.Password);
                    }
                    else
                    {
                        foreach (IdentityError err in passwordResult.Errors)
                        {
                            ModelState.AddModelError("", err.Description);
                        }
                    }
                }
                if ((emailResult.Succeeded && passwordResult == null) || (emailResult.Succeeded && _user.Password != string.Empty && passwordResult.Succeeded))
                {
                    IdentityResult result = await userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction(nameof(Index)));
                    }
                    else
                    {
                        foreach (IdentityError err in result.Errors)
                        {
                            ModelState.AddModelError("", err.Description);
                        }
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user));
        }
コード例 #20
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            ApplicationUser user = await userManager.FindByIdAsync(AppUserViewModel.ID);

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

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

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

                    if (result.Succeeded)
                    {
                        return(RedirectToPage("./Index"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "User Not Found");
                }
            }
            return(Page());
        }
コード例 #21
0
        public async Task <OperationDetailDTO> UpdateProfileDataAsync(StudentDTO newStudentDTO)
        {
            var detail = new OperationDetailDTO <TeacherDTO>();

            try
            {
                List <string> errorMessages = new List <string>();

                var currentUserEntity = await GetUserFromClaimsAsync();

                var studentUser = await _context.Users
                                  .Where(u => u.Id == currentUserEntity.Id)
                                  .FirstOrDefaultAsync();

                if (!UserValidator.Validate(newStudentDTO, out errorMessages))
                {
                    detail.ErrorMessages = errorMessages;
                    return(detail);
                }

                if (await _context.StudentRegisterRequests.AnyAsync(x => x.UserName == newStudentDTO.UserName) ||
                    await _context.TeacherRegisterRequests.AnyAsync(x => x.UserName == newStudentDTO.UserName) ||
                    newStudentDTO.UserName != studentUser.UserName && await _userManager.FindByNameAsync(newStudentDTO.UserName) != null)
                {
                    detail.ErrorMessages.Add("Пользователь с таким именем пользователя уже существует, подберите другое.");
                    return(detail);
                }

                if (studentUser != null)
                {
                    studentUser.Email    = newStudentDTO.Email;
                    studentUser.UserName = newStudentDTO.UserName;

                    var validateRes = _userValidator.ValidateAsync(_userManager, studentUser);
                    if (validateRes.Result.Succeeded)
                    {
                        await _userManager.UpdateNormalizedEmailAsync(studentUser);

                        await _userManager.UpdateNormalizedUserNameAsync(studentUser);

                        detail.Succeeded = true;
                    }
                    else
                    {
                        detail.ErrorMessages.Add("Данные пользователя не прошли валидацию. Подробнее: " + validateRes.Result.Errors.ToList());
                        return(detail);
                    }
                    await _context.SaveChangesAsync();
                }

                return(detail);
            }
            catch (Exception e)
            {
                detail.ErrorMessages.Add(_serverErrorMessage + e.Message);
                return(detail);
            }
        }
コード例 #22
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)
                    {
                        TempData["message"] = $"Пользователь {user.UserName} был обновлен";

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        TempData["error"] = $"Пользователь {user.UserName} не был обновлен";

                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Пользователь не найден");
            }
            return(View(user));
        }
コード例 #23
0
        public async Task <IActionResult> Edit(string id, string username, string email,
                                               string password, string address, string phonenumber, string sin)
        {
            AppUser user = await userManager.FindByIdAsync(id);

            if (user != null)
            {
                user.UserName    = username;
                user.Email       = email;
                user.PhoneNumber = phonenumber;
                user.Address     = address;
                user.SIN         = sin;
                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("UserList"));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user));
        }
コード例 #24
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = Input.Email, Email = Input.Email, FullName = Input.FullName
                };
                IdentityResult validEmail
                    = await _userValidator.ValidateAsync(_userManager, user);

                if (!validEmail.Succeeded)
                {
                    foreach (IdentityError error in validEmail.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
                else
                {
                    var result = await _userManager.CreateAsync(user, Input.Password);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        var resultRole = await _userManager.AddToRoleAsync(user, Input.Role);

                        if (resultRole.Succeeded)
                        {
                            _logger.LogInformation("Role added to the user.");
                        }

                        //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        //var callbackUrl = Url.Page(
                        //    "/Account/ConfirmEmail",
                        //    pageHandler: null,
                        //    values: new { userId = user.Id, code = code },
                        //    protocol: Request.Scheme);

                        //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
コード例 #25
0
ファイル: UserService.cs プロジェクト: jahanalem/Alpha
        public async Task <IdentityResult> EditUser(User userObj)
        {
            IList <IdentityError> errors = new List <IdentityError>();
            User user = await _userManager.FindByIdAsync(userObj.Id.ToString());

            if (user != null)
            {
                user.Email = userObj.Email;
                IdentityResult validEmail = await _userValidator.ValidateAsync(_userManager, user);

                if (!validEmail.Succeeded)
                {
                    errors.Add(validEmail.Errors);
                    //AddErrorsFromResult(validEmail);
                }
                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(userObj.Password))
                {
                    validPass = await _passwordValidator.ValidateAsync(_userManager, user, userObj.Password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, userObj.Password);
                    }
                    else
                    {
                        errors.Add(validPass.Errors);
                        //AddErrorsFromResult(validPass);
                    }
                    if ((validEmail.Succeeded && validPass == null) || (validEmail.Succeeded && userObj.Password != string.Empty && validPass.Succeeded))
                    {
                        var result = await _userManager.UpdateAsync(user);

                        if (!result.Succeeded)
                        {
                            errors.Add(result.Errors);
                            //AddErrorsFromResult(result);
                        }
                    }
                }
                {
                    //user.IsActive = userViewModel.IsActive;
                    //user.UserName = userViewModel.UserName.Trim();
                    //user.Email = userViewModel.Email.Trim();
                    //user.PhoneNumber = userViewModel.PhoneNumber.Trim();
                    //user.BirthDate = userViewModel.BirthDate;
                    //user.FirstName = userViewModel.FirstName.Trim();
                    //user.LastName = userViewModel.LastName.Trim();
                    //user.PhotoFileName = userViewModel.PhotoFileName.Trim();
                    //user.IsEmailPublic = userViewModel.IsEmailPublic;
                    //user.Location = userViewModel.Location.Trim();
                    //result = await _userManager.UpdateAsync(user);
                }
            }
            return(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
        }
コード例 #26
0
        [HttpPost]                                                                                        //Post Method
        public async Task <IActionResult> Edit(string id, string email, string password, string userName) //Inputs Recieved through Post
        {
            AppUser user = await userManager.FindByIdAsync(id);                                           //Get User

            if (user != null)                                                                             //If Valid User
            {
                user.Email    = email;
                user.UserName = userName;                                                                    //Give User Updated Name & Email
                IdentityResult validEmailAndUsername = await userValidator.ValidateAsync(userManager, user); //Validate

                if (!validEmailAndUsername.Succeeded)                                                        //If Fail
                {
                    AddErrorsFromResult(validEmailAndUsername);                                              //Add Errors
                }
                //
                // user.UserName = userName;
                //IdentityResult validName = await userValidator.ValidateAsync(userManager, user);
                //if (!validName.Succeeded)
                //{
                //    AddErrorsFromResult(validEmail);
                //}
                //
                IdentityResult validPass = null;                                                    //Holds Validity of Password
                if (!string.IsNullOrEmpty(password))                                                //If change to password
                {
                    validPass = await passwordValidator.ValidateAsync(userManager, user, password); //Checj Validity

                    if (validPass.Succeeded)                                                        // If Valid update user password hash
                    {
                        user.PasswordHash = passwordHasher.HashPassword(user, password);
                    }
                    else //Else Generate Errors
                    {
                        AddErrorsFromResult(validPass);
                    }
                }
                if ((validEmailAndUsername.Succeeded && validPass == null) || (validEmailAndUsername.Succeeded && password != string.Empty && validPass.Succeeded)) // If Completely Valid
                {
                    IdentityResult result = await userManager.UpdateAsync(user);                                                                                    //Update DB

                    if (result.Succeeded)                                                                                                                           //If Success, redirect
                    {
                        return(RedirectToAction("Index"));
                    }
                    else  // If fail, send back to form
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else  // If no user, add error
            {
                ModelState.AddModelError("", "User Not Found");
            }
            return(View(user)); // Return to form
        }
コード例 #27
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 _userValid.ValidateAsync(_userManager, user);

                if (!validEmail.Succeeded)
                {
                    AddErrorsFromResult(validEmail);
                }

                IdentityResult validPass = null;
                if (!string.IsNullOrEmpty(password))
                {
                    validPass = await _passValid.ValidateAsync(_userManager,
                                                               user, password);

                    if (validPass.Succeeded)
                    {
                        user.PasswordHash = _passwordHash.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));
        }
コード例 #28
0
        public async Task <IActionResult> EditUser(string id, string userName, string email, string password,
                                                   string emailVerificationKey, string phoneNumber, bool emailConfirmed, string returnUrl)
        {
            UserModel user = await _userManager.FindByIdAsync(id);

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

                if (!validEmail.Succeeded)
                {
                    this.AddErrorsFromResult(validEmail);
                }

                IdentityResult validPassword = null;

                if (!string.IsNullOrEmpty(password))
                {
                    validPassword = await _passwordValidator.ValidateAsync(_userManager, user, password);

                    if (validPassword.Succeeded)
                    {
                        user.PasswordHash = _passwordHasher.HashPassword(user, password);
                    }
                    else
                    {
                        this.AddErrorsFromResult(validPassword);
                    }
                }

                if ((validEmail.Succeeded && validPassword == null) || (validEmail.Succeeded && password != string.Empty && validPassword.Succeeded))
                {
                    user.UserName             = userName;
                    user.EmailVerificationKey = emailVerificationKey;
                    user.PhoneNumber          = phoneNumber;
                    user.EmailConfirmed       = emailConfirmed;

                    IdentityResult result = await _userManager.UpdateAsync(user);

                    if (result.Succeeded)
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        this.AddErrorsFromResult(result);
                    }
                }
            }

            return(View(user));
        }
コード例 #29
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.Password     = password;
                        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(nameof(Search), new { LastNameSearchFragment = user.LastName }));
                    }
                    else
                    {
                        AddErrorsFromResult(result);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "Пользователь не найден");
            }

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

            _logger.LogInformation($"Edit  {user}");
            _logger.LogWarning(new NotImplementedException(), $"Warning:");
            _logger.LogError(new NullReferenceException(), "Exception");
            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));
        }