Academatica.Api/Academatica.Api.Users/Controllers/UsersController.cs
/// <summary>
/// Endpoint used to change the user's username.
/// </summary>
/// <param name="id">User ID.</param>
/// <param name="changeUsernameRequestDTO">Body - new username.</param>
Endpoint used to change the user's username.
Endpoint used to change the user ' s username .
[HttpPatch]
        [Route("{id}/username")]
        public async Task<IActionResult> SetUserUsername(Guid id, [FromBody] UserChangeUsernameRequestDto changeUsernameRequestDTO)
        {
            if (ModelState.IsValid)
            {
                var userId = User.FindFirst("sub")?.Value;
                if (userId != id.ToString())
                {
                    return Forbid();
                }
                var user = _academaticaDbContext.Users.Where(x => x.Id == id).FirstOrDefault();
                if (user == null)
                {
                    return NotFound("Invalid user ID.");
                }
                var username = changeUsernameRequestDTO.Username;
                if (_academaticaDbContext.Users.Where(x => x.UserName == username).Any())
                {
                    return BadRequest("Username is already taken.");
                } else
                {
                    await _userManager.SetUserNameAsync(user, username);
                    return Ok();
                }
            } else
            {
                var message = string.Join(" | ", ModelState.Values
                                    .SelectMany(v => v.Errors)
                                    .Select(e => e.ErrorMessage));
                return BadRequest(message);
            }
        }
[ HttpPatch ] [ Route ( " " ) ] public async Task < IActionResult > SetUserUsername ( Guid id , [ FromBody ] UserChangeUsernameRequestDto changeUsernameRequestDTO ) { if ( ModelState . IsValid ) { var userId = User . FindFirst ( " " ) ? . Value ; if ( userId != id . ToString ( ) ) { return Forbid ( ) ; } var user = _academaticaDbContext . Users . Where ( x => x . Id == id ) . FirstOrDefault ( ) ; if ( user == null ) { return NotFound ( " " ) ; } var username = changeUsernameRequestDTO . Username ; if ( _academaticaDbContext . Users . Where ( x => x . UserName == username ) . Any ( ) ) { return BadRequest ( " " ) ; } else { await _userManager . SetUserNameAsync ( user , username ) ; return Ok ( ) ; } } else { var message = string . Join ( " " , ModelState . Values . SelectMany ( v => v . Errors ) . Select ( e => e . ErrorMessage ) ) ; return BadRequest ( message ) ; } }
Endpoint used to change the user's username.
Endpoint used to change the user ' s username .
id
Guid
None
UserChangeUsernameRequestDto
[FromBody]
changeUsernameRequestDTO
None