コード例 #1
0
        public async Task <IActionResult> ModifyUser([FromBody] UserLoginInfo changedUser)
        {
            // Check that new data is provided
            if (changedUser == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "No input data is provided"
                }));
            }

            // Get user who requested it
            var re          = Request;
            var headers     = re.Headers;
            var tokenString = headers["Authorization"];

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(tokenString[0].Split(' ')[1]);

            var claims        = token.Claims;
            var usernameClaim = claims.Where(x => x.Type == ClaimTypes.Name).FirstOrDefault();
            var user          = await _dbHandler.GetUserAsync(usernameClaim.Value);

            // If user does not exist, then BadRequest
            if (user == null)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = "User does not exist"
                }));
            }

            // Check that requester is same then the modify user or role is Admin
            if (user.Username != changedUser.Username && user.Role == UserRole.User)
            {
                return(Unauthorized(new GeneralMessage()
                {
                    Message = "Not authorized to change different user"
                }));
            }

            var targetUser = await _dbHandler.GetUserAsync(changedUser.Username);

            // Everything look cool, let change
            var response = await _dbHandler.ChangeUserAsync(targetUser.Id, new User()
            {
                Username = changedUser.Username, Email = changedUser.Email, Password = changedUser.Password
            });

            if (response.MessageType == MessageType.NOK)
            {
                return(BadRequest(new GeneralMessage()
                {
                    Message = response.MessageText
                }));
            }

            // Everything was fine, return woth OK
            return(Ok(new GeneralMessage()
            {
                Message = "Values has been changed"
            }));
        }