< Summary

Information
Class: LGDXRobotCloud.API.Services.Administration.RoleService
Assembly: LGDXRobotCloud.API
File(s): /builds/yukaitung/lgdxrobot2-cloud/LGDXRobotCloud.API/Services/Administration/RoleService.cs
Line coverage
100%
Covered lines: 138
Uncovered lines: 0
Coverable lines: 138
Total lines: 189
Line coverage: 100%
Branch coverage
92%
Covered branches: 35
Total branches: 38
Branch coverage: 92.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%44100%
GetRolesAsync()100%22100%
GetRoleAsync()100%22100%
CreateRoleAsync()100%88100%
UpdateRoleAsync()100%1414100%
DeleteRoleAsync()100%66100%
SearchRoleAsync()50%22100%

File(s)

/builds/yukaitung/lgdxrobot2-cloud/LGDXRobotCloud.API/Services/Administration/RoleService.cs

#LineLine coverage
 1using System.Security.Claims;
 2using LGDXRobotCloud.API.Exceptions;
 3using LGDXRobotCloud.Data.DbContexts;
 4using LGDXRobotCloud.Data.Entities;
 5using LGDXRobotCloud.Data.Models.Business.Administration;
 6using LGDXRobotCloud.Utilities.Helpers;
 7using Microsoft.AspNetCore.Identity;
 8using Microsoft.EntityFrameworkCore;
 9
 10namespace LGDXRobotCloud.API.Services.Administration;
 11
 12public interface IRoleService
 13{
 14  Task<(IEnumerable<LgdxRoleListBusinessModel>, PaginationHelper)> GetRolesAsync(string? name, int pageNumber, int pageS
 15  Task<LgdxRoleBusinessModel> GetRoleAsync(Guid id);
 16  Task<LgdxRoleBusinessModel> CreateRoleAsync(LgdxRoleCreateBusinessModel lgdxRoleBusinessModel);
 17  Task<bool> UpdateRoleAsync(Guid id, LgdxRoleUpdateBusinessModel lgdxRoleUpdateBusinessModel);
 18  Task<bool> DeleteRoleAsync(Guid id);
 19
 20  Task<IEnumerable<LgdxRoleSearchBusinessModel>> SearchRoleAsync(string? name);
 21}
 22
 2323public class RoleService(
 2324    LgdxContext context,
 2325    RoleManager<LgdxRole> roleManager
 2326  ) : IRoleService
 27{
 2328  private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context));
 2329  private readonly RoleManager<LgdxRole> _roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManage
 30
 31  public async Task<(IEnumerable<LgdxRoleListBusinessModel>, PaginationHelper)> GetRolesAsync(string? name, int pageNumb
 432  {
 433    var query = _context.Roles as IQueryable<LgdxRole>;
 434    if (!string.IsNullOrWhiteSpace(name))
 335    {
 336      name = name.Trim().ToUpper();
 337      query = query.Where(u => u.NormalizedName!.Contains(name.ToUpper()));
 338    }
 439    var itemCount = await query.CountAsync();
 440    var PaginationHelper = new PaginationHelper(itemCount, pageNumber, pageSize);
 441    var roles = await query.AsNoTracking()
 442      .OrderBy(t => t.Id)
 443      .Skip(pageSize * (pageNumber - 1))
 444      .Take(pageSize)
 445      .Select(t => new LgdxRoleListBusinessModel {
 446        Id = Guid.Parse(t.Id!),
 447        Name = t.Name!,
 448        Description = t.Description,
 449      })
 450      .ToListAsync();
 451    return (roles, PaginationHelper);
 452  }
 53
 54  public async Task<LgdxRoleBusinessModel> GetRoleAsync(Guid id)
 255  {
 256    var role = await _context.Roles.AsNoTracking()
 257      .Where(r => r.Id == id.ToString())
 258      .Select(r => new{
 259        r.Id,
 260        r.Name,
 261        r.Description,
 262      })
 263      .FirstOrDefaultAsync()
 264        ?? throw new LgdxNotFound404Exception();
 65
 166    var claims = await _context.RoleClaims.AsNoTracking()
 167      .Where(c => c.RoleId == id.ToString())
 168      .Where(c => c.ClaimType == "scope")
 169      .Select(r => new {
 170        ClaimValue = r.ClaimValue!,
 171      }).ToListAsync();
 72
 173    return new LgdxRoleBusinessModel {
 174      Id = Guid.Parse(role.Id),
 175      Name = role.Name!,
 176      Description = role.Description,
 277      Scopes = claims.Select(c => c.ClaimValue!),
 178    };
 179  }
 80
 81  public async Task<LgdxRoleBusinessModel> CreateRoleAsync(LgdxRoleCreateBusinessModel lgdxRoleBusinessModel)
 382  {
 383    var role = new LgdxRole {
 384      Id = Guid.CreateVersion7().ToString(),
 385      Name = lgdxRoleBusinessModel.Name,
 386      Description = lgdxRoleBusinessModel.Description,
 387      NormalizedName = lgdxRoleBusinessModel.Name.ToUpper(),
 388    };
 389    var result = await _roleManager.CreateAsync(role);
 390    if (!result.Succeeded)
 191    {
 192      throw new LgdxIdentity400Expection(result.Errors);
 93    }
 94
 295    if (lgdxRoleBusinessModel.Scopes.Any())
 296    {
 997      foreach (var scope in lgdxRoleBusinessModel.Scopes)
 298      {
 299        var addScopeResult = await _roleManager.AddClaimAsync(role, new Claim("scope", scope));
 2100        if (!addScopeResult.Succeeded)
 1101        {
 1102          throw new LgdxIdentity400Expection(addScopeResult.Errors);
 103        }
 1104      }
 1105    }
 106
 1107    return new LgdxRoleBusinessModel {
 1108      Id = Guid.Parse(role.Id),
 1109      Name = role.Name!,
 1110      Description = role.Description,
 1111      Scopes = lgdxRoleBusinessModel.Scopes,
 1112    };
 1113  }
 114
 115  public async Task<bool> UpdateRoleAsync(Guid id, LgdxRoleUpdateBusinessModel lgdxRoleUpdateBusinessModel)
 6116  {
 6117    if (LgdxRolesHelper.IsSystemRole(id))
 1118    {
 1119      throw new LgdxValidation400Expection(nameof(lgdxRoleUpdateBusinessModel.Name), "Cannot update system role.");
 120    }
 5121    var role = await _roleManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 122
 4123    role.Name = lgdxRoleUpdateBusinessModel.Name;
 4124    role.Description = lgdxRoleUpdateBusinessModel.Description;
 4125    role.NormalizedName = lgdxRoleUpdateBusinessModel.Name.ToUpper();
 126
 4127    var result = await _roleManager.UpdateAsync(role);
 4128    if (!result.Succeeded)
 1129    {
 1130      throw new LgdxIdentity400Expection(result.Errors);
 131    }
 132
 3133    var scopes = await _context.RoleClaims
 3134      .Where(r => r.RoleId == id.ToString())
 3135      .Where(r => r.ClaimType == "scope")
 3136      .Select(r => new {
 3137        r.ClaimValue
 3138      })
 3139      .ToListAsync();
 6140    var scopesList = scopes.Select(s => s.ClaimValue).ToList();
 3141    var scopeToAdd = lgdxRoleUpdateBusinessModel.Scopes.Except(scopesList);
 14142    foreach (var scope in scopeToAdd)
 3143    {
 3144      var addScopeResult = await _roleManager.AddClaimAsync(role, new Claim("scope", scope!));
 3145      if (!addScopeResult.Succeeded)
 1146      {
 1147        throw new LgdxIdentity400Expection(addScopeResult.Errors);
 148      }
 2149    }
 2150    var scopeToRemove = scopesList.Except(lgdxRoleUpdateBusinessModel.Scopes);
 9151    foreach (var scope in scopeToRemove)
 2152    {
 2153      var removeScopeResult = await _roleManager.RemoveClaimAsync(role, new Claim("scope", scope!));
 2154      if (!removeScopeResult.Succeeded)
 1155      {
 1156        throw new LgdxIdentity400Expection(removeScopeResult.Errors);
 157      }
 1158    }
 1159    return true; // Error is handled in the Identity service
 1160  }
 161
 162  public async Task<bool> DeleteRoleAsync(Guid id)
 4163  {
 4164    if (LgdxRolesHelper.IsSystemRole(id))
 1165    {
 1166      throw new LgdxValidation400Expection(nameof(id), "Cannot delete system role.");
 167    }
 3168    var role = await _roleManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 2169    var result = await _roleManager.DeleteAsync(role);
 2170    if (!result.Succeeded)
 1171    {
 1172      throw new LgdxIdentity400Expection(result.Errors);
 173    }
 1174    return true; // Error is handled in the Identity service
 1175  }
 176
 177  public async Task<IEnumerable<LgdxRoleSearchBusinessModel>> SearchRoleAsync(string? name)
 4178  {
 4179    var n = name ?? string.Empty;
 4180    return await _context.Roles.AsNoTracking()
 4181      .Where(r => r.NormalizedName!.Contains(n.ToUpper()))
 4182      .Take(10)
 4183      .Select(t => new LgdxRoleSearchBusinessModel {
 4184        Id = Guid.Parse(t.Id!),
 4185        Name = t.Name!,
 4186      })
 4187      .ToListAsync();
 4188  }
 189}