DiTuiAPIService.cs 12 KB

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