< 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
0%
Covered lines: 0
Uncovered lines: 146
Coverable lines: 146
Total lines: 204
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 38
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%4260%
GetUsersAsync()0%620%
GetUserAsync()0%620%
CreateUserAsync()0%110100%
UpdateUserAsync()0%7280%
UnlockUserAsync()0%2040%
DeleteUserAsync()0%4260%

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
 022public class UserService(
 023    IEmailService emailService,
 024    UserManager<LgdxUser> userManager,
 025    LgdxContext context
 026  ) : IUserService
 27{
 028  private readonly IEmailService _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService));
 029  private readonly UserManager<LgdxUser> _userManager = userManager ?? throw new ArgumentNullException(nameof(userManage
 030  private readonly LgdxContext _context = context ?? throw new ArgumentNullException(nameof(context));
 31
 32  public async Task<(IEnumerable<LgdxUserListBusinessModel>, PaginationHelper)> GetUsersAsync(string? name, int pageNumb
 033  {
 034    var query = _context.Users as IQueryable<LgdxUser>;
 035    if (!string.IsNullOrWhiteSpace(name))
 036    {
 037      name = name.Trim().ToUpper();
 038      query = query.Where(u => u.NormalizedUserName!.Contains(name));
 039    }
 040    var itemCount = await query.CountAsync();
 041    var PaginationHelper = new PaginationHelper(itemCount, pageNumber, pageSize);
 042    var users = await query.AsNoTracking()
 043      .OrderBy(t => t.Id)
 044      .Skip(pageSize * (pageNumber - 1))
 045      .Take(pageSize)
 046      .Select(t => new LgdxUserListBusinessModel {
 047        Id = Guid.Parse(t.Id!),
 048        Name = t.Name!,
 049        UserName = t.UserName!,
 050        TwoFactorEnabled = t.TwoFactorEnabled,
 051        AccessFailedCount = t.AccessFailedCount,
 052      })
 053      .ToListAsync();
 054    return (users, PaginationHelper);
 055  }
 56
 57  public async Task<LgdxUserBusinessModel> GetUserAsync(Guid id)
 058  {
 059    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 060    var roles = await _userManager.GetRolesAsync(user);
 061    return new LgdxUserBusinessModel {
 062      Id = Guid.Parse(user.Id),
 063      Name = user.Name!,
 064      UserName = user.UserName!,
 065      Email = user.Email!,
 066      Roles = roles,
 067      TwoFactorEnabled = user.TwoFactorEnabled,
 068      AccessFailedCount = user.AccessFailedCount,
 069    };
 070  }
 71
 72  public async Task<LgdxUserBusinessModel> CreateUserAsync(LgdxUserCreateAdminBusinessModel lgdxUserCreateAdminBusinessM
 073  {
 074    var user = new LgdxUser {
 075      Id = Guid.CreateVersion7().ToString(),
 076      Email = lgdxUserCreateAdminBusinessModel.Email,
 077      EmailConfirmed = true,
 078      LockoutEnabled = true,
 079      Name = lgdxUserCreateAdminBusinessModel.Name,
 080      NormalizedEmail = lgdxUserCreateAdminBusinessModel.Email.ToUpper(),
 081      NormalizedUserName = lgdxUserCreateAdminBusinessModel.UserName.ToUpper(),
 082      SecurityStamp = Guid.CreateVersion7().ToString(),
 083      UserName = lgdxUserCreateAdminBusinessModel.UserName
 084    };
 085    if (!string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 086    {
 087      var result = await _userManager.CreateAsync(user, lgdxUserCreateAdminBusinessModel.Password);
 088      if (!result.Succeeded)
 089      {
 090        throw new LgdxIdentity400Expection(result.Errors);
 91      }
 092    }
 93    else
 094    {
 095      var result = await _userManager.CreateAsync(user);
 096      if (!result.Succeeded)
 097      {
 098        throw new LgdxIdentity400Expection(result.Errors);
 99      }
 0100    }
 101
 102    // Add Roles
 0103    var roleToAdd = lgdxUserCreateAdminBusinessModel.Roles;
 0104    var roleAddingResult = await _userManager.AddToRolesAsync(user, roleToAdd);
 0105    if (!roleAddingResult.Succeeded)
 0106    {
 0107      throw new LgdxIdentity400Expection(roleAddingResult.Errors);
 108    }
 109
 110    // Send Email
 0111    if (string.IsNullOrWhiteSpace(lgdxUserCreateAdminBusinessModel.Password))
 0112    {
 113      // No password is specified
 0114      var token = await _userManager.GeneratePasswordResetTokenAsync(user!);
 0115      await _emailService.SendWellcomePasswordSetEmailAsync(
 0116        lgdxUserCreateAdminBusinessModel.Email,
 0117        lgdxUserCreateAdminBusinessModel.Name,
 0118        lgdxUserCreateAdminBusinessModel.UserName,
 0119        token
 0120      );
 0121    }
 122    else
 0123    {
 124      // Password is specified
 0125      await _emailService.SendWelcomeEmailAsync(
 0126        lgdxUserCreateAdminBusinessModel.Email,
 0127        lgdxUserCreateAdminBusinessModel.Name,
 0128        lgdxUserCreateAdminBusinessModel.UserName
 0129      );
 0130    }
 131
 0132    return new LgdxUserBusinessModel {
 0133      Id = Guid.Parse(user.Id),
 0134      Name = user.Name!,
 0135      UserName = user.UserName!,
 0136      Email = user.Email!,
 0137      Roles = lgdxUserCreateAdminBusinessModel.Roles,
 0138      TwoFactorEnabled = user.TwoFactorEnabled,
 0139      AccessFailedCount = user.AccessFailedCount,
 0140    };
 0141  }
 142
 143  public async Task<bool> UpdateUserAsync(Guid id, LgdxUserUpdateAdminBusinessModel lgdxUserUpdateAdminBusinessModel)
 0144  {
 0145    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 146
 0147    user.Name = lgdxUserUpdateAdminBusinessModel.Name;
 0148    user.UserName = lgdxUserUpdateAdminBusinessModel.UserName;
 0149    user.Email = lgdxUserUpdateAdminBusinessModel.Email;
 0150    user.NormalizedEmail = lgdxUserUpdateAdminBusinessModel.Email.ToUpper();
 0151    user.NormalizedUserName = lgdxUserUpdateAdminBusinessModel.UserName.ToUpper();
 152
 0153    var result = await _userManager.UpdateAsync(user);
 0154    if (!result.Succeeded)
 0155    {
 0156      throw new LgdxIdentity400Expection(result.Errors);
 157    }
 158
 0159    var roles = await _userManager.GetRolesAsync(user);
 0160    var roleToAdd = lgdxUserUpdateAdminBusinessModel.Roles.Except(roles);
 0161    result = await _userManager.AddToRolesAsync(user, roleToAdd);
 0162    if (!result.Succeeded)
 0163    {
 0164      throw new LgdxIdentity400Expection(result.Errors);
 165    }
 0166    var roleToRemove = roles.Except(lgdxUserUpdateAdminBusinessModel.Roles);
 0167    result = await _userManager.RemoveFromRolesAsync(user, roleToRemove);
 0168    if (!result.Succeeded)
 0169    {
 0170      throw new LgdxIdentity400Expection(result.Errors);
 171    }
 0172    return true;
 0173  }
 174
 175  public async Task<bool> UnlockUserAsync(Guid id)
 0176  {
 0177    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 178
 0179    user.AccessFailedCount = 0;
 0180    user.LockoutEnd = null;
 181
 0182    var result = await _userManager.UpdateAsync(user);
 0183    if (!result.Succeeded)
 0184    {
 0185      throw new LgdxIdentity400Expection(result.Errors);
 186    }
 0187    return true;
 0188  }
 189
 190  public async Task<bool> DeleteUserAsync(Guid id, string operatorId)
 0191  {
 0192    var user = await _userManager.FindByIdAsync(id.ToString()) ?? throw new LgdxNotFound404Exception();
 0193    if (user.Id == operatorId)
 0194    {
 0195      throw new LgdxValidation400Expection(nameof(id), "Cannot delete yourself.");
 196    }
 0197    var result = await _userManager.DeleteAsync(user);
 0198    if (!result.Succeeded)
 0199    {
 0200      throw new LgdxIdentity400Expection(result.Errors);
 201    }
 0202    return true;
 0203  }
 204}