< Summary

Information
Class: LGDXRobotCloud.API.Services.Administration.UserService
Assembly: LGDXRobotCloud.API
File(s): /builds/yukaitung/lgdxrobot2-cloud/LGDXRobotCloud.API/Services/Administration/UserService.cs
Line coverage
100%
Covered lines: 147
Uncovered lines: 0
Coverable lines: 147
Total lines: 205
Line coverage: 100%
Branch coverage
90%
Covered branches: 36
Total branches: 40
Branch coverage: 90%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%66100%
GetUsersAsync()100%22100%
GetUserAsync()75%44100%
CreateUserAsync()100%1010100%
UpdateUserAsync()100%88100%
UnlockUserAsync()100%44100%
DeleteUserAsync()100%66100%

File(s)

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

#LineLine coverage
 1using LGDXRobotCloud.API.Exceptions;
 2using LGDXRobotCloud.API.Services.Common;
 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 IUserService
 13{
 14  Task<(IEnumerable<LgdxUserListBusinessModel>, PaginationHelper)> GetUsersAsync(string? name, int pageNumber, int pageS
 15  Task<LgdxUserBusinessModel> GetUserAsync(Guid id);
 16  Task<LgdxUserBusinessModel> CreateUserAsync(LgdxUserCreateAdminBusinessModel lgdxUserCreateAdminBusinessModel);
 17  Task<bool> UpdateUserAsync(Guid id, LgdxUserUpdateAdminBusinessModel lgdxUserUpdateAdminBusinessModel);
 18  Task<bool> UnlockUserAsync(Guid id);
 19  Task<bool> DeleteUserAsync(Guid id, string operatorId);
 20}
 21
 2322public class UserService(
 2323    IEmailService emailService,
 2324    UserManager<LgdxUser> userManager,
 2325    LgdxContext context
 2326  ) : IUserService
 27{
 2328  private readonly IEmailService _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService));
 2329  private readonly UserManager<LgdxUser> _userManager = userManager ?? throw new ArgumentNullException(nameof(userManage
 2330  private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context));
 31
 32  public async Task<(IEnumerable<LgdxUserListBusinessModel>, PaginationHelper)> GetUsersAsync(string? name, int pageNumb
 433  {
 434    var query = _context.Users as IQueryable<LgdxUser>;
 435    if (!string.IsNullOrWhiteSpace(name))
 336    {
 337      name = name.Trim().ToUpper();
 338      query = query.Where(u => u.NormalizedUserName!.Contains(name.ToUpper()));
 339    }
 440    var itemCount = await query.CountAsync();
 441    var PaginationHelper = new PaginationHelper(itemCount, pageNumber, pageSize);
 442    var users = await query.AsNoTracking()
 443      .OrderBy(t => t.Id)
 444      .Skip(pageSize * (pageNumber - 1))
 445      .Take(pageSize)
 446      .Select(t => new LgdxUserListBusinessModel {
 447        Id = Guid.Parse(t.Id!),
 448        Name = t.Name!,
 449        UserName = t.UserName!,
 450        TwoFactorEnabled = t.TwoFactorEnabled,
 451        AccessFailedCount = t.AccessFailedCount,
 452      })
 453      .ToListAsync();
 454    return (users, PaginationHelper);
 455  }
 56
 57  public async Task<LgdxUserBusinessModel> GetUserAsync(Guid id)
 258  {
 259    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 160    var roles = await _userManager.GetRolesAsync(user);
 161    return new LgdxUserBusinessModel {
 162      Id = Guid.Parse(user.Id),
 163      Name = user.Name!,
 164      UserName = user.UserName!,
 165      Email = user.Email!,
 166      Roles = roles,
 167      TwoFactorEnabled = user.TwoFactorEnabled,
 168      AccessFailedCount = user.AccessFailedCount,
 169      LockoutEnd = user.LockoutEnd?.DateTime,
 170    };
 171  }
 72
 73  public async Task<LgdxUserBusinessModel> CreateUserAsync(LgdxUserCreateAdminBusinessModel lgdxUserCreateAdminBusinessM
 574  {
 575    var user = new LgdxUser {
 576      Id = Guid.CreateVersion7().ToString(),
 577      Email = lgdxUserCreateAdminBusinessModel.Email,
 578      EmailConfirmed = true,
 579      LockoutEnabled = true,
 580      Name = lgdxUserCreateAdminBusinessModel.Name,
 581      NormalizedEmail = lgdxUserCreateAdminBusinessModel.Email.ToUpper(),
 582      NormalizedUserName = lgdxUserCreateAdminBusinessModel.UserName.ToUpper(),
 583      SecurityStamp = Guid.CreateVersion7().ToString(),
 584      UserName = lgdxUserCreateAdminBusinessModel.UserName
 585    };
 586    if (!string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 387    {
 388      var result = await _userManager.CreateAsync(user, lgdxUserCreateAdminBusinessModel.Password);
 389      if (!result.Succeeded)
 190      {
 191        throw new LgdxIdentity400Expection(result.Errors);
 92      }
 293    }
 94    else
 295    {
 296      var result = await _userManager.CreateAsync(user);
 297      if (!result.Succeeded)
 198      {
 199        throw new LgdxIdentity400Expection(result.Errors);
 100      }
 1101    }
 102
 103    // Add Roles
 3104    var roleToAdd = lgdxUserCreateAdminBusinessModel.Roles;
 3105    var roleAddingResult = await _userManager.AddToRolesAsync(user, roleToAdd);
 3106    if (!roleAddingResult.Succeeded)
 1107    {
 1108      throw new LgdxIdentity400Expection(roleAddingResult.Errors);
 109    }
 110
 111    // Send Email
 2112    if (string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 1113    {
 114      // No password is specified
 1115      var token = await _userManager.GeneratePasswordResetTokenAsync(user!);
 1116      await _emailService.SendWellcomePasswordSetEmailAsync(
 1117        lgdxUserCreateAdminBusinessModel.Email,
 1118        lgdxUserCreateAdminBusinessModel.Name,
 1119        lgdxUserCreateAdminBusinessModel.UserName,
 1120        token
 1121      );
 1122    }
 123    else
 1124    {
 125      // Password is specified
 1126      await _emailService.SendWelcomeEmailAsync(
 1127        lgdxUserCreateAdminBusinessModel.Email,
 1128        lgdxUserCreateAdminBusinessModel.Name,
 1129        lgdxUserCreateAdminBusinessModel.UserName
 1130      );
 1131    }
 132
 2133    return new LgdxUserBusinessModel {
 2134      Id = Guid.Parse(user.Id),
 2135      Name = user.Name!,
 2136      UserName = user.UserName!,
 2137      Email = user.Email!,
 2138      Roles = lgdxUserCreateAdminBusinessModel.Roles,
 2139      TwoFactorEnabled = user.TwoFactorEnabled,
 2140      AccessFailedCount = user.AccessFailedCount,
 2141    };
 2142  }
 143
 144  public async Task<bool> UpdateUserAsync(Guid id, LgdxUserUpdateAdminBusinessModel lgdxUserUpdateAdminBusinessModel)
 5145  {
 5146    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 147
 4148    user.Name = lgdxUserUpdateAdminBusinessModel.Name;
 4149    user.UserName = lgdxUserUpdateAdminBusinessModel.UserName;
 4150    user.Email = lgdxUserUpdateAdminBusinessModel.Email;
 4151    user.NormalizedEmail = lgdxUserUpdateAdminBusinessModel.Email.ToUpper();
 4152    user.NormalizedUserName = lgdxUserUpdateAdminBusinessModel.UserName.ToUpper();
 153
 4154    var result = await _userManager.UpdateAsync(user);
 4155    if (!result.Succeeded)
 1156    {
 1157      throw new LgdxIdentity400Expection(result.Errors);
 158    }
 159
 3160    var roles = await _userManager.GetRolesAsync(user);
 3161    var roleToAdd = lgdxUserUpdateAdminBusinessModel.Roles.Except(roles);
 3162    result = await _userManager.AddToRolesAsync(user, roleToAdd);
 3163    if (!result.Succeeded)
 1164    {
 1165      throw new LgdxIdentity400Expection(result.Errors);
 166    }
 2167    var roleToRemove = roles.Except(lgdxUserUpdateAdminBusinessModel.Roles);
 2168    result = await _userManager.RemoveFromRolesAsync(user, roleToRemove);
 2169    if (!result.Succeeded)
 1170    {
 1171      throw new LgdxIdentity400Expection(result.Errors);
 172    }
 1173    return true;
 1174  }
 175
 176  public async Task<bool> UnlockUserAsync(Guid id)
 3177  {
 3178    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 179
 2180    user.AccessFailedCount = 0;
 2181    user.LockoutEnd = null;
 182
 2183    var result = await _userManager.UpdateAsync(user);
 2184    if (!result.Succeeded)
 1185    {
 1186      throw new LgdxIdentity400Expection(result.Errors);
 187    }
 1188    return true;
 1189  }
 190
 191  public async Task<bool> DeleteUserAsync(Guid id, string operatorId)
 4192  {
 4193    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 3194    if (user.Id == operatorId)
 1195    {
 1196      throw new LgdxValidation400Expection(nameof(id), "Cannot delete yourself.");
 197    }
 2198    var result = await _userManager.DeleteAsync(user);
 2199    if (!result.Succeeded)
 1200    {
 1201      throw new LgdxIdentity400Expection(result.Errors);
 202    }
 1203    return true;
 1204  }
 205}