Home > other >  Checking ir UserRole exist with same ID's
Checking ir UserRole exist with same ID's

Time:10-19

I run into another problem. I have a UserRole domain class which takes UserID and RoleID

public class User_Role
{
    public Guid Id { get; set; }

    public Guid UserId { get; set; }
    //nav prop
    public User User { get; set; }

    public Guid RoleId { get; set; }
    //nav prop
    public Role Role { get; set; }
}

Roles have 2 types Reader and Admin. I need them for authentication which I will implement later. The problem is when I added a "Reader" I can add it again and again. I understand that I need to validate user_role. This is my User_role controller

[Route("api/[controller]")]
[ApiController]
public class UserRoleController : ControllerBase
{

    public readonly IUserRepository _userRepository;
    public readonly IRoleRepository _roleRepository;
    public readonly IUserRoleRepository _userRoleRepository;

    public UserRoleController(IUserRepository userRepository, IRoleRepository IRoleRepository,
        IUserRoleRepository userRoleRepository)
    {
        _userRepository = userRepository;
        _roleRepository = IRoleRepository;
        _userRoleRepository = userRoleRepository;
    }

    [HttpGet]
    public async Task<IActionResult> GetAllUserRoles()
    {
        var userRoleDomain = await _userRoleRepository.GetAllAsync();

        return Ok(userRoleDomain);
    }
    [HttpGet]
    [Route("{userRoleId:guid}")]
    [ActionName("GetUserRoleById")]
    public async Task<IActionResult> GetUserRoleById(Guid userRoleId)
    {
        var userRoleDomain = await _userRoleRepository.GetUserRoleByIdAsync(userRoleId);

        if(userRoleDomain ==  null)
        {
            return NotFound();
        }

        var UserRoleDto = userRoleDomain.ConvertToDto();

        return Ok(UserRoleDto);
    }
    [HttpPost]
    public async Task<IActionResult> AddUserRole([FromBody]AddUserRoleRequest addUserRoleRequest)
    {
        if(!(await ValidateAddUserRoleAsync(addUserRoleRequest)))
        {
            return BadRequest(ModelState);
        }
        //CheckIfRoleExist
        var userRoleDomain = new User_Role
        {
            RoleId = addUserRoleRequest.RoleId,
            UserId = addUserRoleRequest.UserId
        };

        userRoleDomain = await _userRoleRepository.AddUserRoleAsync(userRoleDomain);

        var userRoleDto = userRoleDomain.ConvertToDto();

        return CreatedAtAction(nameof(GetUserRoleById), new { userRoleId = userRoleDto.Id}, userRoleDto);
    }
    [HttpDelete]
    [Route("{userRoleId:guid}")]
    public async Task<IActionResult> DeleteUserRole(Guid userRoleId)
    {
        var userRoleDomain = await _userRoleRepository.DeleteAsync(userRoleId);

        if(userRoleDomain == null)
        {
            return NotFound();
        }

        var userRoleDto = userRoleDomain.ConvertToDto();

        return Ok(userRoleDto);
    }
    [HttpPut]
    [Route("{userRoleId:guid}")]
    public async Task<IActionResult> UpdateUserRole([FromRoute]Guid userRoleId,
        [FromBody]UpdateUserRoleRequest updateUserRoleRequest)
    {
        if(!(await ValidateUpdateUserRoleAsync(updateUserRoleRequest)))
        {
            return BadRequest(ModelState);
        }


        var userRoleDomain = new User_Role()
        {
            Id = userRoleId,
            UserId = updateUserRoleRequest.UserId,
            RoleId = updateUserRoleRequest.RoleId
        };

        userRoleDomain = await _userRoleRepository.UpddateAsync(userRoleId, userRoleDomain);

        if(userRoleDomain == null)
        {
            return NotFound();
        }

        var userRoleDto = userRoleDomain.ConvertToDto();

        return Ok(userRoleDto);
    }

    #region Validation methods

    private async Task<bool> ValidateAddUserRoleAsync(AddUserRoleRequest addUserRoleRequest)
    {
        var user = await _userRepository.GetAsyncByIdWithRoles(addUserRoleRequest.UserId);
        if (user == null)
        {
            ModelState.AddModelError(nameof(addUserRoleRequest.UserId),
                $"{nameof(addUserRoleRequest.UserId)} UserId is invalid");
        }
        var role = await _roleRepository.GetAsync(addUserRoleRequest.RoleId);
        if(role == null)
        {
            ModelState.AddModelError(nameof(addUserRoleRequest.RoleId),
                $"{nameof(addUserRoleRequest.RoleId)} RoleId is invalid");
        }

        if(ModelState.ErrorCount > 0)
        {
            return false;
        }

        return true;
    }

    private async Task<bool> ValidateUpdateUserRoleAsync(UpdateUserRoleRequest updateUserRoleRequest)
    {
        var user = await _userRepository.GetUserByIdASync(updateUserRoleRequest.UserId);
        if(user ==  null)
        {
            ModelState.AddModelError(nameof(updateUserRoleRequest.UserId),
                $"{nameof(updateUserRoleRequest.UserId)} UserId is invalid");
        }
        var role = await _roleRepository.GetAsync(updateUserRoleRequest.RoleId);
        if(role == null)
        {
            ModelState.AddModelError(nameof(updateUserRoleRequest.RoleId),
                $"{nameof(updateUserRoleRequest.RoleId)} RoleId is invalid");
        }

        if(ModelState.ErrorCount > 0)
        {
            return false;
        }

        return true;
    }

    private async Task<bool> CheckIfRoleExist(AddUserRoleRequest addUserRoleRequest)
    {

    }
    #endregion
}

I am thinking to validate this in my CheckIfRoleExist function. How do I check if this type of role is already added with a specific userId?

CodePudding user response:

Figured out something like this

private async Task<bool> CheckIfRoleExist(AddUserRoleRequest addUserRoleRequest)
    {
        var user = await _userRepository.GetAsyncByIdWithRoles(addUserRoleRequest.UserId);
        if(user == null)
        {
            return false;
        }
        foreach(var roleAdded in user.UserRoles)
        {
            if(roleAdded.RoleId == addUserRoleRequest.RoleId)
            {
                ModelState.AddModelError(nameof(addUserRoleRequest.RoleId),
                $"{nameof(addUserRoleRequest.RoleId)} user already have this role");
            }
        }
        if (ModelState.ErrorCount > 0)
        {
            return false;
        }

        return true;
    }

If you have cleaner answer dont be afraid to post it:)

CodePudding user response:

Adding call to repository

  public async Task<bool> CheckIfAlreadyExistAsync(User_Role userRole)
    {
        var userRoleExist = await _webApiDbContext.User_Roles.AnyAsync(u => u.RoleId == userRole.RoleId && u.UserId == userRole.UserId);
       if(userRoleExist != null)
        {
            return true;
        }

        return false;
    }
  • Related