IdentityAppService.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. using System.Security.Claims;
  2. using Hotline.Caching.Interfaces;
  3. using Hotline.Identity;
  4. using Hotline.Identity.Accounts;
  5. using Hotline.Orders;
  6. using Hotline.Push;
  7. using Hotline.Schedulings;
  8. using Hotline.Settings;
  9. using Hotline.Share.Dtos.FlowEngine;
  10. using Hotline.Share.Dtos.Identity;
  11. using Hotline.Share.Enums.FlowEngine;
  12. using Hotline.Share.Enums.Identity;
  13. using Hotline.Users;
  14. using IdentityModel;
  15. using Microsoft.AspNetCore.Http;
  16. using Microsoft.AspNetCore.Identity;
  17. using Microsoft.Extensions.Options;
  18. using XF.Domain.Authentications;
  19. using XF.Domain.Cache;
  20. using XF.Domain.Constants;
  21. using XF.Domain.Dependency;
  22. using XF.Domain.Exceptions;
  23. using XF.Domain.Options;
  24. using XF.Domain.Repository;
  25. namespace Hotline.Application.Identity;
  26. public class IdentityAppService : IIdentityAppService, IScopeDependency
  27. {
  28. private readonly IAccountRepository _accountRepository;
  29. private readonly IAccountDomainService _accountDomainService;
  30. private readonly IRepository<User> _userRepository;
  31. private readonly IJwtSecurity _jwtSecurity;
  32. private readonly IOptionsSnapshot<IdentityConfiguration> _identityOptionsAccessor;
  33. private readonly ITypedCache<AudienceTicket> _cacheAudience;
  34. private readonly IMessageCodeDomainService _messageCodeDomainService;
  35. private readonly IRepository<Scheduling> _schedulingRepository;
  36. private readonly IOrderDomainService _orderDomainService;
  37. private readonly ISystemSettingCacheManager _systemSettingCacheManager;
  38. public IdentityAppService(
  39. IAccountRepository accountRepository,
  40. IAccountDomainService accountDomainService,
  41. IRepository<User> userRepository,
  42. IJwtSecurity jwtSecurity,
  43. IOptionsSnapshot<IdentityConfiguration> identityOptionsAccessor,
  44. ITypedCache<AudienceTicket> cacheAudience,
  45. IMessageCodeDomainService messageCodeDomainService,
  46. IRepository<Scheduling> schedulingRepository,
  47. IOrderDomainService orderDomainService,
  48. ISystemSettingCacheManager systemSettingCacheManager)
  49. {
  50. _accountRepository = accountRepository;
  51. _accountDomainService = accountDomainService;
  52. _userRepository = userRepository;
  53. _jwtSecurity = jwtSecurity;
  54. _identityOptionsAccessor = identityOptionsAccessor;
  55. _cacheAudience = cacheAudience;
  56. _messageCodeDomainService = messageCodeDomainService;
  57. _schedulingRepository = schedulingRepository;
  58. _orderDomainService = orderDomainService;
  59. _systemSettingCacheManager = systemSettingCacheManager;
  60. }
  61. public async Task<string> LoginAsync(LoginDto dto, CancellationToken cancellationToken)
  62. {
  63. var account = await _accountRepository.GetExtAsync(
  64. d => d.UserName == dto.Username,
  65. d => d.Includes(x => x.Roles));
  66. if (account == null)
  67. throw new UserFriendlyException($"用户名或密码错误!{System.Text.Json.JsonSerializer.Serialize(dto)}", "用户名或密码错误!");
  68. var userInfo = await _userRepository.GetAsync(p => p.Id == account.Id, cancellationToken);
  69. //校验验证码
  70. await _messageCodeDomainService.CheckdCode(account.UserName, userInfo.PhoneNo, dto.MsgCode, cancellationToken);
  71. if (account.Status != EAccountStatus.Normal)
  72. throw UserFriendlyException.SameMessage("用户名或密码错误!");
  73. if (account.LockoutEnabled && account.LockoutEnd >= DateTime.Now)
  74. throw UserFriendlyException.SameMessage("账号被锁定!");
  75. var verifyResult = _accountDomainService.VerifyPassword(account, dto.Password);
  76. if (verifyResult == PasswordVerificationResult.Failed)
  77. {
  78. var lockoutOptions = _identityOptionsAccessor.Value.Lockout;
  79. account.AccessFailedCount += 1;
  80. if (account.LockoutEnabled && account.AccessFailedCount >= lockoutOptions.MaxFailedAccessAttempts)
  81. account.LockoutEnd = DateTime.Now.Add(lockoutOptions.DefaultLockoutTimeSpan);
  82. await _accountRepository.UpdateAsync(account, cancellationToken);
  83. throw new UserFriendlyException($"用户名或密码错误!{System.Text.Json.JsonSerializer.Serialize(dto)}", "用户名或密码错误!");
  84. }
  85. //限制系统类型账户频繁获取token的行为
  86. //todo
  87. if (account.LockoutEnd.HasValue || account.AccessFailedCount > 0)
  88. {
  89. account.LockoutEnd = null;
  90. account.AccessFailedCount = 0;
  91. await _accountRepository.UpdateAsync(account, cancellationToken);
  92. }
  93. var user = await _userRepository.Queryable()
  94. .Includes(d => d.Organization)
  95. .FirstAsync(d => d.Id == account.Id);
  96. if (user == null)
  97. throw UserFriendlyException.SameMessage("未查询到用户数据");
  98. //平均派单
  99. var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
  100. if (averageSendOrder)
  101. {
  102. await AverageOrderScheduling(account.Id, cancellationToken);
  103. }
  104. var jwtOptions = _identityOptionsAccessor.Value.Jwt;
  105. var claims = new List<Claim>
  106. {
  107. //new(JwtClaimTypes.Id, account.Id),
  108. new(JwtClaimTypes.Subject, account.Id),
  109. new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
  110. new(AppClaimTypes.UserDisplayName, account.Name),
  111. new(JwtClaimTypes.Scope, jwtOptions.Scope),
  112. new(AppClaimTypes.UserPasswordChanged, account.PasswordChanged.ToString()),
  113. new(AppClaimTypes.StaffNo, user.StaffNo ?? string.Empty),
  114. };
  115. if (!string.IsNullOrEmpty(user.OrgId) && user.Organization is not null)
  116. {
  117. claims.AddRange(
  118. new List<Claim>
  119. {
  120. new(AppClaimTypes.DepartmentId, user.OrgId ?? string.Empty),
  121. new(AppClaimTypes.DepartmentIsCenter, user.Organization?.IsCenter.ToString()),
  122. new(AppClaimTypes.DepartmentName, user.Organization?.Name ?? string.Empty),
  123. new(AppClaimTypes.DepartmentAreaCode, user.Organization?.AreaCode ?? string.Empty),
  124. new(AppClaimTypes.DepartmentAreaName, user.Organization?.AreaName ?? string.Empty),
  125. new(AppClaimTypes.DepartmentLevel, user.Organization?.Level.ToString() ?? string.Empty),
  126. new(AppClaimTypes.AreaId, user.OrgId?.GetHigherOrgId() ?? string.Empty),
  127. }
  128. );
  129. }
  130. claims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
  131. var audience = new AudienceTicket(account.Id);
  132. var expiredSeconds = jwtOptions.Expired <= 0 ? 3600 : jwtOptions.Expired;
  133. await _cacheAudience.SetAsync(audience.Id, audience, TimeSpan.FromSeconds(expiredSeconds), cancellationToken);
  134. var token = _jwtSecurity.EncodeJwtToken(claims, audience.Ticket);
  135. return token;
  136. }
  137. public async Task AverageOrderScheduling(string id, CancellationToken cancellationToken)
  138. {
  139. try
  140. {
  141. DateTime time = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
  142. //&& x.AtWork!.Value != true
  143. //根据当前时间获取排班信息
  144. var scheduling = await _schedulingRepository.Queryable()
  145. .Includes(x => x.SchedulingUser)
  146. .Where(x => x.SchedulingTime == time &&
  147. (x.AtWork == true || x.AtWork == null) &&
  148. x.SchedulingUser.UserId == id)
  149. .OrderBy(x => x.SendOrderNum).FirstAsync(cancellationToken);
  150. if (scheduling != null)
  151. {
  152. scheduling.AtWork = true;
  153. //执行登录平均派单
  154. await _orderDomainService.LogAverageOrder(id, scheduling, cancellationToken);
  155. }
  156. }
  157. catch
  158. {
  159. // ignored
  160. }
  161. }
  162. }