UserController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Security.Claims;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Datory.Utils;
  8. using GxPress.Api.Tools;
  9. using GxPress.Auth;
  10. using GxPress.Common.Exceptions;
  11. using GxPress.Common.Tools;
  12. using GxPress.Common.Validation;
  13. using GxPress.Entity;
  14. using GxPress.EnumConst;
  15. using GxPress.Repository.Interface;
  16. using GxPress.Request.App.User;
  17. using GxPress.Request.User;
  18. using GxPress.Result.App.FileLibrary;
  19. using GxPress.Result.App.User;
  20. using GxPress.Result.User;
  21. using GxPress.Service.Interface;
  22. using Microsoft.AspNetCore.Authorization;
  23. using Microsoft.AspNetCore.Mvc;
  24. using Microsoft.Extensions.Caching.Distributed;
  25. using Microsoft.Extensions.Logging;
  26. using Microsoft.Extensions.Options;
  27. namespace GxPress.Api.AppControllers
  28. {
  29. /// <summary>
  30. /// 用户
  31. /// </summary>
  32. [Route("/api/app/user")]
  33. [ApiController]
  34. [Authorize]
  35. public class UserController : ControllerBase
  36. {
  37. private readonly JwtOptions _jwtOptions;
  38. private readonly ILogger<UserController> _logger;
  39. private readonly IUserRepository _userRepository;
  40. private readonly IDepartmentRepository _departmentRepository;
  41. private readonly ILoginContext _loginContext;
  42. private readonly IUserService _userService;
  43. private readonly IFileLibraryRepository fileLibraryRepository;
  44. private readonly IDistributedCache _cache;
  45. public UserController(IUserRepository userRepository, IOptions<JwtOptions> jwtOptions,
  46. ILogger<UserController> logger, IDepartmentRepository departmentRepository, ILoginContext loginContext,
  47. IUserService userService, IFileLibraryRepository fileLibraryRepository, IDistributedCache cache)
  48. {
  49. _userRepository = userRepository;
  50. _departmentRepository = departmentRepository;
  51. _userService = userService;
  52. _jwtOptions = jwtOptions.Value;
  53. _logger = logger;
  54. _loginContext = loginContext;
  55. this.fileLibraryRepository = fileLibraryRepository;
  56. _cache = cache;
  57. }
  58. ///// <summary>
  59. ///// 添加
  60. ///// </summary>
  61. ///// <param name="request"></param>
  62. ///// <returns></returns>
  63. //[HttpPost]
  64. //public async Task<User> Add([FromBody] User request)
  65. //{
  66. // request.Id = await _userRepository.InsertAsync(request);
  67. // return request;
  68. //}
  69. /// <summary>
  70. /// 登录
  71. /// </summary>
  72. /// <param name="request"></param>
  73. /// <returns></returns>
  74. [HttpPost("signin")]
  75. [AllowAnonymous]
  76. public async Task<UserSignInResult> SignIn(UserSignInRequest request)
  77. {
  78. var result = await _userRepository.SignInAsync(request);
  79. if (result.IsAddUser)
  80. {
  81. //添加环信
  82. await _userRepository.CreateMiUserAsync(result.UserEntity);
  83. }
  84. var claims = new[]
  85. {
  86. new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
  87. new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString()),
  88. new Claim(ClaimTypes.GroupSid,result.DepartmentId.ToString())
  89. };
  90. result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
  91. return result;
  92. }
  93. /// <summary>
  94. /// 绑定opendId
  95. /// </summary>
  96. /// <param name="request"></param>
  97. /// <returns></returns>
  98. [HttpPost("set-opend-Id")]
  99. [AllowAnonymous]
  100. public async Task<UserSignInResult> SetOpenId(UserSignInRequest request)
  101. {
  102. var success = await _userRepository.UpdateByOpendIdAsync(request);
  103. if (success)
  104. {
  105. var result = await _userRepository.SignInAsync(request);
  106. if (result.IsAddUser)
  107. {
  108. //添加环信
  109. await _userRepository.CreateMiUserAsync(result.UserEntity);
  110. }
  111. var claims = new[]
  112. {
  113. new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
  114. new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString()),
  115. new Claim(ClaimTypes.GroupSid,result.DepartmentId.ToString())
  116. };
  117. result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
  118. return result;
  119. }
  120. return new UserSignInResult();
  121. }
  122. /// <summary>
  123. /// 查询opendId是否存在
  124. /// </summary>
  125. /// <param name="opendId"></param>
  126. /// <returns></returns>
  127. [HttpGet("find-opend-Id/{opendId}")]
  128. [AllowAnonymous]
  129. public async Task<bool> FindOpenId(string opendId)
  130. {
  131. var user = await _userRepository.GetByOpenIdAsync(opendId);
  132. if (user == null)
  133. return false;
  134. return true;
  135. }
  136. /////// <summary>
  137. /////// 登录验证码发送
  138. /////// </summary>
  139. /////// <param name="phone"></param>
  140. /////// <returns></returns>
  141. ////[HttpGet("sendSmsCode")]
  142. ////[AllowAnonymous]
  143. ////public async Task<bool> SendSmsCode([FromQuery] [Required] [Mobile] string phone)
  144. ////{
  145. //// var user = await _userRepository.GetByPhoneAsync(phone);
  146. //// //用户不存在
  147. //// if (user == null)
  148. //// {
  149. //// throw new BusinessException("该用户不存在");
  150. //// }
  151. //// //TODO 短信验证码发送
  152. //// //return await _smsService.
  153. //// //SendValidationCodeAsync(phone);
  154. //// var key = $"login:{phone}";
  155. //// if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  156. //// var code = RandomGenerator.GetNumberString(6);
  157. //// _logger.LogInformation("{phone}验证码:{code}", phone, code);
  158. //// //发送验证码阿里云
  159. //// IClientProfile profile =
  160. //// DefaultProfile.GetProfile("cn-hangzhou", "LTAI2E47R4DlcYfo", "5epQRUGRrDSoF7yukyYf4HX6dUlvF3");
  161. //// DefaultAcsClient client = new DefaultAcsClient(profile);
  162. //// CommonRequest request = new CommonRequest
  163. //// {
  164. //// Method = MethodType.POST,
  165. //// Domain = "dysmsapi.aliyuncs.com",
  166. //// Version = "2017-05-25",
  167. //// Action = "SendSms"
  168. //// };
  169. //// request.AddQueryParameters("PhoneNumbers", $"{phone}");
  170. //// request.AddQueryParameters("SignName", "泰德合众");
  171. //// request.AddQueryParameters("TemplateCode", "SMS_168126117");
  172. //// request.AddQueryParameters("TemplateParam", "{\"code\":\"" + code + "\"}");
  173. //// try
  174. //// {
  175. //// CommonResponse response = client.GetCommonResponse(request);
  176. //// _logger.LogInformation(Encoding.Default.GetString(response.HttpResponse.Content));
  177. //// }
  178. //// catch (ServerException e)
  179. //// {
  180. //// throw new BusinessException(e.Message);
  181. //// }
  182. //return await RedisHelper.SetAsync(key, code, 300);
  183. ////}
  184. /// <summary>
  185. /// 登录验证码发送
  186. /// </summary>
  187. /// <param name="phone"></param>
  188. /// <returns></returns>
  189. [HttpGet("sendSmsCode")]
  190. [AllowAnonymous]
  191. public async Task<bool> SendSmsCode([FromQuery][Required][Mobile] string phone)
  192. {
  193. var user = await _userRepository.GetByPhoneAsync(phone);
  194. //用户不存在
  195. if (user == null)
  196. {
  197. user = new User();
  198. user.Name = phone;
  199. user.Phone = phone;
  200. user.ImId = phone;
  201. user.Id = await _userRepository.InsertAsync(user);
  202. if (user.Id > 0 && await _userRepository.CreateMiUserAsync(user))
  203. {
  204. }
  205. }
  206. //TODO 短信验证码发送
  207. //return await _smsService.
  208. //SendValidationCodeAsync(phone);
  209. //发送短信
  210. var key = $"login:{phone}";
  211. var code = await _cache.GetStringAsync(key);
  212. if (!string.IsNullOrEmpty(code))
  213. throw new BusinessException("请求太频繁!");
  214. code = RandomGenerator.GetNumberString(6);
  215. var isRegisterValue = ConfigHelper.GetValue("ServiceAddress:IsRegister");
  216. if (bool.TryParse(isRegisterValue, out bool isRegister))
  217. code = "123456";
  218. //code = "123456";
  219. if (Common.Sms.MasSms.SendSmsTemplate(phone, code, "8b833ac6dfe54e62821bc6843279e2dd"))
  220. {
  221. _logger.LogInformation("{phone}验证码:{code}", phone, code);
  222. var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
  223. await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
  224. {
  225. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
  226. });
  227. return true;
  228. }
  229. return false;
  230. }
  231. /// <summary>
  232. /// 更换手机号码验证码发送
  233. /// </summary>
  234. /// <param name="phone"></param>
  235. /// <returns></returns>
  236. [HttpGet("send-sms-code")]
  237. public async Task<bool> SendSmsCodeReplace([FromQuery][Required][Mobile] string phone)
  238. {
  239. var user = await _userRepository.GetByPhoneAsync(phone);
  240. if (user != null)
  241. throw new BusinessException("号码以被使用");
  242. //TODO 短信验证码发送
  243. //发送短信
  244. var key = $"login:{phone}";
  245. var code = await _cache.GetStringAsync(key);
  246. if (!string.IsNullOrEmpty(code))
  247. throw new BusinessException("请求太频繁!");
  248. code = RandomGenerator.GetNumberString(6);
  249. var isRegisterValue = ConfigHelper.GetValue("ServiceAddress:IsRegister");
  250. if (bool.TryParse(isRegisterValue, out bool isRegister))
  251. code = "123456";
  252. if (Common.Sms.MasSms.SendSmsTemplate(phone, code, "8b833ac6dfe54e62821bc6843279e2dd"))
  253. {
  254. _logger.LogInformation("{phone}验证码:{code}", phone, code);
  255. var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
  256. await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
  257. {
  258. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
  259. });
  260. return true;
  261. }
  262. return false;
  263. }
  264. /// <summary>
  265. /// app查询用户详情
  266. /// </summary>
  267. /// <returns></returns>
  268. [HttpGet("detail")]
  269. public async Task<UserDetail> GetDetail()
  270. {
  271. var id = _loginContext.AccountId;
  272. var user = await _userRepository.GetAsync(id);
  273. if (user == null)
  274. throw new BusinessException("用户id有误");
  275. return await _userRepository.GetDetailAsync(id);
  276. }
  277. /// <summary>
  278. /// app查询他人用户详情
  279. /// </summary>
  280. /// <returns></returns>
  281. [HttpGet("detail/{id}")]
  282. public async Task<UserDetail> GetDetail(int id)
  283. {
  284. if (id <= 0)
  285. throw new BusinessException("用户id有误");
  286. return await _userService.GetUserByIdAsync(_loginContext.AccountId, id);
  287. }
  288. /// <summary>
  289. /// app更新用户信息
  290. /// </summary>
  291. /// <param name="request"></param>
  292. /// <returns></returns>
  293. [HttpPut("update")]
  294. public async Task<bool> Update([FromBody] User request)
  295. {
  296. var id = _loginContext.AccountId;
  297. var result = await _userRepository.UpdateAsync(id, request);
  298. if (result == false)
  299. throw new BusinessException("更新失败");
  300. return true;
  301. }
  302. /// <summary>
  303. /// 私信
  304. /// </summary>
  305. /// <returns></returns>
  306. [HttpPost("update-user-private-letter")]
  307. public async Task<bool> UpdateUserPrivateLetter()
  308. {
  309. UserPrivateLetterRequest request = new UserPrivateLetterRequest { Id = _loginContext.AccountId };
  310. var result = await _userRepository.UpdateUserPrivateLetterAsync(request);
  311. if (result == false)
  312. throw new BusinessException("更新失败");
  313. return true;
  314. }
  315. /// <summary>
  316. /// 通知
  317. /// </summary>
  318. /// <returns></returns>
  319. [HttpPost("update-user-notice")]
  320. public async Task<bool> UpdateUserNotice()
  321. {
  322. var request = new UserNoticeRequest { Id = _loginContext.AccountId };
  323. var result = await _userRepository.UpdateUserNoticeAsync(request);
  324. if (result == false)
  325. throw new BusinessException("更新失败");
  326. return true;
  327. }
  328. /// <summary>
  329. /// 回复
  330. /// </summary>
  331. /// <returns></returns>
  332. [HttpPost("update-user-reply")]
  333. public async Task<bool> UpdateUserReply()
  334. {
  335. var request = new UserReplyRequest { Id = _loginContext.AccountId };
  336. var result = await _userRepository.UpdateUserReplyAsync(request);
  337. if (result == false)
  338. throw new BusinessException("更新失败");
  339. return true;
  340. }
  341. /// <summary>
  342. /// 静音
  343. /// </summary>
  344. /// <returns></returns>
  345. [HttpPost("update-user-mute")]
  346. public async Task<bool> UpdateUserMute()
  347. {
  348. var request = new UserMuteRequest { Id = _loginContext.AccountId };
  349. var result = await _userRepository.UpdateUserMuteAsync(request);
  350. if (result == false)
  351. throw new BusinessException("更新失败");
  352. return true;
  353. }
  354. /// <summary>
  355. /// 震动
  356. /// </summary>
  357. /// <returns></returns>
  358. [HttpPost("update-user-shake")]
  359. public async Task<bool> UpdateUserShake()
  360. {
  361. var request = new UserShakeRequest { Id = _loginContext.AccountId };
  362. var result = await _userRepository.UpdateUserShakeAsync(request);
  363. if (result == false)
  364. throw new BusinessException("更新失败");
  365. return true;
  366. }
  367. /// <summary>
  368. /// 用户修改手机号码
  369. /// </summary>
  370. /// <param name="request"></param>
  371. /// <returns></returns>
  372. [HttpPost("update-user-phone")]
  373. public async Task<bool> UpdateUserPhone(UserUpdatePhoneRequest request)
  374. {
  375. request.UserId = _loginContext.AccountId;
  376. var result = await _userRepository.UpdateUserPhoneAsync(request);
  377. if (result == false)
  378. throw new BusinessException("更新失败");
  379. return true;
  380. }
  381. /// <summary>
  382. /// 邮箱验证码
  383. /// </summary>
  384. /// <param name="request"></param>
  385. /// <returns></returns>
  386. [HttpPost("send-email-verify-code")]
  387. public async Task<bool> SendEmailVerifyCode(UserEmailVerifyCodeRequest request)
  388. {
  389. request.UserId = _loginContext.AccountId;
  390. var result = await _userRepository.SendEmailVerifyCodeAsync(request);
  391. if (result == false)
  392. throw new BusinessException("更新失败");
  393. return true;
  394. }
  395. /// <summary>
  396. /// 修改邮箱
  397. /// </summary>
  398. /// <param name="request"></param>
  399. /// <returns></returns>
  400. [HttpPost("update-user-email")]
  401. public async Task<bool> UpdateUserEmail(UserUpdateEmailRequest request)
  402. {
  403. request.UserId = _loginContext.AccountId;
  404. var result = await _userRepository.UpdateUserEmailAsync(request);
  405. if (result == false)
  406. throw new BusinessException("更新失败");
  407. return true;
  408. }
  409. /// <summary>
  410. /// 查询联系人
  411. /// </summary>
  412. /// <param name="request"></param>
  413. /// <returns></returns>
  414. [HttpPost("search")]
  415. public async Task<IEnumerable<UserInfoResult>> SearchUserName(SearchUserNameRequest request)
  416. {
  417. return await _userRepository.SearchUserNameAsync(request);
  418. }
  419. /// <summary>
  420. /// 根据部门ID获取自建ID获取用户列表
  421. /// </summary>
  422. /// <param name="request"></param>
  423. /// <returns></returns>
  424. [HttpPost("find")]
  425. public async Task<IEnumerable<UserInfoResult>> FindUser(FindUserRequest request)
  426. {
  427. request.UserId = _loginContext.AccountId;
  428. return await _userService.FindUser(request);
  429. }
  430. /// <summary>
  431. /// 根据部门ID获取自建ID获取用户列表
  432. /// </summary>
  433. /// <param name="name"></param>
  434. /// <returns></returns>
  435. [HttpGet("find-name")]
  436. public async Task<IEnumerable<UserInfoResult>> FindUserByName([FromQuery] string name)
  437. {
  438. return await _userRepository.UserByNameAsync(name);
  439. }
  440. /// <summary>
  441. /// 根据GUID查询用户
  442. /// </summary>
  443. /// <returns></returns>
  444. [HttpPost("guid")]
  445. public async Task<UserDetail> FindUserByGuid(FindUserByGuidRequest request)
  446. {
  447. var user = await _userRepository.GetGuidAsync(request.Guid);
  448. return user;
  449. }
  450. /// <summary>
  451. /// 获取用户工作模块未读数据
  452. /// </summary>
  453. /// <returns></returns>
  454. [HttpGet("user-uread-count")]
  455. public async Task<UserCountResult> GetUserCountAsync()
  456. {
  457. return await _userService.GetUserCountAsync(_loginContext.AccountId);
  458. }
  459. /// <summary>
  460. /// 根据用户名获取电脑上传的数据
  461. /// </summary>
  462. /// <returns></returns>
  463. [HttpGet("user-file-library")]
  464. public async Task<IEnumerable<FileLibraryResult>> GetFileLibraryByUserIdAsync()
  465. {
  466. return await fileLibraryRepository.GetFileLibraryByUserIdAsync(_loginContext.AccountId);
  467. }
  468. }
  469. }