1
0

AuthService.cs 12 KB

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