public async Task <IActionResult> Login(LoginModel model)
        {
            var user = await _accountManager.GetUserByNameAsync(model.UserName);

            if (user != null && await _accountManager.CheckPasswordAsync(user, model.Password))
            {
                var role = await _accountManager.GetUserRolesAsync(user);

                IdentityOptions options = new IdentityOptions();

                var tokenDescription = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserID", user.Id.ToString()),
                        new Claim(options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_applicationSetting.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescription);
                var token         = tokenHandler.WriteToken(securityToken);

                return(Ok(new { token }));
            }

            else
            {
                return(BadRequest(new { message = "Username or password is incorrect." }));
            }
        }
        //[HttpPut("ChangePassword/{id}")]
        public async Task <IActionResult> ChangePassword(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            if (appUser == null)
            {
                return(NotFound(id));
            }

            bool isValid = true;

            if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
            {
                if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                {
                    isValid = false;
                    AddErrors(new string[] { "Entered Current password is invalid." });
                    return(BadRequest("Entered Current password is invalid"));
                }
            }

            if (isValid)
            {
                if (!string.IsNullOrWhiteSpace(user.NewPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        var result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                        else
                        {
                            return(BadRequest("Password could not be changed. Please try again."));
                        }
                    }
                    else
                    {
                        return(BadRequest("Current password is empty"));
                    }
                }
                else
                {
                    return(BadRequest("New password is empty"));
                }
            }

            return(BadRequest(ModelState));
        }
Example #3
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AccountManagementOperations.Update);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), Authorization.Policies.AssignAllowedRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User) == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Current password is required when changing your own password"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Current password is required when changing your own username"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "The username/password couple is invalid." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #4
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AuthPolicies.ManageUserByUserIdPolicy);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), AuthPolicies.AssignRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User).ToString() == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Current password is required when changing your own password"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Current password is required when changing your own username"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User).ToString() == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "The username/password couple is invalid." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }


                        var value = user;
                        //update profierimage
                        //save logo to physical file
                        if (value.profier != null && !string.IsNullOrEmpty(value.profier.Name) && !string.IsNullOrEmpty(value.profier.Value))
                        {
                            //Convert Base64 Encoded string to Byte Array.
                            var    base64String = value.profier.Value;
                            var    fileName     = value.profier.Name;
                            byte[] imageBytes   = Convert.FromBase64String(base64String);

                            //Save the Byte Array as Image File.
                            string filePath = fileName.WebRootPathProfier(Guid.NewGuid().ToString(), _env);
                            imageBytes.WriteAllBytes(filePath);

                            //store filename to DB
                            appUser.ProfilerImage = filePath.GetFileName();

                            result = await _accountManager.UpdateUserAsync(appUser, user.Roles);
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
Example #5
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserDataContract user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }

                bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword);
                bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase);

                if (GetUserId(this.User) == id)
                {
                    if (string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        if (isPasswordChanged)
                        {
                            AddError("Current password is required when changing your own password", "Password");
                        }

                        if (isUserNameChanged)
                        {
                            AddError("Current password is required when changing your own username", "Username");
                        }
                    }
                    else if (isPasswordChanged || isUserNameChanged)
                    {
                        if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                        {
                            AddError("The username/password couple is invalid.");
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    _mapper.Map(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.RoleIds);

                    if (result.Succeeded)
                    {
                        if (isPasswordChanged)
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Succeeded)
                        {
                            return(NoContent());
                        }
                    }

                    AddError(result.Errors);
                }
            }

            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AccountManagementOperations.Update);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, (user.Roles, currentRoles), Authorization.Policies.AssignAllowedRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Conflicting user id in parameter and model data"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }

                bool isPasswordChanged       = !string.IsNullOrWhiteSpace(user.NewPassword);
                bool isUserNameChanged       = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase);
                bool isConfirmedEmailChanged = !appUser.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase) && appUser.EmailConfirmed;

                bool userHasPassword = await _accountManager.GetUserHasPasswordAsync(appUser);

                if (userHasPassword && Utilities.GetUserId(this.User) == id)
                {
                    if (string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        if (isPasswordChanged)
                        {
                            AddError("Current password is required when changing your own password", "Password");
                        }

                        if (isUserNameChanged)
                        {
                            AddError("Current password is required when changing your own username", "Username");
                        }

                        if (isConfirmedEmailChanged)
                        {
                            AddError("Current password is required when changing your own email address", "Email");
                        }
                    }
                    else if (isPasswordChanged || isUserNameChanged || isConfirmedEmailChanged)
                    {
                        if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                        {
                            AddError("The username/password couple is invalid.");
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    _mapper.Map <UserEditViewModel, ApplicationUser>(user, appUser);
                    appUser.EmailConfirmed = isConfirmedEmailChanged ? false : appUser.EmailConfirmed;

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Succeeded)
                    {
                        if (isConfirmedEmailChanged)
                        {
                            await SendVerificationEmail(appUser);
                        }

                        if (isPasswordChanged)
                        {
                            if (userHasPassword && !string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Succeeded)
                        {
                            return(NoContent());
                        }
                    }

                    AddError(result.Errors);
                }
            }

            return(BadRequest(ModelState));
        }
