DiTuiAPIService.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Identity;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System;
  5. using System.Diagnostics;
  6. using System.Threading.Tasks;
  7. using ZhonTai.Admin.Core.Attributes;
  8. using ZhonTai.Admin.Core.Consts;
  9. using ZhonTai.Admin.Core.Dto;
  10. using ZhonTai.Admin.Domain.User;
  11. using ZhonTai.Admin.Services.Auth.Dto;
  12. using ZhonTai.Admin.Services.DiTuiAPI.Dto;
  13. using ZhonTai.Common.Helpers;
  14. using ZhonTai.DynamicApi;
  15. using ZhonTai.DynamicApi.Attributes;
  16. using ZhonTai.Admin.Domain.Platform;
  17. using ZhonTai.Admin.Core.Configs;
  18. using ZhonTai.Admin.Domain.Tenant;
  19. using System.Security.Claims;
  20. using ZhonTai.Admin.Core.Auth;
  21. using ZhonTai.Common.Extensions;
  22. using System.Linq.Expressions;
  23. using ZhonTai.Admin.Domain.UserOrg;
  24. using ZhonTai.Admin.Domain.UserRole;
  25. using ZhonTai.Admin.Domain.UserStaff;
  26. using ZhonTai.Admin.Services.User.Dto;
  27. namespace ZhonTai.Admin.Services.DiTuiAPI
  28. {
  29. /// <summary>
  30. /// 前端接口
  31. /// </summary>
  32. [DynamicApi(Area = AdminConsts.DiTuiName)]
  33. public class DiTuiAPIService : BaseService, IDiTuiAPIService, IDynamicApi
  34. {
  35. private IPasswordHasher<PlatformUserEntity> _passwordHasher => LazyGetRequiredService<IPasswordHasher<PlatformUserEntity>>();
  36. private readonly AppConfig _appConfig;
  37. private readonly IUserRepository _userRepository;
  38. private readonly IPlatformUserRepository _platformUserRepository;
  39. private readonly ITenantRepository _tenantRepository;
  40. public DiTuiAPIService(
  41. IPlatformUserRepository platformUserRepository,
  42. AppConfig appConfig,
  43. ITenantRepository tenantRepository
  44. )
  45. {
  46. _platformUserRepository = platformUserRepository;
  47. _appConfig = appConfig;
  48. _tenantRepository = tenantRepository;
  49. }
  50. [HttpPost]
  51. [AllowAnonymous]
  52. [NoOprationLog]
  53. public async Task<dynamic> LoginAsync(LoginInput input)
  54. {
  55. using (_platformUserRepository.DataFilter.DisableAll())
  56. {
  57. var sw = new Stopwatch();
  58. sw.Start();
  59. #region 验证码校验
  60. //if (_appConfig.VarifyCode.Enable)
  61. //{
  62. // if (input.CaptchaId.IsNull() || input.CaptchaData.IsNull())
  63. // {
  64. // throw ResultOutput.Exception("请完成安全验证");
  65. // }
  66. // var validateResult = _captcha.Validate(input.CaptchaId, JsonConvert.DeserializeObject<SlideTrack>(input.CaptchaData));
  67. // if (validateResult.Result != ValidateResultType.Success)
  68. // {
  69. // throw ResultOutput.Exception($"安全{validateResult.Message},请重新登录");
  70. // }
  71. //}
  72. #endregion
  73. #region 密码解密
  74. //if (input.PasswordKey.NotNull())
  75. //{
  76. // var passwordEncryptKey = CacheKeys.PassWordEncrypt + input.PasswordKey;
  77. // var existsPasswordKey = await Cache.ExistsAsync(passwordEncryptKey);
  78. // if (existsPasswordKey)
  79. // {
  80. // var secretKey = await Cache.GetAsync(passwordEncryptKey);
  81. // if (secretKey.IsNull())
  82. // {
  83. // throw ResultOutput.Exception("解密失败");
  84. // }
  85. // input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
  86. // await Cache.DelAsync(passwordEncryptKey);
  87. // }
  88. // else
  89. // {
  90. // throw ResultOutput.Exception("解密失败");
  91. // }
  92. //}
  93. #endregion
  94. #region 登录
  95. var user = await _platformUserRepository.Select.Where(a => a.Phone == input.mobile).ToOneAsync();
  96. var valid = user?.Id > 0;
  97. if (valid)
  98. {
  99. var password = MD5Encrypt.Encrypt32(input.pwd);
  100. valid = user.Password == password;
  101. }
  102. if (!valid)
  103. {
  104. throw ResultOutput.Exception("用户名或密码错误");
  105. }
  106. //if (!user.Enabled)
  107. //{
  108. // throw ResultOutput.Exception("账号已停用,禁止登录");
  109. //}
  110. #endregion
  111. #region 获得token
  112. var authLoginOutput = Mapper.Map<AuthLoginOutput>(user);
  113. if (_appConfig.Tenant)
  114. {
  115. var tenant = await _tenantRepository.Select.WhereDynamic(user.TenantId).ToOneAsync<AuthLoginTenantDto>();
  116. if (!(tenant != null && tenant.Enabled))
  117. {
  118. throw ResultOutput.Exception("企业已停用,禁止登录");
  119. }
  120. authLoginOutput.Tenant = tenant;
  121. }
  122. string token = GetToken(authLoginOutput);
  123. #endregion
  124. sw.Stop();
  125. #region 添加登录日志
  126. //var loginLogAddInput = new LoginLogAddInput
  127. //{
  128. // TenantId = authLoginOutput.TenantId,
  129. // Name = authLoginOutput.Name,
  130. // ElapsedMilliseconds = sw.ElapsedMilliseconds,
  131. // Status = true,
  132. // CreatedUserId = authLoginOutput.Id,
  133. // CreatedUserName = user.UserName,
  134. //};
  135. //await LazyGetRequiredService<ILoginLogService>().AddAsync(loginLogAddInput);
  136. #endregion 添加登录日志
  137. return new { token };
  138. }
  139. throw new NotImplementedException();
  140. }
  141. /// <summary>
  142. /// 新增用户
  143. /// </summary>
  144. /// <param name="input"></param>
  145. /// <returns></returns>
  146. [HttpPost]
  147. [AllowAnonymous]
  148. [NoOprationLog]
  149. [AdminTransaction]
  150. public virtual async Task<long> RegisterAsync(RegisterInput input)
  151. {
  152. Expression<Func<PlatformUserEntity, bool>> where = (a => a.Phone == input.Phone);
  153. where = where.Or(input.Phone.NotNull(), a => a.Phone == input.Phone)
  154. .Or(input.Name.NotNull(), a => a.Name == input.Name);
  155. var existsUser = await _platformUserRepository.Select.Where(where)
  156. .FirstAsync(a => new { a.Name, a.Phone });
  157. if (existsUser != null)
  158. {
  159. // 可能会有重名用户
  160. //if (existsUser.Name == input.Name)
  161. //{
  162. // throw ResultOutput.Exception($"账号已存在");
  163. //}
  164. if (input.Phone.NotNull() && existsUser.Phone == input.Phone)
  165. {
  166. throw ResultOutput.Exception($"手机号已存在");
  167. }
  168. //if (input.Name.NotNull() && existsUser.Name == input.Name)
  169. //{
  170. // throw ResultOutput.Exception($"姓名已存在");
  171. //}
  172. }
  173. // 用户信息
  174. if (input.Password.IsNull())
  175. {
  176. input.Password = _appConfig.DefaultPassword;
  177. }
  178. var entity = Mapper.Map<PlatformUserEntity>(input);
  179. //entity.Type = UserType.DefaultUser;
  180. entity.Password = MD5Encrypt.Encrypt32(input.Password);
  181. // 注册口注册用户皆为下级角色
  182. entity.Role = "2";
  183. var user = await _platformUserRepository.InsertAsync(entity);
  184. var userId = user.Id;
  185. //用户角色
  186. //if (input.RoleIds != null && input.RoleIds.Any())
  187. //{
  188. // var roles = input.RoleIds.Select(roleId => new UserRoleEntity
  189. // {
  190. // UserId = userId,
  191. // RoleId = roleId
  192. // }).ToList();
  193. // await _userRoleRepository.InsertAsync(roles);
  194. //}
  195. // 员工信息
  196. //var staff = input.Staff == null ? new UserStaffEntity() : Mapper.Map<UserStaffEntity>(input.Staff);
  197. //staff.Id = userId;
  198. //await _staffRepository.InsertAsync(staff);
  199. ////所属部门
  200. //if (input.OrgIds != null && input.OrgIds.Any())
  201. //{
  202. // var orgs = input.OrgIds.Select(orgId => new UserOrgEntity
  203. // {
  204. // UserId = userId,
  205. // OrgId = orgId
  206. // }).ToList();
  207. // await _userOrgRepository.InsertAsync(orgs);
  208. //}
  209. return userId;
  210. }
  211. /// <summary>
  212. /// 获得token
  213. /// </summary>
  214. /// <param name="user">用户信息</param>
  215. /// <returns></returns>
  216. private string GetToken(AuthLoginOutput user)
  217. {
  218. if (user == null)
  219. {
  220. return string.Empty;
  221. }
  222. var token = LazyGetRequiredService<IUserToken>().Create(new[]
  223. {
  224. new Claim(ClaimAttributes.UserId, user.Id.ToString(), ClaimValueTypes.Integer64),
  225. new Claim(ClaimAttributes.UserName, user.UserName),
  226. new Claim(ClaimAttributes.Name, user.Name),
  227. new Claim(ClaimAttributes.UserType, user.Type.ToInt().ToString(), ClaimValueTypes.Integer32),
  228. new Claim(ClaimAttributes.TenantId, user.TenantId.ToString(), ClaimValueTypes.Integer64),
  229. new Claim(ClaimAttributes.TenantType, user.Tenant?.TenantType.ToInt().ToString(), ClaimValueTypes.Integer32),
  230. new Claim(ClaimAttributes.DbKey, user.Tenant?.DbKey??"")
  231. });
  232. return token;
  233. }
  234. }
  235. }