AuthService.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Claims;
  6. using System.Threading.Tasks;
  7. using Microsoft.AspNetCore.Authorization;
  8. using Microsoft.AspNetCore.Cors;
  9. using Microsoft.AspNetCore.Mvc;
  10. using Microsoft.AspNetCore.Mvc.ModelBinding;
  11. using Microsoft.IdentityModel.Tokens;
  12. using Microsoft.IdentityModel.JsonWebTokens;
  13. using ZhonTai.Admin.Core.Auth;
  14. using ZhonTai.Admin.Core.Attributes;
  15. using ZhonTai.Admin.Core.Configs;
  16. using ZhonTai.Admin.Core.Consts;
  17. using ZhonTai.Admin.Core.Dto;
  18. using ZhonTai.Admin.Domain.Permission;
  19. using ZhonTai.Admin.Domain.User;
  20. using ZhonTai.Admin.Domain.Tenant;
  21. using ZhonTai.Admin.Services.Auth.Dto;
  22. using ZhonTai.Admin.Domain.RolePermission;
  23. using ZhonTai.Admin.Domain.UserRole;
  24. using ZhonTai.Admin.Tools.Captcha;
  25. using ZhonTai.Admin.Services.LoginLog.Dto;
  26. using ZhonTai.Admin.Services.LoginLog;
  27. using ZhonTai.Admin.Services.User;
  28. using ZhonTai.Common.Extensions;
  29. using ZhonTai.Common.Helpers;
  30. using ZhonTai.DynamicApi;
  31. using ZhonTai.DynamicApi.Attributes;
  32. using FreeSql;
  33. using ZhonTai.Admin.Domain.TenantPermission;
  34. using Microsoft.AspNetCore.Identity;
  35. using System.Collections.Generic;
  36. namespace ZhonTai.Admin.Services.Auth;
  37. /// <summary>
  38. /// 认证授权服务
  39. /// </summary>
  40. [DynamicApi(Area = AdminConsts.AreaName)]
  41. public class AuthService : BaseService, IAuthService, IDynamicApi
  42. {
  43. private readonly AppConfig _appConfig;
  44. private readonly JwtConfig _jwtConfig;
  45. private readonly IPermissionRepository _permissionRepository;
  46. private readonly IUserRepository _userRepository;
  47. private readonly ITenantRepository _tenantRepository;
  48. private readonly ICaptchaTool _captchaTool;
  49. private IPasswordHasher<UserEntity> _passwordHasher => LazyGetRequiredService<IPasswordHasher<UserEntity>>();
  50. public AuthService(
  51. AppConfig appConfig,
  52. JwtConfig jwtConfig,
  53. IUserRepository userRepository,
  54. IPermissionRepository permissionRepository,
  55. ITenantRepository tenantRepository,
  56. ICaptchaTool captchaTool
  57. )
  58. {
  59. _appConfig = appConfig;
  60. _jwtConfig = jwtConfig;
  61. _userRepository = userRepository;
  62. _permissionRepository = permissionRepository;
  63. _tenantRepository = tenantRepository;
  64. _captchaTool = captchaTool;
  65. }
  66. /// <summary>
  67. /// 获得token
  68. /// </summary>
  69. /// <param name="user">用户信息</param>
  70. /// <returns></returns>
  71. private string GetToken(AuthLoginOutput user)
  72. {
  73. if (user == null)
  74. {
  75. return string.Empty;
  76. }
  77. var token = LazyGetRequiredService<IUserToken>().Create(new[]
  78. {
  79. new Claim(ClaimAttributes.UserId, user.Id.ToString(), ClaimValueTypes.Integer64),
  80. new Claim(ClaimAttributes.UserName, user.UserName),
  81. new Claim(ClaimAttributes.Name, user.Name),
  82. new Claim(ClaimAttributes.UserType, user.Type.ToInt().ToString(), ClaimValueTypes.Integer32),
  83. new Claim(ClaimAttributes.TenantId, user.TenantId.ToString(), ClaimValueTypes.Integer64),
  84. new Claim(ClaimAttributes.TenantType, user.TenantType.ToInt().ToString(), ClaimValueTypes.Integer32),
  85. new Claim(ClaimAttributes.DbKey, user.DbKey??"")
  86. });
  87. return token;
  88. }
  89. /// <summary>
  90. /// 查询密钥
  91. /// </summary>
  92. /// <returns></returns>
  93. [HttpGet]
  94. [AllowAnonymous]
  95. [NoOprationLog]
  96. public async Task<AuthGetPasswordEncryptKeyOutput> GetPasswordEncryptKeyAsync()
  97. {
  98. //写入Redis
  99. var guid = Guid.NewGuid().ToString("N");
  100. var key = CacheKeys.PassWordEncrypt + guid;
  101. var encyptKey = StringHelper.GenerateRandom(8);
  102. await Cache.SetAsync(key, encyptKey, TimeSpan.FromMinutes(5));
  103. return new AuthGetPasswordEncryptKeyOutput { Key = guid, EncyptKey = encyptKey };
  104. }
  105. /// <summary>
  106. /// 查询用户个人信息
  107. /// </summary>
  108. /// <returns></returns>
  109. [Login]
  110. public async Task<AuthUserProfileDto> GetUserProfileAsync()
  111. {
  112. if (!(User?.Id > 0))
  113. {
  114. throw ResultOutput.Exception("未登录");
  115. }
  116. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  117. {
  118. var profile = await _userRepository.GetAsync<AuthUserProfileDto>(User.Id);
  119. return profile;
  120. }
  121. }
  122. /// <summary>
  123. /// 查询用户菜单列表
  124. /// </summary>
  125. /// <returns></returns>
  126. [Login]
  127. public async Task<List<AuthUserMenuDto>> GetUserMenusAsync()
  128. {
  129. if (!(User?.Id > 0))
  130. {
  131. throw ResultOutput.Exception("未登录");
  132. }
  133. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  134. {
  135. var menuSelect = _permissionRepository.Select;
  136. if (!User.PlatformAdmin)
  137. {
  138. var db = _permissionRepository.Orm;
  139. if (User.TenantAdmin)
  140. {
  141. menuSelect = menuSelect.Where(a =>
  142. db.Select<TenantPermissionEntity>()
  143. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  144. .Any()
  145. );
  146. }
  147. else
  148. {
  149. menuSelect = menuSelect.Where(a =>
  150. db.Select<RolePermissionEntity>()
  151. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  152. .Where(b => b.PermissionId == a.Id)
  153. .Any()
  154. );
  155. }
  156. menuSelect = menuSelect.AsTreeCte(up: true);
  157. }
  158. var menuList = await menuSelect
  159. .Where(a => new[] { PermissionType.Group, PermissionType.Menu }.Contains(a.Type))
  160. .ToListAsync(a => new AuthUserMenuDto { ViewPath = a.View.Path });
  161. return menuList.DistinctBy(a => a.Id).OrderBy(a => a.ParentId).ThenBy(a => a.Sort).ToList();
  162. }
  163. }
  164. /// <summary>
  165. /// 查询用户权限列表
  166. /// </summary>
  167. /// <returns></returns>
  168. [Login]
  169. public async Task<AuthGetUserPermissionsOutput> GetUserPermissionsAsync()
  170. {
  171. if (!(User?.Id > 0))
  172. {
  173. throw ResultOutput.Exception("未登录");
  174. }
  175. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  176. {
  177. var authGetUserPermissionsOutput = new AuthGetUserPermissionsOutput
  178. {
  179. //用户信息
  180. User = await _userRepository.GetAsync<AuthUserProfileDto>(User.Id)
  181. };
  182. var dotSelect = _permissionRepository.Select.Where(a => a.Type == PermissionType.Dot);
  183. if (!User.PlatformAdmin)
  184. {
  185. var db = _permissionRepository.Orm;
  186. if (User.TenantAdmin)
  187. {
  188. dotSelect = dotSelect.Where(a =>
  189. db.Select<TenantPermissionEntity>()
  190. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  191. .Any()
  192. );
  193. }
  194. else
  195. {
  196. dotSelect = dotSelect.Where(a =>
  197. db.Select<RolePermissionEntity>()
  198. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  199. .Where(b => b.PermissionId == a.Id)
  200. .Any()
  201. );
  202. }
  203. }
  204. //用户权限点
  205. authGetUserPermissionsOutput.Permissions = await dotSelect.ToListAsync(a => a.Code);
  206. return authGetUserPermissionsOutput;
  207. }
  208. }
  209. /// <summary>
  210. /// 查询用户信息
  211. /// </summary>
  212. /// <returns></returns>
  213. [Login]
  214. public async Task<AuthGetUserInfoOutput> GetUserInfoAsync()
  215. {
  216. if (!(User?.Id > 0))
  217. {
  218. throw ResultOutput.Exception("未登录");
  219. }
  220. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  221. {
  222. var authGetUserInfoOutput = new AuthGetUserInfoOutput
  223. {
  224. //用户信息
  225. User = await _userRepository.GetAsync<AuthUserProfileDto>(User.Id)
  226. };
  227. var menuSelect = _permissionRepository.Select;
  228. var dotSelect = _permissionRepository.Select.Where(a => a.Type == PermissionType.Dot);
  229. if (!User.PlatformAdmin)
  230. {
  231. var db = _permissionRepository.Orm;
  232. if (User.TenantAdmin)
  233. {
  234. menuSelect = menuSelect.Where(a =>
  235. db.Select<TenantPermissionEntity>()
  236. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  237. .Any()
  238. );
  239. dotSelect = dotSelect.Where(a =>
  240. db.Select<TenantPermissionEntity>()
  241. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  242. .Any()
  243. );
  244. }
  245. else
  246. {
  247. menuSelect = menuSelect.Where(a =>
  248. db.Select<RolePermissionEntity>()
  249. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  250. .Where(b => b.PermissionId == a.Id)
  251. .Any()
  252. );
  253. dotSelect = dotSelect.Where(a =>
  254. db.Select<RolePermissionEntity>()
  255. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  256. .Where(b => b.PermissionId == a.Id)
  257. .Any()
  258. );
  259. }
  260. menuSelect = menuSelect.AsTreeCte(up: true);
  261. }
  262. var menuList = await menuSelect
  263. .Where(a => new[] { PermissionType.Group, PermissionType.Menu }.Contains(a.Type))
  264. .ToListAsync(a => new AuthUserMenuDto { ViewPath = a.View.Path });
  265. //用户菜单
  266. authGetUserInfoOutput.Menus = menuList.DistinctBy(a => a.Id).OrderBy(a => a.ParentId).ThenBy(a => a.Sort).ToList();
  267. //用户权限点
  268. authGetUserInfoOutput.Permissions = await dotSelect.ToListAsync(a => a.Code);
  269. return authGetUserInfoOutput;
  270. }
  271. }
  272. /// <summary>
  273. /// 登录
  274. /// </summary>
  275. /// <param name="input"></param>
  276. /// <returns></returns>
  277. [HttpPost]
  278. [AllowAnonymous]
  279. [NoOprationLog]
  280. public async Task<dynamic> LoginAsync(AuthLoginInput input)
  281. {
  282. using (_userRepository.DataFilter.DisableAll())
  283. {
  284. var sw = new Stopwatch();
  285. sw.Start();
  286. #region 验证码校验
  287. if (_appConfig.VarifyCode.Enable)
  288. {
  289. input.Captcha.DeleteCache = true;
  290. input.Captcha.CaptchaKey = CacheKeys.Captcha;
  291. var isOk = await _captchaTool.CheckAsync(input.Captcha);
  292. if (!isOk)
  293. {
  294. throw ResultOutput.Exception("安全验证不通过,请重新登录");
  295. }
  296. }
  297. #endregion
  298. #region 密码解密
  299. if (input.PasswordKey.NotNull())
  300. {
  301. var passwordEncryptKey = CacheKeys.PassWordEncrypt + input.PasswordKey;
  302. var existsPasswordKey = await Cache.ExistsAsync(passwordEncryptKey);
  303. if (existsPasswordKey)
  304. {
  305. var secretKey = await Cache.GetAsync(passwordEncryptKey);
  306. if (secretKey.IsNull())
  307. {
  308. throw ResultOutput.Exception("解密失败");
  309. }
  310. input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
  311. await Cache.DelAsync(passwordEncryptKey);
  312. }
  313. else
  314. {
  315. throw ResultOutput.Exception("解密失败!");
  316. }
  317. }
  318. #endregion
  319. #region 登录
  320. var user = await _userRepository.Select.Where(a => a.UserName == input.UserName).ToOneAsync();
  321. var valid = user?.Id > 0;
  322. if(valid)
  323. {
  324. if (user.PasswordEncryptType == PasswordEncryptType.PasswordHasher)
  325. {
  326. var passwordVerificationResult = _passwordHasher.VerifyHashedPassword(user, user.Password, input.Password);
  327. valid = passwordVerificationResult == PasswordVerificationResult.Success || passwordVerificationResult == PasswordVerificationResult.SuccessRehashNeeded;
  328. }
  329. else
  330. {
  331. var password = MD5Encrypt.Encrypt32(input.Password);
  332. valid = user.Password == password;
  333. }
  334. }
  335. if (!valid)
  336. {
  337. throw ResultOutput.Exception("用户名或密码错误");
  338. }
  339. if (user.Status == UserStatus.Disabled)
  340. {
  341. throw ResultOutput.Exception("禁止登录,请联系管理员");
  342. }
  343. #endregion
  344. #region 获得token
  345. var authLoginOutput = Mapper.Map<AuthLoginOutput>(user);
  346. if (_appConfig.Tenant)
  347. {
  348. var tenant = await _tenantRepository.Select.WhereDynamic(user.TenantId).ToOneAsync(a => new { a.TenantType, a.DbKey });
  349. authLoginOutput.TenantType = tenant.TenantType;
  350. authLoginOutput.DbKey = tenant.DbKey;
  351. }
  352. string token = GetToken(authLoginOutput);
  353. #endregion
  354. sw.Stop();
  355. #region 添加登录日志
  356. var loginLogAddInput = new LoginLogAddInput
  357. {
  358. TenantId = authLoginOutput.TenantId,
  359. Name = authLoginOutput.Name,
  360. ElapsedMilliseconds = sw.ElapsedMilliseconds,
  361. Status = true,
  362. CreatedUserId = authLoginOutput.Id,
  363. CreatedUserName = input.UserName,
  364. };
  365. await LazyGetRequiredService<ILoginLogService>().AddAsync(loginLogAddInput);
  366. #endregion 添加登录日志
  367. return new { token };
  368. }
  369. }
  370. /// <summary>
  371. /// 刷新Token
  372. /// 以旧换新
  373. /// </summary>
  374. /// <param name="token"></param>
  375. /// <returns></returns>
  376. [HttpGet]
  377. [AllowAnonymous]
  378. public async Task<dynamic> Refresh([BindRequired] string token)
  379. {
  380. var jwtSecurityToken = LazyGetRequiredService<IUserToken>().Decode(token);
  381. var userClaims = jwtSecurityToken?.Claims?.ToArray();
  382. if (userClaims == null || userClaims.Length == 0)
  383. {
  384. throw ResultOutput.Exception("无法解析token");
  385. }
  386. var refreshExpires = userClaims.FirstOrDefault(a => a.Type == ClaimAttributes.RefreshExpires)?.Value;
  387. if (refreshExpires.IsNull() || refreshExpires.ToLong() <= DateTime.Now.ToTimestamp())
  388. {
  389. throw ResultOutput.Exception("登录信息已过期");
  390. }
  391. var userId = userClaims.FirstOrDefault(a => a.Type == ClaimAttributes.UserId)?.Value;
  392. if (userId.IsNull())
  393. {
  394. throw ResultOutput.Exception("登录信息已失效");
  395. }
  396. //验签
  397. var securityKey = _jwtConfig.SecurityKey;
  398. var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey)), SecurityAlgorithms.HmacSha256);
  399. var input = jwtSecurityToken.RawHeader + "." + jwtSecurityToken.RawPayload;
  400. if (jwtSecurityToken.RawSignature != JwtTokenUtilities.CreateEncodedSignature(input, signingCredentials))
  401. {
  402. throw ResultOutput.Exception("验签失败");
  403. }
  404. var output = await LazyGetRequiredService<IUserService>().GetLoginUserAsync(userId.ToLong());
  405. string newToken = GetToken(output);
  406. return new { token = newToken };
  407. }
  408. /// <summary>
  409. /// 获取验证数据
  410. /// </summary>
  411. /// <returns></returns>
  412. [HttpGet]
  413. [AllowAnonymous]
  414. [NoOprationLog]
  415. [EnableCors(AdminConsts.AllowAnyPolicyName)]
  416. public async Task<CaptchaOutput> GetCaptcha()
  417. {
  418. var data = await _captchaTool.GetAsync(CacheKeys.Captcha);
  419. return data;
  420. }
  421. /// <summary>
  422. /// 检查验证数据
  423. /// </summary>
  424. /// <returns></returns>
  425. [HttpGet]
  426. [AllowAnonymous]
  427. [NoOprationLog]
  428. [EnableCors(AdminConsts.AllowAnyPolicyName)]
  429. public async Task CheckCaptcha([FromQuery] CaptchaInput input)
  430. {
  431. input.CaptchaKey = CacheKeys.Captcha;
  432. var check = await _captchaTool.CheckAsync(input);
  433. if (!check)
  434. {
  435. throw ResultOutput.Exception("安全验证不通过");
  436. }
  437. }
  438. }