You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

688 lines
25 KiB

3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
  1. using IdentityModel.Client;
  2. using log4net.ObjectRenderer;
  3. using Microsoft.AspNetCore.Authorization;
  4. using Microsoft.AspNetCore.Identity;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Mvc.Routing;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Options;
  9. using Newtonsoft.Json;
  10. using NPOI.SS.Formula.Functions;
  11. using NPOI.SS.UserModel;
  12. using Shentun.Peis.Models;
  13. using Shentun.Peis.MyUser;
  14. using Shentun.Peis.OrganizationUnits;
  15. using Shentun.Peis.Permissions;
  16. using Shentun.Peis.RegisterCheckPictures;
  17. using Shentun.Peis.Sexs;
  18. using Shentun.Utilities;
  19. using SqlSugar;
  20. using System;
  21. using System.Collections.Generic;
  22. using System.Linq;
  23. using System.Net;
  24. using System.Net.Http;
  25. using System.Text;
  26. using System.Threading.Tasks;
  27. using Volo.Abp;
  28. using Volo.Abp.Account;
  29. using Volo.Abp.Application.Dtos;
  30. using Volo.Abp.Application.Services;
  31. using Volo.Abp.Caching;
  32. using Volo.Abp.Data;
  33. using Volo.Abp.DependencyInjection;
  34. using Volo.Abp.Domain.Repositories;
  35. using Volo.Abp.Identity;
  36. using Volo.Abp.ObjectExtending;
  37. using Volo.Abp.ObjectMapping;
  38. using Volo.Abp.Security.Encryption;
  39. using Volo.Abp.Users;
  40. namespace Shentun.Peis.MyUser
  41. {
  42. /// <summary>
  43. /// 重写IdentityUser服务
  44. /// </summary>
  45. [Dependency(ReplaceServices = true)]
  46. ////[RemoteService(isEnabled: false)]
  47. [ExposeServices(typeof(IIdentityUserAppService))]
  48. public class MyUserAppService : IdentityUserAppService
  49. {
  50. private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
  51. private readonly IdentityUserManager _userManager;
  52. private readonly IIdentityUserRepository _userRepository;
  53. private readonly IOptions<IdentityOptions> _identityOptions;
  54. private readonly IPasswordHasher<IdentityUser> _passwordHasher;
  55. private readonly IStringEncryptionService _stringEncryptionService;
  56. private readonly PeisOrganizationUnitManager _peisOrganizationUnitManager;
  57. private readonly IHttpClientFactory _httpClientFactory;
  58. private readonly IConfiguration _configuration;
  59. private readonly IRepository<OrganizationUnit, Guid> _organizationUnitRepository;
  60. private readonly IRepository<IdentityUserOrganizationUnit> _identityUserOrganizationUnitRepository;
  61. private readonly CurrentUser _currentUser;
  62. private readonly IDistributedCache<IdentityUser, Guid> _userCache;
  63. public MyUserAppService(
  64. IRepository<IdentityUser, Guid> identityUserRepository,
  65. IdentityUserManager userManager,
  66. IIdentityUserRepository userRepository,
  67. IIdentityRoleRepository roleRepository,
  68. IOptions<IdentityOptions> identityOptions,
  69. IPasswordHasher<IdentityUser> passwordHasher,
  70. IStringEncryptionService stringEncryptionService,
  71. IRepository<OrganizationUnit, Guid> organizationUnitRepository,
  72. PeisOrganizationUnitManager peisOrganizationUnitManager,
  73. IHttpClientFactory httpClientFactory,
  74. IConfiguration configuration,
  75. IRepository<IdentityUserOrganizationUnit> identityUserOrganizationUnitRepository,
  76. CurrentUser currentUser,
  77. IDistributedCache<IdentityUser, Guid> userCache) :
  78. base(userManager,
  79. userRepository,
  80. roleRepository,
  81. identityOptions)
  82. {
  83. this._identityUserRepository = identityUserRepository;
  84. this._userManager = userManager;
  85. this._userRepository = userRepository;
  86. this._identityOptions = identityOptions;
  87. this._passwordHasher = passwordHasher;
  88. this._stringEncryptionService = stringEncryptionService;
  89. this._peisOrganizationUnitManager = peisOrganizationUnitManager;
  90. this._httpClientFactory = httpClientFactory;
  91. this._configuration = configuration;
  92. this._organizationUnitRepository = organizationUnitRepository;
  93. this._identityUserOrganizationUnitRepository = identityUserOrganizationUnitRepository;
  94. this._currentUser = currentUser;
  95. _userCache = userCache;
  96. }
  97. /// <summary>
  98. /// 根据角色查询用户列表
  99. /// </summary>
  100. /// <param name="RoleName"></param>
  101. /// <returns></returns>
  102. [Authorize(PeisPermissions.Users.Default)]
  103. [HttpGet("api/identity/users/userlistbyrolename")]
  104. public async Task<List<IdentityUserDto>> GetUserListByRoleName(string RoleName)
  105. {
  106. var userlist = await _userRepository.GetListByNormalizedRoleNameAsync(RoleName);
  107. return ObjectMapper.Map<List<IdentityUser>, List<IdentityUserDto>>(userlist);
  108. }
  109. /// <summary>
  110. /// 修改用户密码 修改自身密码
  111. /// </summary>
  112. /// <param name="input"></param>
  113. /// <returns></returns>
  114. [Authorize(PeisPermissions.Users.Default)]
  115. [HttpPost("api/identity/users/updatepassword")]
  116. public async Task UpdatePassWordAsync(UpdatePasswordDto input)
  117. {
  118. var user = await _userManager.FindByIdAsync(_currentUser.Id.ToString());
  119. if (user != null)
  120. {
  121. var isPassWord = await _userManager.CheckPasswordAsync(user, input.OldPassWord);
  122. if (!isPassWord)
  123. {
  124. throw new UserFriendlyException("原密码不正确");
  125. }
  126. await _userManager.RemovePasswordAsync(user);
  127. await _userManager.AddPasswordAsync(user, input.NewPassWord);
  128. }
  129. }
  130. /// <summary>
  131. /// 管理员重置用户密码
  132. /// </summary>
  133. /// <param name="input"></param>
  134. /// <returns></returns>
  135. [Authorize(PeisPermissions.Users.Default)]
  136. [HttpPost("api/identity/users/resetpassword")]
  137. public async Task ResetPassWordAsync(ResetPassWordDto input)
  138. {
  139. var user = await _userManager.FindByIdAsync(input.UserId.ToString());
  140. if (user != null)
  141. {
  142. var RemoveMsg = await _userManager.RemovePasswordAsync(user);
  143. if (!RemoveMsg.Succeeded)
  144. throw new UserFriendlyException($"操作失败,{RemoveMsg.Errors.FirstOrDefault().Code}");
  145. var AddPasswordMsg = await _userManager.AddPasswordAsync(user, input.NewPassWord);
  146. if (!AddPasswordMsg.Succeeded)
  147. throw new UserFriendlyException($"操作失败,{AddPasswordMsg.Errors.FirstOrDefault().Code}");
  148. }
  149. }
  150. ///// <summary>
  151. ///// 创建
  152. ///// </summary>
  153. ///// <param name="input"></param>
  154. ///// <returns></returns>
  155. //[Authorize(PeisPermissions.Users.Create)]
  156. //[HttpPost("api/identity/users/create")]
  157. //public override Task<IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
  158. //{
  159. // return base.CreateAsync(input);
  160. //}
  161. /// <summary>
  162. /// 创建 可以不带邮箱 自动以用户名生成
  163. /// </summary>
  164. /// <param name="input"></param>
  165. /// <returns></returns>
  166. [Authorize(PeisPermissions.Users.Create)]
  167. [HttpPost("api/identity/users/create")]
  168. public async Task<IdentityUserDto> CreateAsync(IdentityUserCreateNoEmailDto input)
  169. {
  170. #region 上传图片
  171. string userPhoto = UploadUserPhotoAsync(new UploadUserPhotoInputDto { PictureBaseStr = input.UserPhoto });
  172. string userSign = UploadUserSignAsync(new UploadUserPhotoInputDto { PictureBaseStr = input.UserSign });
  173. #endregion
  174. IdentityUserCreateDto newinput = new IdentityUserCreateDto
  175. {
  176. Email = string.IsNullOrWhiteSpace(input.Email) ? input.UserName + "@qq.com" : input.Email,
  177. IsActive = input.IsActive,
  178. LockoutEnabled = input.LockoutEnabled,
  179. Name = input.Name,
  180. Password = input.Password,
  181. PhoneNumber = input.PhoneNumber,
  182. RoleNames = input.RoleNames,
  183. Surname = input.Surname,
  184. UserName = input.UserName
  185. };
  186. await IdentityOptions.SetAsync();
  187. var user = new IdentityUser(
  188. GuidGenerator.Create(),
  189. newinput.UserName,
  190. newinput.Email,
  191. CurrentTenant.Id
  192. );
  193. user.SetProperty("user_photo", userPhoto);
  194. user.SetProperty("user_sign", userSign);
  195. user.SetProperty("operator_type", input.OperatorType);
  196. newinput.MapExtraPropertiesTo(user);
  197. (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
  198. await UpdateUserByInput(user, newinput);
  199. (await UserManager.UpdateAsync(user)).CheckErrors();
  200. await CurrentUnitOfWork.SaveChangesAsync();
  201. var entityDto = ObjectMapper.Map<IdentityUser, IdentityUserDto>(user);
  202. var entity = await _identityUserRepository.GetAsync(entityDto.Id);
  203. _userCache.Set(entityDto.Id, entity);
  204. return entityDto;
  205. }
  206. /// <summary>
  207. /// 删除用户
  208. /// </summary>
  209. /// <param name="id"></param>
  210. /// <returns></returns>
  211. [Authorize(PeisPermissions.Users.Delete)]
  212. [HttpPost("api/identity/users/delete")]
  213. public override Task DeleteAsync(Guid id)
  214. {
  215. return base.DeleteAsync(id);
  216. }
  217. /// <summary>
  218. /// 获取列表
  219. /// </summary>
  220. /// <param name="input"></param>
  221. /// <returns></returns>
  222. [Authorize(PeisPermissions.Users.Default)]
  223. [HttpGet("api/identity/users/getlist")]
  224. public override Task<PagedResultDto<IdentityUserDto>> GetListAsync(GetIdentityUsersInput input)
  225. {
  226. return base.GetListAsync(input);
  227. }
  228. /// <summary>
  229. /// 获取列表 根据科室查询 不传科室查所有
  230. /// </summary>
  231. /// <param name="input"></param>
  232. /// <returns></returns>
  233. [Authorize(PeisPermissions.Users.Default)]
  234. [HttpPost("api/identity/users/getlistinorganizationunit")]
  235. public async Task<List<IdentityUserWithExtensionDto>> GetListInOrganizationUnitAsync(OrganizationUnitIdIuputDto input)
  236. {
  237. List<IdentityUser> userList = new List<IdentityUser>();
  238. var identityUserOrganizationUnitList = await _identityUserOrganizationUnitRepository.GetListAsync();
  239. if (input.OrganizationUnitId != null && input.OrganizationUnitId != Guid.Empty)
  240. {
  241. List<Guid> organizationUnitIds = await _peisOrganizationUnitManager.GetOrganizationUnitChildIds(input.OrganizationUnitId.Value);
  242. userList = await _userRepository.GetUsersInOrganizationsListAsync(organizationUnitIds);
  243. }
  244. else
  245. {
  246. userList = await _identityUserRepository.GetListAsync(m => m.IsDeleted == false);
  247. }
  248. var entlistdto = userList.Select(s => new IdentityUserWithExtensionDto
  249. {
  250. UserSign = s.GetProperty<string>("user_sign"),
  251. UserPhoto = s.GetProperty<string>("user_photo"),
  252. OperatorType = s.GetProperty<char>("operator_type"),
  253. ConcurrencyStamp = s.ConcurrencyStamp,
  254. CreationTime = s.CreationTime,
  255. CreatorId = s.CreatorId,
  256. DeleterId = s.DeleterId,
  257. DeletionTime = s.DeletionTime,
  258. Email = s.Email,
  259. EmailConfirmed = s.EmailConfirmed,
  260. Id = s.Id,
  261. IsActive = s.IsActive,
  262. IsDeleted = s.IsDeleted,
  263. LastModificationTime = s.LastModificationTime,
  264. LastModifierId = s.LastModifierId,
  265. LockoutEnabled = s.LockoutEnabled,
  266. LockoutEnd = s.LockoutEnd,
  267. Name = s.Name,
  268. PhoneNumber = s.PhoneNumber,
  269. PhoneNumberConfirmed = s.PhoneNumberConfirmed,
  270. Surname = s.Surname,
  271. TenantId = s.TenantId,
  272. UserName = s.UserName,
  273. //OrganizationUnitId = identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id) != null? identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id).OrganizationUnitId:Guid.Empty,
  274. OrganizationUnitId = identityUserOrganizationUnitList.FirstOrDefault(m => m.UserId == s.Id)?.OrganizationUnitId,
  275. SimpleCode = LanguageConverter.GetPYSimpleCode(s.Surname)
  276. }).ToList();
  277. // var entlistdto = ObjectMapper.Map<List<IdentityUser>, List<IdentityUserDto>>(entlist);
  278. return entlistdto;
  279. }
  280. /// <summary>
  281. /// 获取列表 根据用户类别
  282. /// </summary>
  283. /// <param name="input"></param>
  284. /// <returns></returns>
  285. [Authorize(PeisPermissions.Users.Default)]
  286. [HttpPost("api/identity/users/GetListByOperatorType")]
  287. public async Task<List<ListByOperatorTypeDto>> GetListByOperatorTypeAsync(OperatorTypeIuputDto input)
  288. {
  289. var entlist = await _identityUserRepository.GetListAsync(m => m.IsDeleted == false);
  290. var entlistDto = entlist.Where(m => input.OperatorTypes.Contains(m.GetProperty<char>("operator_type"))).Select(s => new ListByOperatorTypeDto
  291. {
  292. Id = s.Id,
  293. SimpleCode = LanguageConverter.GetPYSimpleCode(s.Surname),
  294. Surname = s.Surname,
  295. UserName = s.UserName
  296. }).ToList();
  297. return entlistDto;
  298. }
  299. /// <summary>
  300. /// 修改用户信息
  301. /// </summary>
  302. /// <param name="id"></param>
  303. /// <param name="input"></param>
  304. /// <returns></returns>
  305. //[Authorize(PeisPermissions.Users.Edit)]
  306. //[HttpPost("api/identity/users/update")]
  307. [RemoteService(false)]
  308. public override async Task<IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input)
  309. {
  310. var entityDto = await base.UpdateAsync(id, input);
  311. var entity = await _identityUserRepository.GetAsync(id);
  312. _userCache.Set(id, entity);
  313. return entityDto;
  314. }
  315. /// <summary>
  316. /// 修改
  317. /// </summary>
  318. /// <param name="id"></param>
  319. /// <param name="input"></param>
  320. /// <returns></returns>
  321. [Authorize(PeisPermissions.Users.Edit)]
  322. [HttpPost("api/identity/users/update")]
  323. public async Task<IdentityUserDto> UpdateIdentityUserAsync(Guid id, IdentityUserUpdateInputDto input)
  324. {
  325. #region 上传图片
  326. string userPhoto = UploadUserPhotoAsync(new UploadUserPhotoInputDto
  327. {
  328. PictureBaseStr = input.UserPhoto,
  329. UserId = id
  330. });
  331. string userSign = UploadUserSignAsync(new UploadUserPhotoInputDto
  332. {
  333. PictureBaseStr = input.UserSign,
  334. UserId = id
  335. });
  336. #endregion
  337. input.Email = input.UserName + "@qq.com";
  338. await IdentityOptions.SetAsync();
  339. var user = await UserManager.GetByIdAsync(id);
  340. user.SetProperty("user_sign", userSign);
  341. user.SetProperty("user_photo", userPhoto);
  342. user.SetProperty("operator_type", input.OperatorType);
  343. user.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
  344. (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();
  345. await UpdateUserByInput(user, input);
  346. input.MapExtraPropertiesTo(user);
  347. (await UserManager.UpdateAsync(user)).CheckErrors();
  348. if (!input.Password.IsNullOrEmpty())
  349. {
  350. (await UserManager.RemovePasswordAsync(user)).CheckErrors();
  351. (await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors();
  352. }
  353. await CurrentUnitOfWork.SaveChangesAsync();
  354. var entityDto = ObjectMapper.Map<IdentityUser, IdentityUserDto>(user);
  355. var entity = await _identityUserRepository.GetAsync(id);
  356. _userCache.Set(id, entity);
  357. return entityDto;
  358. }
  359. /// <summary>
  360. /// 获取用户信息 根据ID
  361. /// </summary>
  362. /// <param name="id"></param>
  363. /// <returns></returns>
  364. //[Authorize(PeisPermissions.Users.Default)]
  365. //[HttpGet("api/identity/users/getinfo")]
  366. [RemoteService(false)]
  367. public override Task<IdentityUserDto> GetAsync(Guid id)
  368. {
  369. return base.GetAsync(id);
  370. }
  371. /// <summary>
  372. ///上传用户照片 图片base64
  373. /// </summary>
  374. /// <param name="input"></param>
  375. /// <returns></returns>
  376. /// <exception cref="UserFriendlyException"></exception>
  377. private string UploadUserPhotoAsync(UploadUserPhotoInputDto input)
  378. {
  379. string fileName = "";
  380. if (input.UserId != null)
  381. {
  382. fileName = input.UserId.ToString();
  383. }
  384. else
  385. {
  386. fileName = Guid.NewGuid().ToString();
  387. }
  388. string imgurl = $"UserPhoto/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{fileName}";
  389. var isupload = ImageHelper.Base64StrToImage(input.PictureBaseStr, imgurl);
  390. if (!string.IsNullOrEmpty(isupload))
  391. return isupload;
  392. else
  393. return "";
  394. }
  395. /// <summary>
  396. /// 上传用户签名 图片base64
  397. /// </summary>
  398. /// <param name="input"></param>
  399. /// <returns></returns>
  400. /// <exception cref="UserFriendlyException"></exception>
  401. private string UploadUserSignAsync(UploadUserPhotoInputDto input)
  402. {
  403. string fileName = "";
  404. if (input.UserId != null)
  405. {
  406. fileName = input.UserId.ToString();
  407. }
  408. else
  409. {
  410. fileName = Guid.NewGuid().ToString();
  411. }
  412. string imgurl = $"UserSign/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{fileName}";
  413. var isupload = ImageHelper.Base64StrToImage(input.PictureBaseStr, imgurl);
  414. if (!string.IsNullOrEmpty(isupload))
  415. return isupload;
  416. else
  417. return "";
  418. }
  419. /// <summary>
  420. /// 获取用户信息 根据ID
  421. /// </summary>
  422. /// <param name="id"></param>
  423. /// <returns></returns>
  424. [Authorize(PeisPermissions.Users.Default)]
  425. [HttpGet("api/identity/users/getinfo")]
  426. public async Task<IdentityUserWithExtensionDto> GetWithExtensionAsync(Guid id)
  427. {
  428. var ent = await UserManager.GetByIdAsync(id);
  429. var userSign = !string.IsNullOrWhiteSpace(ent.GetProperty<string>("user_sign")) ? ImageHelper.GetImageBase64StringAsync(ent.GetProperty<string>("user_sign")) : "";
  430. var userPhoto = !string.IsNullOrWhiteSpace(ent.GetProperty<string>("user_photo")) ? ImageHelper.GetImageBase64StringAsync(ent.GetProperty<string>("user_photo")) : "";
  431. var operatorType = ent.GetProperty<char>("operator_type");
  432. var entDto = ObjectMapper.Map<IdentityUser, IdentityUserWithExtensionDto>(ent);
  433. entDto.UserPhoto = userPhoto;
  434. entDto.UserSign = userSign;
  435. entDto.OperatorType = operatorType;
  436. return entDto;
  437. }
  438. /// <summary>
  439. /// 给用户绑定角色
  440. /// </summary>
  441. /// <param name="id">用户ID</param>
  442. /// <param name="input">角色集合</param>
  443. /// <returns></returns>
  444. [Authorize(PeisPermissions.Users.Edit)]
  445. [HttpPost("api/identity/users/updateroles")]
  446. public override Task UpdateRolesAsync(Guid id, IdentityUserUpdateRolesDto input)
  447. {
  448. return base.UpdateRolesAsync(id, input);
  449. }
  450. /// <summary>
  451. /// 获取用户的角色信息 根据用户ID
  452. /// </summary>
  453. /// <param name="id">用户ID</param>
  454. /// <returns></returns>
  455. [Authorize(PeisPermissions.Users.Default)]
  456. [HttpGet("api/identity/users/getroles")]
  457. public override Task<ListResultDto<IdentityRoleDto>> GetRolesAsync(Guid id)
  458. {
  459. return base.GetRolesAsync(id);
  460. }
  461. /// <summary>
  462. /// 获取当前登录用户的角色信息
  463. /// </summary>
  464. /// <returns></returns>
  465. [Authorize(PeisPermissions.Users.Default)]
  466. [HttpGet("api/identity/users/getassignableroles")]
  467. public override Task<ListResultDto<IdentityRoleDto>> GetAssignableRolesAsync()
  468. {
  469. return base.GetAssignableRolesAsync();
  470. }
  471. /// <summary>
  472. /// 暂未用到
  473. /// </summary>
  474. /// <param name="userName"></param>
  475. /// <returns></returns>
  476. [Authorize(PeisPermissions.Users.Default)]
  477. [RemoteService(false)]
  478. public override Task<IdentityUserDto> FindByUsernameAsync(string userName)
  479. {
  480. return base.FindByUsernameAsync(userName);
  481. }
  482. /// <summary>
  483. /// 暂未用到
  484. /// </summary>
  485. /// <param name="email"></param>
  486. /// <returns></returns>
  487. [Authorize(PeisPermissions.Users.Default)]
  488. [RemoteService(false)]
  489. public override Task<IdentityUserDto> FindByEmailAsync(string email)
  490. {
  491. return base.FindByEmailAsync(email);
  492. }
  493. /// <summary>
  494. /// 用户登录
  495. /// </summary>
  496. /// <param name="input"></param>
  497. /// <returns></returns>
  498. [HttpPost("api/identity/users/login")]
  499. public async Task<UserLoginDto> UserLogin(UserLoginRequestDto input)
  500. {
  501. UserLoginDto msg;
  502. var user = await _userManager.FindByNameAsync(input.UserName);
  503. if (user != null)
  504. {
  505. var verifyResult = await _userManager.CheckPasswordAsync(user, input.PassWord);
  506. if (verifyResult)
  507. {
  508. var PeisId = await _peisOrganizationUnitManager.GetPeisIdAsync(user.Id);
  509. if (user.IsActive == false)
  510. {
  511. throw new UserFriendlyException("账号已被禁用");
  512. }
  513. if (user.LockoutEnabled == true)
  514. {
  515. throw new UserFriendlyException("账号已被锁定");
  516. }
  517. TokenResponse token = await RequestAuthServerLoginByPasswordAsync(input.UserName, input.PassWord);
  518. if (token.HttpResponse != null && token.HttpResponse.StatusCode == HttpStatusCode.OK)
  519. {
  520. msg = new UserLoginDto
  521. {
  522. //code = 1,
  523. //msg = "登录成功",
  524. peisid = PeisId,
  525. UserId = user.Id,
  526. OperatorType = user.GetProperty<char>("operator_type"),
  527. access_token = token.AccessToken,
  528. expires_in = token.ExpiresIn,
  529. refresh_token = token.RefreshToken,
  530. token_type = token.TokenType
  531. };
  532. }
  533. else
  534. {
  535. //msg = new UserLoginDto { code = 1, msg = "登录成功", peisid = PeisId };
  536. throw new UserFriendlyException("获取token失败");
  537. }
  538. }
  539. else
  540. {
  541. //msg = new UserLoginDto { code = -1, msg = "密码不正确" };
  542. throw new UserFriendlyException("密码不正确");
  543. }
  544. #region MyRegion
  545. //var verifyResult = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, PassWord);
  546. //if (verifyResult == PasswordVerificationResult.Success)
  547. //{
  548. // return "1";
  549. //}
  550. //else
  551. //{
  552. // throw new UserFriendlyException("密码错误");
  553. //}
  554. #endregion
  555. }
  556. else
  557. {
  558. //msg = new UserLoginDto { code = -1, msg = "用户不存在" };
  559. throw new UserFriendlyException("用户不存在");
  560. }
  561. return msg;
  562. }
  563. protected virtual async Task<TokenResponse> RequestAuthServerLoginByPasswordAsync(string username, string password)
  564. {
  565. var client = _httpClientFactory.CreateClient();
  566. var request = new PasswordTokenRequest
  567. {
  568. Address = _configuration["AuthServer:Authority"] + "/connect/token",
  569. //GrantType = "password",
  570. //UserName = username,
  571. //Password = password,
  572. //Scope = "Peis offline_access",
  573. //ClientId = "Peis_App",
  574. Parameters =
  575. {
  576. {"username",username},
  577. {"password",password },
  578. {"scope","Peis offline_access" },
  579. {"client_id","Peis_App" },
  580. {"grant_type","password" }
  581. }
  582. };
  583. //request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  584. return await client.RequestTokenAsync(request);
  585. }
  586. }
  587. }