IdentityAppService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System.Security.Claims;
  2. using Fw.Utility.UnifyResponse;
  3. using Hotline.Caching.Interfaces;
  4. using Hotline.Caching.Services;
  5. using Hotline.Identity;
  6. using Hotline.Identity.Accounts;
  7. using Hotline.Orders;
  8. using Hotline.Push;
  9. using Hotline.Schedulings;
  10. using Hotline.SeedData;
  11. using Hotline.Settings;
  12. using Hotline.Share.Dtos.FlowEngine;
  13. using Hotline.Share.Dtos.Identity;
  14. using Hotline.Share.Dtos.Snapshot;
  15. using Hotline.Share.Enums.FlowEngine;
  16. using Hotline.Share.Enums.Identity;
  17. using Hotline.Share.Enums.Snapshot;
  18. using Hotline.Share.Enums.User;
  19. using Hotline.Share.Tools;
  20. using Hotline.Snapshot.Interfaces;
  21. using Hotline.ThirdAccountDomainServices;
  22. using Hotline.ThirdAccountDomainServices.Interfaces;
  23. using Hotline.Users;
  24. using IdentityModel;
  25. using Mapster;
  26. using Microsoft.AspNetCore.Identity;
  27. using Microsoft.Extensions.Options;
  28. using SqlSugar;
  29. using XF.Domain.Authentications;
  30. using XF.Domain.Cache;
  31. using XF.Domain.Dependency;
  32. using XF.Domain.Exceptions;
  33. using XF.Domain.Options;
  34. using XF.Domain.Repository;
  35. namespace Hotline.Application.Identity;
  36. public class IdentityAppService : IIdentityAppService, IScopeDependency
  37. {
  38. private readonly IAccountRepository _accountRepository;
  39. private readonly IAccountDomainService _accountDomainService;
  40. private readonly IRepository<User> _userRepository;
  41. private readonly IJwtSecurity _jwtSecurity;
  42. private readonly IOptionsSnapshot<IdentityConfiguration> _identityOptionsAccessor;
  43. private readonly ITypedCache<AudienceTicket> _cacheAudience;
  44. private readonly IMessageCodeDomainService _messageCodeDomainService;
  45. private readonly IRepository<Scheduling> _schedulingRepository;
  46. private readonly IOrderDomainService _orderDomainService;
  47. private readonly ISystemSettingCacheManager _systemSettingCacheManager;
  48. private readonly IThirdAccountRepository _thirdAccountRepository;
  49. private readonly ISystemLogRepository _systemLog;
  50. private readonly ThirdIdentiyFactory _thirdIdentiyFactory;
  51. private readonly ThirdAccounSupplierFactory _thirdAccountDomainFactory;
  52. public IdentityAppService(
  53. IAccountRepository accountRepository,
  54. IAccountDomainService accountDomainService,
  55. IRepository<User> userRepository,
  56. IJwtSecurity jwtSecurity,
  57. IOptionsSnapshot<IdentityConfiguration> identityOptionsAccessor,
  58. ITypedCache<AudienceTicket> cacheAudience,
  59. IMessageCodeDomainService messageCodeDomainService,
  60. IRepository<Scheduling> schedulingRepository,
  61. IOrderDomainService orderDomainService,
  62. ISystemSettingCacheManager systemSettingCacheManager,
  63. IThirdAccountRepository thirdAccountRepository,
  64. ISystemLogRepository systemLog,
  65. ThirdIdentiyFactory thirdIdentiyFactory,
  66. ThirdAccounSupplierFactory thirdAccountDomainFactory)
  67. {
  68. _accountRepository = accountRepository;
  69. _accountDomainService = accountDomainService;
  70. _userRepository = userRepository;
  71. _jwtSecurity = jwtSecurity;
  72. _identityOptionsAccessor = identityOptionsAccessor;
  73. _cacheAudience = cacheAudience;
  74. _messageCodeDomainService = messageCodeDomainService;
  75. _schedulingRepository = schedulingRepository;
  76. _orderDomainService = orderDomainService;
  77. _systemSettingCacheManager = systemSettingCacheManager;
  78. _thirdAccountRepository = thirdAccountRepository;
  79. _systemLog = systemLog;
  80. _thirdIdentiyFactory = thirdIdentiyFactory;
  81. _thirdAccountDomainFactory = thirdAccountDomainFactory;
  82. }
  83. public async Task<string> OldToNewLoginAsync(HotlineLoginOldToNewDto dto, CancellationToken cancellationToken)
  84. {
  85. var account = await _accountRepository.GetExtAsync(
  86. d => d.UserName == dto.UserName,
  87. d => d.Includes(x => x.Roles));
  88. if (account is null)
  89. throw UserFriendlyException.SameMessage("未找到帐号,请联系管理员查看");
  90. if (account.Status != EAccountStatus.Normal)
  91. throw UserFriendlyException.SameMessage("帐号已被注销,请联系管理员查看");
  92. if (account.LockoutEnabled && account.LockoutEnd >= DateTime.Now)
  93. throw UserFriendlyException.SameMessage("账号被锁定!请联系管理员查看");
  94. var userInfo = await _userRepository.GetAsync(p => p.Id == account.Id, cancellationToken);
  95. //限制系统类型账户频繁获取token的行为
  96. //todo
  97. if (account.LockoutEnd.HasValue || account.AccessFailedCount > 0)
  98. {
  99. account.LockoutEnd = null;
  100. account.AccessFailedCount = 0;
  101. await _accountRepository.UpdateAsync(account, cancellationToken);
  102. }
  103. var user = await _userRepository.Queryable()
  104. .Includes(d => d.Organization)
  105. .FirstAsync(d => d.Id == account.Id);
  106. //平均派单
  107. var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
  108. if (averageSendOrder)
  109. {
  110. await AverageOrderScheduling(account.Id, cancellationToken);
  111. }
  112. var jwtOptions = _identityOptionsAccessor.Value.Jwt;
  113. var claims = new List<Claim>
  114. {
  115. //new(JwtClaimTypes.Id, account.Id),
  116. new(JwtClaimTypes.Subject, account.Id),
  117. new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
  118. new(AppClaimTypes.UserDisplayName, account.Name),
  119. //new(JwtClaimTypes.Scope, jwtOptions.Scope),
  120. new(JwtClaimTypes.Scope, account.Scope),
  121. new(AppClaimTypes.UserPasswordChanged, account.PasswordChanged.ToString()),
  122. new(AppClaimTypes.StaffNo, user.StaffNo ?? string.Empty),
  123. };
  124. if (!string.IsNullOrEmpty(user.OrgId) && user.Organization is not null)
  125. {
  126. claims.AddRange(
  127. new List<Claim>
  128. {
  129. new(AppClaimTypes.DepartmentId, user.OrgId ?? string.Empty),
  130. new(AppClaimTypes.DepartmentIsCenter, user.Organization?.IsCenter.ToString()),
  131. new(AppClaimTypes.DepartmentName, user.Organization?.Name ?? string.Empty),
  132. new(AppClaimTypes.DepartmentAreaCode, user.Organization?.AreaCode ?? string.Empty),
  133. new(AppClaimTypes.DepartmentAreaName, user.Organization?.AreaName ?? string.Empty),
  134. new(AppClaimTypes.DepartmentLevel, user.Organization?.Level.ToString() ?? string.Empty),
  135. new(AppClaimTypes.AreaId, user.OrgId?.GetHigherOrgId() ?? string.Empty),
  136. }
  137. );
  138. }
  139. claims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
  140. var audience = new AudienceTicket(account.Id);
  141. var expiredSeconds = jwtOptions.Expired <= 0 ? 3600 : jwtOptions.Expired;
  142. await _cacheAudience.SetAsync(audience.Id, audience, TimeSpan.FromSeconds(expiredSeconds), cancellationToken);
  143. var token = _jwtSecurity.EncodeJwtToken(claims, audience.Ticket);
  144. return token;
  145. }
  146. public async Task<(bool,bool, User)> IsCheckAdmin(string userName)
  147. {
  148. var isAdmin = false;
  149. var isCenter = false;
  150. var account = await _accountRepository.GetExtAsync(
  151. d => d.UserName == userName,
  152. d => d.Includes(x => x.Roles)
  153. );
  154. if (account is null)
  155. throw UserFriendlyException.SameMessage("未找到帐号,请联系管理员查看");
  156. if (account.Status != EAccountStatus.Normal)
  157. throw UserFriendlyException.SameMessage("帐号已被注销,请联系管理员查看");
  158. if (account.LockoutEnabled && account.LockoutEnd >= DateTime.Now)
  159. throw UserFriendlyException.SameMessage("账号被锁定!请联系管理员查看");
  160. var user = await _userRepository.Queryable()
  161. .Includes(d => d.Organization)
  162. .Includes(d => d.Roles)
  163. .FirstAsync(d => d.Id == account.Id);
  164. var systemAdministrator = _systemSettingCacheManager.GetSetting(SettingConstants.SystemAdministrator)?.SettingValue[0];
  165. if (!string.IsNullOrEmpty(systemAdministrator) && (user.Roles.Any(x=>x.Name.Contains(systemAdministrator)) || user.Roles.Any(x=>x.Name.Contains(RoleSeedData.AdminRole))))
  166. isAdmin = true;
  167. else
  168. isAdmin = false;
  169. isCenter = user.Organization.IsCenter;
  170. return (isAdmin, isCenter,user);
  171. }
  172. public async Task<string> LoginAsync(LoginDto dto, CancellationToken cancellationToken)
  173. {
  174. var account = await _accountRepository.GetExtAsync(
  175. d => d.UserName == dto.Username,
  176. d => d.Includes(x => x.Roles));
  177. if (account == null)
  178. throw new UserFriendlyException($"用户名或密码错误!{System.Text.Json.JsonSerializer.Serialize(dto)}", "用户名或密码错误!");
  179. var userInfo = await _userRepository.GetAsync(p => p.Id == account.Id, cancellationToken);
  180. //校验验证码
  181. await _messageCodeDomainService.CheckdCode(account.UserName, userInfo.PhoneNo, dto.MsgCode, cancellationToken);
  182. if (account.Status != EAccountStatus.Normal)
  183. throw UserFriendlyException.SameMessage("用户名或密码错误!");
  184. if (account.LockoutEnabled && account.LockoutEnd >= DateTime.Now)
  185. throw UserFriendlyException.SameMessage("账号被锁定!");
  186. var verifyResult = _accountDomainService.VerifyPassword(account, dto.Password);
  187. if (verifyResult == PasswordVerificationResult.Failed)
  188. {
  189. var lockoutOptions = _identityOptionsAccessor.Value.Lockout;
  190. account.AccessFailedCount += 1;
  191. if (account.LockoutEnabled && account.AccessFailedCount >= lockoutOptions.MaxFailedAccessAttempts)
  192. account.LockoutEnd = DateTime.Now.Add(lockoutOptions.DefaultLockoutTimeSpan);
  193. await _accountRepository.UpdateAsync(account, cancellationToken);
  194. throw new UserFriendlyException($"用户名或密码错误!{System.Text.Json.JsonSerializer.Serialize(dto)}", "用户名或密码错误!");
  195. }
  196. //限制系统类型账户频繁获取token的行为
  197. //todo
  198. if (account.LockoutEnd.HasValue || account.AccessFailedCount > 0)
  199. {
  200. account.LockoutEnd = null;
  201. account.AccessFailedCount = 0;
  202. await _accountRepository.UpdateAsync(account, cancellationToken);
  203. }
  204. var user = await _userRepository.Queryable()
  205. .Includes(d => d.Organization)
  206. .FirstAsync(d => d.Id == account.Id);
  207. if (user == null)
  208. throw UserFriendlyException.SameMessage("未查询到用户数据");
  209. //平均派单
  210. var averageSendOrder = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.AverageSendOrder).SettingValue[0]);
  211. if (averageSendOrder)
  212. {
  213. await AverageOrderScheduling(account.Id, cancellationToken);
  214. }
  215. var jwtOptions = _identityOptionsAccessor.Value.Jwt;
  216. var claims = new List<Claim>
  217. {
  218. //new(JwtClaimTypes.Id, account.Id),
  219. new(JwtClaimTypes.Subject, account.Id),
  220. new(JwtClaimTypes.PhoneNumber, account.PhoneNo ?? string.Empty),
  221. new(AppClaimTypes.UserDisplayName, account.Name),
  222. //new(JwtClaimTypes.Scope, jwtOptions.Scope),
  223. new(JwtClaimTypes.Scope, account.Scope),
  224. new(AppClaimTypes.UserPasswordChanged, account.PasswordChanged.ToString()),
  225. new(AppClaimTypes.StaffNo, user.StaffNo ?? string.Empty),
  226. };
  227. if (!string.IsNullOrEmpty(user.OrgId) && user.Organization is not null)
  228. {
  229. claims.AddRange(
  230. new List<Claim>
  231. {
  232. new(AppClaimTypes.DepartmentId, user.OrgId ?? string.Empty),
  233. new(AppClaimTypes.DepartmentIsCenter, user.Organization?.IsCenter.ToString()),
  234. new(AppClaimTypes.DepartmentName, user.Organization?.Name ?? string.Empty),
  235. new(AppClaimTypes.DepartmentAreaCode, user.Organization?.AreaCode ?? string.Empty),
  236. new(AppClaimTypes.DepartmentAreaName, user.Organization?.AreaName ?? string.Empty),
  237. new(AppClaimTypes.DepartmentLevel, user.Organization?.Level.ToString() ?? string.Empty),
  238. new(AppClaimTypes.AreaId, user.OrgId?.GetHigherOrgId() ?? string.Empty),
  239. }
  240. );
  241. }
  242. claims.AddRange(account.Roles.Select(d => new Claim(JwtClaimTypes.Role, d.Name)));
  243. var audience = new AudienceTicket(account.Id);
  244. var expiredSeconds = jwtOptions.Expired <= 0 ? 3600 : jwtOptions.Expired;
  245. await _cacheAudience.SetAsync(audience.Id, audience, TimeSpan.FromSeconds(expiredSeconds), cancellationToken);
  246. var token = _jwtSecurity.EncodeJwtToken(claims, audience.Ticket);
  247. return token;
  248. }
  249. public async Task AverageOrderScheduling(string id, CancellationToken cancellationToken)
  250. {
  251. try
  252. {
  253. DateTime time = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
  254. //&& x.AtWork!.Value != true
  255. //根据当前时间获取排班信息
  256. var scheduling = await _schedulingRepository.Queryable()
  257. .Includes(x => x.SchedulingUser)
  258. .Where(x => x.SchedulingTime == time &&
  259. //(x.AtWork == true || x.AtWork == null) &&
  260. x.SchedulingUser.UserId == id)
  261. .OrderBy(x => x.SendOrderNum).FirstAsync(cancellationToken);
  262. if (scheduling != null && (!scheduling.AtWork.HasValue || scheduling.AtWork == false))
  263. {
  264. scheduling.AtWork = true;
  265. //执行登录平均派单
  266. await _orderDomainService.LogAverageOrder(id, scheduling, cancellationToken);
  267. }
  268. }
  269. catch
  270. {
  271. // ignored
  272. }
  273. }
  274. /// <summary>
  275. /// 获取三方令牌
  276. /// </summary>
  277. /// <param name="dto"></param>
  278. /// <returns></returns>
  279. /// <exception cref="UserFriendlyException"></exception>
  280. public async Task<Dictionary<string, object>> GetThredTokenAsync(ThirdTokenInDto dto, CancellationToken token)
  281. {
  282. var thirdDto = dto.Adapt<ThirdTokenDto>();
  283. thirdDto = await _thirdAccountDomainFactory.GetThirdParameterAsync(thirdDto, token);
  284. var thirdToken = await _thirdIdentiyFactory.GetTokenAsync(thirdDto, token);
  285. var phone = await _thirdIdentiyFactory.GetPhoneNumberAsync(thirdDto, token);
  286. var thirdAccount = await _thirdAccountRepository.GetByOpenIdAsync(thirdToken.OpenId, token);
  287. // 新用户注册
  288. if (thirdAccount is null)
  289. {
  290. thirdAccount = dto.Adapt<ThirdAccount>();
  291. thirdToken.Adapt(thirdAccount);
  292. thirdAccount.PhoneNumber = phone.PhoneNumber;
  293. thirdAccount.Id = await _thirdAccountRepository.AddAsync(thirdAccount);
  294. await _thirdAccountDomainFactory.RegisterAsync(thirdAccount, token);
  295. }
  296. return await GetJwtToken(thirdAccount, token);
  297. }
  298. public async Task<Dictionary<string, object>> RefreshTokenAsync(string openId, CancellationToken token)
  299. {
  300. var thirdAccount = await _thirdAccountRepository.GetByOpenIdAsync(openId, token)
  301. ?? throw UserFriendlyException.SameMessage("未找到用户信息");
  302. return await GetJwtToken(thirdAccount, token);
  303. }
  304. private async Task<Dictionary<string, object>> GetJwtToken(ThirdAccount thirdAccount, CancellationToken cancel)
  305. {
  306. var jwtOptions = _identityOptionsAccessor.Value.Jwt;
  307. var claims = new List<Claim>
  308. {
  309. new(JwtClaimTypes.Subject, thirdAccount.Id),
  310. new(JwtClaimTypes.PhoneNumber, thirdAccount.PhoneNumber ?? string.Empty),
  311. new(JwtClaimTypes.Scope, jwtOptions.Scope),//todo 三方账号的scope
  312. new(AppClaimTypes.OpenId, thirdAccount.OpenId),
  313. };
  314. claims = await _thirdAccountDomainFactory.GetClaimAsync(thirdAccount, claims, cancel);
  315. var audience = new AudienceTicket(thirdAccount.Id);
  316. var expiredSeconds = jwtOptions.Expired <= 0 ? 3600 : jwtOptions.Expired;
  317. await _cacheAudience.SetAsync(audience.Id, audience, TimeSpan.FromSeconds(expiredSeconds));
  318. var token = _jwtSecurity.EncodeJwtToken(claims, audience.Ticket);
  319. var dicOutData = new Dictionary<string, object>()
  320. {
  321. { "Token", token },
  322. { "OpenId", thirdAccount.OpenId },
  323. { "PhoneNumber", thirdAccount.PhoneNumber },
  324. { "UserName", thirdAccount.UserName }
  325. };
  326. dicOutData = await _thirdAccountDomainFactory.GetLoginOutDataAsync(thirdAccount, dicOutData, cancel);
  327. return dicOutData;
  328. }
  329. }