Example #7
0
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(this.User, id, AuthPolicies.ManageUserByUserIdPolicy);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(this.User, Tuple.Create(user.Roles, currentRoles), AuthPolicies.AssignRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
                {
                    return(BadRequest("Xung đột user id trong tham số và mô hình dữ liệu"));
                }

                if (appUser == null)
                {
                    return(NotFound(id));
                }


                if (Utilities.GetUserId(this.User) == id && string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (!string.IsNullOrWhiteSpace(user.NewPassword))
                    {
                        return(BadRequest("Mật khẩu hiện tại được yêu cầu khi thay đổi mật khẩu của riêng bạn"));
                    }

                    if (appUser.UserName != user.UserName)
                    {
                        return(BadRequest("Mật khẩu hiện tại được yêu cầu khi thay đổi tên người dùng của bạn"));
                    }
                }


                bool isValid = true;

                if (Utilities.GetUserId(this.User) == id && (appUser.UserName != user.UserName || !string.IsNullOrWhiteSpace(user.NewPassword)))
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        isValid = false;
                        AddErrors(new string[] { "Tên tài khoản/Mật khẩu không hợp lệ." });
                    }
                }

                if (isValid)
                {
                    Mapper.Map <UserViewModel, ApplicationUser>(user, appUser);

                    var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

                    if (result.Item1)
                    {
                        if (!string.IsNullOrWhiteSpace(user.NewPassword))
                        {
                            if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                            {
                                result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                            }
                            else
                            {
                                result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                            }
                        }

                        if (result.Item1)
                        {
                            return(NoContent());
                        }
                    }

                    AddErrors(result.Item2);
                }
            }

            return(BadRequest(ModelState));
        }
        public async Task <IActionResult> UpdateUser(string id, [FromBody] UserEditViewModel user)
        {
            ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id);

            string[] currentRoles = appUser != null ? (await _accountManager.GetUserRolesAsync(appUser)).ToArray() : null;

            var manageUsersPolicy = _authorizationService.AuthorizeAsync(User, id, AccountManagementOperations.Update);
            var assignRolePolicy  = _authorizationService.AuthorizeAsync(User, (user.Roles, currentRoles), Policies.AssignAllowedRolesPolicy);


            if ((await Task.WhenAll(manageUsersPolicy, assignRolePolicy)).Any(r => !r.Succeeded))
            {
                return(new ChallengeResult());
            }


            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //if (user == null)
            //    return BadRequest($"{nameof(user)} cannot be null");

            if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id)
            {
                return(BadRequest(AppRes.AccountController_UpdateUser_IdMismatch));
            }

            if (appUser == null)
            {
                return(NotFound(id));
            }

            bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword);
            bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase);

            if (User.GetUserId() == id)
            {
                if (string.IsNullOrWhiteSpace(user.CurrentPassword))
                {
                    if (isPasswordChanged)
                    {
                        AddError(AppRes.AccountController_UpdateUser_PasswordChanged, "Password");
                    }

                    if (isUserNameChanged)
                    {
                        AddError(AppRes.AccountController_UpdateUser_UserChanged, "Username");
                    }
                }
                else if (isPasswordChanged || isUserNameChanged)
                {
                    if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword))
                    {
                        AddError(AppRes.AccountController_UpdateUser_PasswordCheck);
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Mapper.Map(user, appUser);

            var result = await _accountManager.UpdateUserAsync(appUser, user.Roles);

            if (result.Succeeded)
            {
                if (isPasswordChanged)
                {
                    if (!string.IsNullOrWhiteSpace(user.CurrentPassword))
                    {
                        result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword);
                    }
                    else
                    {
                        result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword);
                    }
                }

                if (result.Succeeded)
                {
                    return(NoContent());
                }
            }

            AddError(result.Errors);

            return(BadRequest(ModelState));
        }