AuthService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 StackExchange.Profiling;
  8. using Microsoft.AspNetCore.Authorization;
  9. using Microsoft.AspNetCore.Cors;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.Mvc.ModelBinding;
  12. using Microsoft.IdentityModel.Tokens;
  13. using Microsoft.IdentityModel.JsonWebTokens;
  14. using ZhonTai.Admin.Core.Auth;
  15. using ZhonTai.Admin.Core.Attributes;
  16. using ZhonTai.Admin.Core.Configs;
  17. using ZhonTai.Admin.Core.Consts;
  18. using ZhonTai.Admin.Core.Dto;
  19. using ZhonTai.Admin.Domain.Permission;
  20. using ZhonTai.Admin.Domain.User;
  21. using ZhonTai.Admin.Domain.Tenant;
  22. using ZhonTai.Admin.Services.Auth.Dto;
  23. using ZhonTai.Admin.Domain.RolePermission;
  24. using ZhonTai.Admin.Domain.UserRole;
  25. using ZhonTai.Admin.Tools.Captcha;
  26. using ZhonTai.Admin.Services.LoginLog.Dto;
  27. using ZhonTai.Admin.Services.LoginLog;
  28. using ZhonTai.Admin.Services.User;
  29. using ZhonTai.Common.Extensions;
  30. using ZhonTai.Common.Helpers;
  31. using ZhonTai.DynamicApi;
  32. using ZhonTai.DynamicApi.Attributes;
  33. using FreeSql;
  34. using ZhonTai.Admin.Domain.TenantPermission;
  35. namespace ZhonTai.Admin.Services.Auth;
  36. /// <summary>
  37. /// 认证授权服务
  38. /// </summary>
  39. [DynamicApi(Area = AdminConsts.AreaName)]
  40. public class AuthService : BaseService, IAuthService, IDynamicApi
  41. {
  42. private readonly AppConfig _appConfig;
  43. private readonly JwtConfig _jwtConfig;
  44. private readonly IPermissionRepository _permissionRepository;
  45. private readonly IUserRepository _userRepository;
  46. private readonly ITenantRepository _tenantRepository;
  47. private readonly ICaptchaTool _captchaTool;
  48. public AuthService(
  49. AppConfig appConfig,
  50. JwtConfig jwtConfig,
  51. IUserRepository userRepository,
  52. IPermissionRepository permissionRepository,
  53. ITenantRepository tenantRepository,
  54. ICaptchaTool captchaTool
  55. )
  56. {
  57. _appConfig = appConfig;
  58. _jwtConfig = jwtConfig;
  59. _userRepository = userRepository;
  60. _permissionRepository = permissionRepository;
  61. _tenantRepository = tenantRepository;
  62. _captchaTool = captchaTool;
  63. }
  64. /// <summary>
  65. /// 获得token
  66. /// </summary>
  67. /// <param name="user">用户信息</param>
  68. /// <returns></returns>
  69. private string GetToken(AuthLoginOutput user)
  70. {
  71. if (user == null)
  72. {
  73. return string.Empty;
  74. }
  75. var token = LazyGetRequiredService<IUserToken>().Create(new[]
  76. {
  77. new Claim(ClaimAttributes.UserId, user.Id.ToString(), ClaimValueTypes.Integer64),
  78. new Claim(ClaimAttributes.UserName, user.UserName),
  79. new Claim(ClaimAttributes.Name, user.Name),
  80. new Claim(ClaimAttributes.UserType, user.Type.ToInt().ToString(), ClaimValueTypes.Integer32),
  81. new Claim(ClaimAttributes.TenantId, user.TenantId.ToString(), ClaimValueTypes.Integer64),
  82. new Claim(ClaimAttributes.TenantType, user.TenantType.ToInt().ToString(), ClaimValueTypes.Integer32),
  83. new Claim(ClaimAttributes.DbKey, user.DbKey??"")
  84. });
  85. return token;
  86. }
  87. /// <summary>
  88. /// 查询密钥
  89. /// </summary>
  90. /// <returns></returns>
  91. [HttpGet]
  92. [AllowAnonymous]
  93. [NoOprationLog]
  94. public async Task<AuthGetPasswordEncryptKeyOutput> GetPasswordEncryptKeyAsync()
  95. {
  96. //写入Redis
  97. var guid = Guid.NewGuid().ToString("N");
  98. var key = CacheKeys.PassWordEncrypt + guid;
  99. var encyptKey = StringHelper.GenerateRandom(8);
  100. await Cache.SetAsync(key, encyptKey, TimeSpan.FromMinutes(5));
  101. return new AuthGetPasswordEncryptKeyOutput { Key = guid, EncyptKey = encyptKey };
  102. }
  103. /// <summary>
  104. /// 查询用户信息
  105. /// </summary>
  106. /// <returns></returns>
  107. [Login]
  108. public async Task<AuthGetUserInfoOutput> GetUserInfoAsync()
  109. {
  110. if (!(User?.Id > 0))
  111. {
  112. throw ResultOutput.Exception("未登录");
  113. }
  114. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  115. {
  116. var authGetUserInfoOutput = new AuthGetUserInfoOutput
  117. {
  118. //用户信息
  119. User = await _userRepository.GetAsync<AuthUserProfileDto>(User.Id)
  120. };
  121. var menuSelect = _permissionRepository.Select;
  122. var dotSelect = _permissionRepository.Select.Where(a => a.Type == PermissionType.Dot);
  123. if (!User.PlatformAdmin)
  124. {
  125. var db = _permissionRepository.Orm;
  126. if (User.TenantAdmin)
  127. {
  128. menuSelect = menuSelect.Where(a =>
  129. db.Select<TenantPermissionEntity>()
  130. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  131. .Any()
  132. );
  133. dotSelect = dotSelect.Where(a =>
  134. db.Select<TenantPermissionEntity>()
  135. .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
  136. .Any()
  137. );
  138. }
  139. else
  140. {
  141. menuSelect = menuSelect.Where(a =>
  142. db.Select<RolePermissionEntity>()
  143. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  144. .Where(b => b.PermissionId == a.Id)
  145. .Any()
  146. );
  147. dotSelect = dotSelect.Where(a =>
  148. db.Select<RolePermissionEntity>()
  149. .InnerJoin<UserRoleEntity>((b, c) => b.RoleId == c.RoleId && c.UserId == User.Id)
  150. .Where(b => b.PermissionId == a.Id)
  151. .Any()
  152. );
  153. }
  154. menuSelect = menuSelect.AsTreeCte(up: true);
  155. }
  156. var menuList = await menuSelect
  157. .Where(a => new[] { PermissionType.Group, PermissionType.Menu }.Contains(a.Type))
  158. .ToListAsync(a => new AuthUserMenuDto { ViewPath = a.View.Path });
  159. //用户菜单
  160. authGetUserInfoOutput.Menus = menuList.DistinctBy(a => a.Id).OrderBy(a => a.ParentId).ThenBy(a => a.Sort).ToList();
  161. //用户权限点
  162. authGetUserInfoOutput.Permissions = await dotSelect.ToListAsync(a => a.Code);
  163. return authGetUserInfoOutput;
  164. }
  165. }
  166. /// <summary>
  167. /// 登录
  168. /// </summary>
  169. /// <param name="input"></param>
  170. /// <returns></returns>
  171. [HttpPost]
  172. [AllowAnonymous]
  173. [NoOprationLog]
  174. public async Task<dynamic> LoginAsync(AuthLoginInput input)
  175. {
  176. using (_userRepository.DataFilter.Disable(FilterNames.Tenant, FilterNames.Self, FilterNames.Data))
  177. {
  178. var sw = new Stopwatch();
  179. sw.Start();
  180. #region 验证码校验
  181. if (_appConfig.VarifyCode.Enable)
  182. {
  183. input.Captcha.DeleteCache = true;
  184. input.Captcha.CaptchaKey = CacheKeys.Captcha;
  185. var isOk = await _captchaTool.CheckAsync(input.Captcha);
  186. if (!isOk)
  187. {
  188. throw ResultOutput.Exception("安全验证不通过,请重新登录");
  189. }
  190. }
  191. #endregion
  192. #region 密码解密
  193. if (input.PasswordKey.NotNull())
  194. {
  195. var passwordEncryptKey = CacheKeys.PassWordEncrypt + input.PasswordKey;
  196. var existsPasswordKey = await Cache.ExistsAsync(passwordEncryptKey);
  197. if (existsPasswordKey)
  198. {
  199. var secretKey = await Cache.GetAsync(passwordEncryptKey);
  200. if (secretKey.IsNull())
  201. {
  202. throw ResultOutput.Exception("解密失败");
  203. }
  204. input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
  205. await Cache.DelAsync(passwordEncryptKey);
  206. }
  207. else
  208. {
  209. throw ResultOutput.Exception("解密失败!");
  210. }
  211. }
  212. #endregion
  213. #region 登录
  214. var password = MD5Encrypt.Encrypt32(input.Password);
  215. var user = await _userRepository.Select.Where(a => a.UserName == input.UserName && a.Password == password).ToOneAsync();
  216. if (!(user?.Id > 0))
  217. {
  218. throw ResultOutput.Exception("用户名或密码错误");
  219. }
  220. if (user.Status == UserStatus.Disabled)
  221. {
  222. throw ResultOutput.Exception("禁止登录,请联系管理员");
  223. }
  224. #endregion
  225. #region 获得token
  226. var authLoginOutput = Mapper.Map<AuthLoginOutput>(user);
  227. if (_appConfig.Tenant)
  228. {
  229. var tenant = await _tenantRepository.Select.WhereDynamic(user.TenantId).ToOneAsync(a => new { a.TenantType, a.DbKey });
  230. authLoginOutput.TenantType = tenant.TenantType;
  231. authLoginOutput.DbKey = tenant.DbKey;
  232. }
  233. string token = GetToken(authLoginOutput);
  234. #endregion
  235. sw.Stop();
  236. #region 添加登录日志
  237. var loginLogAddInput = new LoginLogAddInput
  238. {
  239. TenantId = authLoginOutput.TenantId,
  240. Name = authLoginOutput.Name,
  241. ElapsedMilliseconds = sw.ElapsedMilliseconds,
  242. Status = true,
  243. CreatedUserId = authLoginOutput.Id,
  244. CreatedUserName = input.UserName,
  245. };
  246. await LazyGetRequiredService<ILoginLogService>().AddAsync(loginLogAddInput);
  247. #endregion 添加登录日志
  248. return new { token };
  249. }
  250. }
  251. /// <summary>
  252. /// 刷新Token
  253. /// 以旧换新
  254. /// </summary>
  255. /// <param name="token"></param>
  256. /// <returns></returns>
  257. [HttpGet]
  258. [AllowAnonymous]
  259. public async Task<dynamic> Refresh([BindRequired] string token)
  260. {
  261. var jwtSecurityToken = LazyGetRequiredService<IUserToken>().Decode(token);
  262. var userClaims = jwtSecurityToken?.Claims?.ToArray();
  263. if (userClaims == null || userClaims.Length == 0)
  264. {
  265. return ResultOutput.NotOk();
  266. }
  267. var refreshExpires = userClaims.FirstOrDefault(a => a.Type == ClaimAttributes.RefreshExpires)?.Value;
  268. if (refreshExpires.IsNull())
  269. {
  270. return ResultOutput.NotOk();
  271. }
  272. if (refreshExpires.ToLong() <= DateTime.Now.ToTimestamp())
  273. {
  274. return ResultOutput.NotOk("登录信息已过期");
  275. }
  276. var userId = userClaims.FirstOrDefault(a => a.Type == ClaimAttributes.UserId)?.Value;
  277. if (userId.IsNull())
  278. {
  279. return ResultOutput.NotOk("登录信息已失效");
  280. }
  281. //验签
  282. var securityKey = _jwtConfig.SecurityKey;
  283. var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey)), SecurityAlgorithms.HmacSha256);
  284. var input = jwtSecurityToken.RawHeader + "." + jwtSecurityToken.RawPayload;
  285. if (jwtSecurityToken.RawSignature != JwtTokenUtilities.CreateEncodedSignature(input, signingCredentials))
  286. {
  287. return ResultOutput.NotOk("验签失败");
  288. }
  289. var output = await LazyGetRequiredService<IUserService>().GetLoginUserAsync(userId.ToLong());
  290. string newToken = GetToken(output?.Data);
  291. return new { token = newToken };
  292. }
  293. /// <summary>
  294. /// 获取验证数据
  295. /// </summary>
  296. /// <returns></returns>
  297. [HttpGet]
  298. [AllowAnonymous]
  299. [NoOprationLog]
  300. [EnableCors(AdminConsts.AllowAnyPolicyName)]
  301. public async Task<CaptchaOutput> GetCaptcha()
  302. {
  303. var data = await _captchaTool.GetAsync(CacheKeys.Captcha);
  304. return data;
  305. }
  306. /// <summary>
  307. /// 检查验证数据
  308. /// </summary>
  309. /// <returns></returns>
  310. [HttpGet]
  311. [AllowAnonymous]
  312. [NoOprationLog]
  313. [EnableCors(AdminConsts.AllowAnyPolicyName)]
  314. public async Task<bool> CheckCaptcha([FromQuery] CaptchaInput input)
  315. {
  316. input.CaptchaKey = CacheKeys.Captcha;
  317. var result = await _captchaTool.CheckAsync(input);
  318. return result;
  319. }
  320. }