< 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: 174
Uncovered lines: 0
Coverable lines: 174
Total lines: 240
Line coverage: 100%
Branch coverage
88%
Covered branches: 37
Total branches: 42
Branch coverage: 88%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)50%88100%
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.Enums;
 7using LGDXRobotCloud.Utilities.Helpers;
 8using Microsoft.AspNetCore.Identity;
 9using Microsoft.EntityFrameworkCore;
 10
 11namespace LGDXRobotCloud.API.Services.Administration;
 12
 13public interface IUserService
 14{
 15  Task<(IEnumerable<LgdxUserListBusinessModel>, PaginationHelper)> GetUsersAsync(string? name, int pageNumber, int pageS
 16  Task<LgdxUserBusinessModel> GetUserAsync(Guid id);
 17  Task<LgdxUserBusinessModel> CreateUserAsync(LgdxUserCreateAdminBusinessModel lgdxUserCreateAdminBusinessModel);
 18  Task<bool> UpdateUserAsync(Guid id, LgdxUserUpdateAdminBusinessModel lgdxUserUpdateAdminBusinessModel);
 19  Task<bool> UnlockUserAsync(Guid id);
 20  Task<bool> DeleteUserAsync(Guid id, string operatorId);
 21}
 22
 2323public class UserService(
 2324    IActivityLogService activityLogService,
 2325    IEmailService emailService,
 2326    LgdxContext context,
 2327    UserManager<LgdxUser> userManager
 2328  ) : IUserService
 29{
 2330  private readonly IActivityLogService _activityLogService = activityLogService ?? throw new ArgumentNullException(nameo
 2331  private readonly IEmailService _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService));
 2332  private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context));
 2333  private readonly UserManager<LgdxUser> _userManager = userManager ?? throw new ArgumentNullException(nameof(userManage
 34
 35  public async Task<(IEnumerable<LgdxUserListBusinessModel>, PaginationHelper)> GetUsersAsync(string? name, int pageNumb
 436  {
 437    var query = _context.Users as IQueryable<LgdxUser>;
 438    if (!string.IsNullOrWhiteSpace(name))
 339    {
 340      name = name.Trim().ToUpper();
 341      query = query.Where(u => u.NormalizedUserName!.Contains(name.ToUpper()));
 342    }
 443    var itemCount = await query.CountAsync();
 444    var PaginationHelper = new PaginationHelper(itemCount, pageNumber, pageSize);
 445    var users = await query.AsNoTracking()
 446      .OrderBy(t => t.Id)
 447      .Skip(pageSize * (pageNumber - 1))
 448      .Take(pageSize)
 449      .Select(t => new LgdxUserListBusinessModel {
 450        Id = Guid.Parse(t.Id!),
 451        Name = t.Name!,
 452        UserName = t.UserName!,
 453        TwoFactorEnabled = t.TwoFactorEnabled,
 454        AccessFailedCount = t.AccessFailedCount,
 455      })
 456      .ToListAsync();
 457    return (users, PaginationHelper);
 458  }
 59
 60  public async Task<LgdxUserBusinessModel> GetUserAsync(Guid id)
 261  {
 262    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 163    var roles = await _userManager.GetRolesAsync(user);
 164    return new LgdxUserBusinessModel {
 165      Id = Guid.Parse(user.Id),
 166      Name = user.Name!,
 167      UserName = user.UserName!,
 168      Email = user.Email!,
 169      Roles = roles,
 170      TwoFactorEnabled = user.TwoFactorEnabled,
 171      AccessFailedCount = user.AccessFailedCount,
 172      LockoutEnd = user.LockoutEnd?.DateTime,
 173    };
 174  }
 75
 76  public async Task<LgdxUserBusinessModel> CreateUserAsync(LgdxUserCreateAdminBusinessModel lgdxUserCreateAdminBusinessM
 577  {
 578    var user = new LgdxUser {
 579      Id = Guid.CreateVersion7().ToString(),
 580      Email = lgdxUserCreateAdminBusinessModel.Email,
 581      EmailConfirmed = true,
 582      LockoutEnabled = true,
 583      Name = lgdxUserCreateAdminBusinessModel.Name,
 584      NormalizedEmail = lgdxUserCreateAdminBusinessModel.Email.ToUpper(),
 585      NormalizedUserName = lgdxUserCreateAdminBusinessModel.UserName.ToUpper(),
 586      SecurityStamp = Guid.CreateVersion7().ToString(),
 587      UserName = lgdxUserCreateAdminBusinessModel.UserName
 588    };
 589    if (!string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 390    {
 391      var result = await _userManager.CreateAsync(user, lgdxUserCreateAdminBusinessModel.Password);
 392      if (!result.Succeeded)
 193      {
 194        throw new LgdxIdentity400Expection(result.Errors);
 95      }
 296    }
 97    else
 298    {
 299      var result = await _userManager.CreateAsync(user);
 2100      if (!result.Succeeded)
 1101      {
 1102        throw new LgdxIdentity400Expection(result.Errors);
 103      }
 1104    }
 105
 106    // Add Roles
 3107    var roleToAdd = lgdxUserCreateAdminBusinessModel.Roles;
 3108    var roleAddingResult = await _userManager.AddToRolesAsync(user, roleToAdd);
 3109    if (!roleAddingResult.Succeeded)
 1110    {
 1111      throw new LgdxIdentity400Expection(roleAddingResult.Errors);
 112    }
 113
 114    // Send Email
 2115    if (string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 1116    {
 117      // No password is specified
 1118      var token = await _userManager.GeneratePasswordResetTokenAsync(user!);
 1119      await _emailService.SendWellcomePasswordSetEmailAsync(
 1120        lgdxUserCreateAdminBusinessModel.Email,
 1121        lgdxUserCreateAdminBusinessModel.Name,
 1122        lgdxUserCreateAdminBusinessModel.UserName,
 1123        token
 1124      );
 1125    }
 126    else
 1127    {
 128      // Password is specified
 1129      await _emailService.SendWelcomeEmailAsync(
 1130        lgdxUserCreateAdminBusinessModel.Email,
 1131        lgdxUserCreateAdminBusinessModel.Name,
 1132        lgdxUserCreateAdminBusinessModel.UserName
 1133      );
 1134    }
 135
 2136    await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel
 2137    {
 2138      EntityName = nameof(LgdxUser),
 2139      EntityId = user.Id,
 2140      Action = ActivityAction.Create,
 2141    });
 142
 2143    return new LgdxUserBusinessModel
 2144    {
 2145      Id = Guid.Parse(user.Id),
 2146      Name = user.Name!,
 2147      UserName = user.UserName!,
 2148      Email = user.Email!,
 2149      Roles = lgdxUserCreateAdminBusinessModel.Roles,
 2150      TwoFactorEnabled = user.TwoFactorEnabled,
 2151      AccessFailedCount = user.AccessFailedCount,
 2152    };
 2153  }
 154
 155  public async Task<bool> UpdateUserAsync(Guid id, LgdxUserUpdateAdminBusinessModel lgdxUserUpdateAdminBusinessModel)
 5156  {
 5157    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 158
 4159    user.Name = lgdxUserUpdateAdminBusinessModel.Name;
 4160    user.UserName = lgdxUserUpdateAdminBusinessModel.UserName;
 4161    user.Email = lgdxUserUpdateAdminBusinessModel.Email;
 4162    user.NormalizedEmail = lgdxUserUpdateAdminBusinessModel.Email.ToUpper();
 4163    user.NormalizedUserName = lgdxUserUpdateAdminBusinessModel.UserName.ToUpper();
 164
 4165    var result = await _userManager.UpdateAsync(user);
 4166    if (!result.Succeeded)
 1167    {
 1168      throw new LgdxIdentity400Expection(result.Errors);
 169    }
 170
 3171    var roles = await _userManager.GetRolesAsync(user);
 3172    var roleToAdd = lgdxUserUpdateAdminBusinessModel.Roles.Except(roles);
 3173    result = await _userManager.AddToRolesAsync(user, roleToAdd);
 3174    if (!result.Succeeded)
 1175    {
 1176      throw new LgdxIdentity400Expection(result.Errors);
 177    }
 2178    var roleToRemove = roles.Except(lgdxUserUpdateAdminBusinessModel.Roles);
 2179    result = await _userManager.RemoveFromRolesAsync(user, roleToRemove);
 2180    if (!result.Succeeded)
 1181    {
 1182      throw new LgdxIdentity400Expection(result.Errors);
 183    }
 184
 1185    await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel
 1186    {
 1187      EntityName = nameof(LgdxUser),
 1188      EntityId = user.Id,
 1189      Action = ActivityAction.Update,
 1190    });
 191
 1192    return true;
 1193  }
 194
 195  public async Task<bool> UnlockUserAsync(Guid id)
 3196  {
 3197    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 198
 2199    user.AccessFailedCount = 0;
 2200    user.LockoutEnd = null;
 201
 2202    var result = await _userManager.UpdateAsync(user);
 2203    if (!result.Succeeded)
 1204    {
 1205      throw new LgdxIdentity400Expection(result.Errors);
 206    }
 207
 1208    await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel
 1209    {
 1210      EntityName = nameof(LgdxUser),
 1211      EntityId = user.Id,
 1212      Action = ActivityAction.UserUnlocked,
 1213    });
 214
 1215    return true;
 1216  }
 217
 218  public async Task<bool> DeleteUserAsync(Guid id, string operatorId)
 4219  {
 4220    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 3221    if (user.Id == operatorId)
 1222    {
 1223      throw new LgdxValidation400Expection(nameof(id), "Cannot delete yourself.");
 224    }
 2225    var result = await _userManager.DeleteAsync(user);
 2226    if (!result.Succeeded)
 1227    {
 1228      throw new LgdxIdentity400Expection(result.Errors);
 229    }
 230
 1231    await _activityLogService.CreateActivityLogAsync(new ActivityLogCreateBusinessModel
 1232    {
 1233      EntityName = nameof(LgdxUser),
 1234      EntityId = user.Id,
 1235      Action = ActivityAction.Delete,
 1236    });
 237
 1238    return true;
 1239  }
 240}