UserController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. var claims = new[]
  80. {
  81. new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
  82. new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString())
  83. };
  84. result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
  85. return result;
  86. }
  87. /// <summary>
  88. /// 绑定opendId
  89. /// </summary>
  90. /// <param name="request"></param>
  91. /// <returns></returns>
  92. [HttpPost("set-opend-Id")]
  93. [AllowAnonymous]
  94. public async Task<UserSignInResult> SetOpenId(UserSignInRequest request)
  95. {
  96. var success = await _userRepository.UpdateByOpendIdAsync(request);
  97. if (success)
  98. {
  99. var result = await _userRepository.SignInAsync(request);
  100. var claims = new[]
  101. {
  102. new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()),
  103. new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString())
  104. };
  105. result.Token = TokenHelper.BuildToken(_jwtOptions, claims);
  106. return result;
  107. }
  108. return new UserSignInResult();
  109. }
  110. /// <summary>
  111. /// 查询opendId是否存在
  112. /// </summary>
  113. /// <param name="opendId"></param>
  114. /// <returns></returns>
  115. [HttpGet("find-opend-Id/{opendId}")]
  116. [AllowAnonymous]
  117. public async Task<bool> FindOpenId(string opendId)
  118. {
  119. var user = await _userRepository.GetByOpenIdAsync(opendId);
  120. if (user == null)
  121. return false;
  122. return true;
  123. }
  124. /////// <summary>
  125. /////// 登录验证码发送
  126. /////// </summary>
  127. /////// <param name="phone"></param>
  128. /////// <returns></returns>
  129. ////[HttpGet("sendSmsCode")]
  130. ////[AllowAnonymous]
  131. ////public async Task<bool> SendSmsCode([FromQuery] [Required] [Mobile] string phone)
  132. ////{
  133. //// var user = await _userRepository.GetByPhoneAsync(phone);
  134. //// //用户不存在
  135. //// if (user == null)
  136. //// {
  137. //// throw new BusinessException("该用户不存在");
  138. //// }
  139. //// //TODO 短信验证码发送
  140. //// //return await _smsService.
  141. //// //SendValidationCodeAsync(phone);
  142. //// var key = $"login:{phone}";
  143. //// if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  144. //// var code = RandomGenerator.GetNumberString(6);
  145. //// _logger.LogInformation("{phone}验证码:{code}", phone, code);
  146. //// //发送验证码阿里云
  147. //// IClientProfile profile =
  148. //// DefaultProfile.GetProfile("cn-hangzhou", "LTAI2E47R4DlcYfo", "5epQRUGRrDSoF7yukyYf4HX6dUlvF3");
  149. //// DefaultAcsClient client = new DefaultAcsClient(profile);
  150. //// CommonRequest request = new CommonRequest
  151. //// {
  152. //// Method = MethodType.POST,
  153. //// Domain = "dysmsapi.aliyuncs.com",
  154. //// Version = "2017-05-25",
  155. //// Action = "SendSms"
  156. //// };
  157. //// request.AddQueryParameters("PhoneNumbers", $"{phone}");
  158. //// request.AddQueryParameters("SignName", "泰德合众");
  159. //// request.AddQueryParameters("TemplateCode", "SMS_168126117");
  160. //// request.AddQueryParameters("TemplateParam", "{\"code\":\"" + code + "\"}");
  161. //// try
  162. //// {
  163. //// CommonResponse response = client.GetCommonResponse(request);
  164. //// _logger.LogInformation(Encoding.Default.GetString(response.HttpResponse.Content));
  165. //// }
  166. //// catch (ServerException e)
  167. //// {
  168. //// throw new BusinessException(e.Message);
  169. //// }
  170. //return await RedisHelper.SetAsync(key, code, 300);
  171. ////}
  172. /// <summary>
  173. /// 登录验证码发送
  174. /// </summary>
  175. /// <param name="phone"></param>
  176. /// <returns></returns>
  177. [HttpGet("sendSmsCode")]
  178. [AllowAnonymous]
  179. public async Task<bool> SendSmsCode([FromQuery][Required][Mobile] string phone)
  180. {
  181. var user = await _userRepository.GetByPhoneAsync(phone);
  182. //用户不存在
  183. if (user == null)
  184. {
  185. throw new BusinessException("该用户不存在");
  186. }
  187. //TODO 短信验证码发送
  188. //return await _smsService.
  189. //SendValidationCodeAsync(phone);
  190. //发送短信
  191. var key = $"login:{phone}";
  192. var code = await _cache.GetStringAsync(key);
  193. if (!string.IsNullOrEmpty(code))
  194. throw new BusinessException("请求太频繁!");
  195. code = RandomGenerator.GetNumberString(6);
  196. if (Common.Sms.AliySms.SendSms(phone, code))
  197. {
  198. _logger.LogInformation("{phone}验证码:{code}", phone, code);
  199. var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
  200. await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
  201. {
  202. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
  203. });
  204. return true;
  205. }
  206. return false;
  207. }
  208. /// <summary>
  209. /// 更换手机号码验证码发送
  210. /// </summary>
  211. /// <param name="phone"></param>
  212. /// <returns></returns>
  213. [HttpGet("send-sms-code")]
  214. public async Task<bool> SendSmsCodeReplace([FromQuery][Required][Mobile] string phone)
  215. {
  216. var user = await _userRepository.GetByPhoneAsync(phone);
  217. if (user != null)
  218. throw new BusinessException("号码以被使用");
  219. //TODO 短信验证码发送
  220. //发送短信
  221. var key = $"login:{phone}";
  222. var code = await _cache.GetStringAsync(key);
  223. if (!string.IsNullOrEmpty(code))
  224. throw new BusinessException("请求太频繁!");
  225. code = RandomGenerator.GetNumberString(6);
  226. if (Common.Sms.AliySms.SendSms(phone, code))
  227. {
  228. _logger.LogInformation("{phone}验证码:{code}", phone, code);
  229. var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code));
  230. await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions
  231. {
  232. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60)
  233. });
  234. return true;
  235. }
  236. return false;
  237. }
  238. /// <summary>
  239. /// app查询用户详情
  240. /// </summary>
  241. /// <returns></returns>
  242. [HttpGet("detail")]
  243. public async Task<UserDetail> GetDetail()
  244. {
  245. var id = _loginContext.AccountId;
  246. var user = await _userRepository.GetAsync(id);
  247. if (user == null)
  248. throw new BusinessException("用户id有误");
  249. return await _userRepository.GetDetailAsync(id);
  250. }
  251. /// <summary>
  252. /// app查询他人用户详情
  253. /// </summary>
  254. /// <returns></returns>
  255. [HttpGet("detail/{id}")]
  256. public async Task<UserDetail> GetDetail(int id)
  257. {
  258. if (id <= 0)
  259. throw new BusinessException("用户id有误");
  260. return await _userService.GetUserByIdAsync(_loginContext.AccountId, id);
  261. }
  262. /// <summary>
  263. /// app更新用户信息
  264. /// </summary>
  265. /// <param name="request"></param>
  266. /// <returns></returns>
  267. [HttpPut("update")]
  268. public async Task<bool> Update([FromBody] User request)
  269. {
  270. var id = _loginContext.AccountId;
  271. var result = await _userRepository.UpdateAsync(id, request);
  272. if (result == false)
  273. throw new BusinessException("更新失败");
  274. return true;
  275. }
  276. /// <summary>
  277. /// 私信
  278. /// </summary>
  279. /// <returns></returns>
  280. [HttpPost("update-user-private-letter")]
  281. public async Task<bool> UpdateUserPrivateLetter()
  282. {
  283. UserPrivateLetterRequest request = new UserPrivateLetterRequest { Id = _loginContext.AccountId };
  284. var result = await _userRepository.UpdateUserPrivateLetterAsync(request);
  285. if (result == false)
  286. throw new BusinessException("更新失败");
  287. return true;
  288. }
  289. /// <summary>
  290. /// 通知
  291. /// </summary>
  292. /// <returns></returns>
  293. [HttpPost("update-user-notice")]
  294. public async Task<bool> UpdateUserNotice()
  295. {
  296. var request = new UserNoticeRequest { Id = _loginContext.AccountId };
  297. var result = await _userRepository.UpdateUserNoticeAsync(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-reply")]
  307. public async Task<bool> UpdateUserReply()
  308. {
  309. var request = new UserReplyRequest { Id = _loginContext.AccountId };
  310. var result = await _userRepository.UpdateUserReplyAsync(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-mute")]
  320. public async Task<bool> UpdateUserMute()
  321. {
  322. var request = new UserMuteRequest { Id = _loginContext.AccountId };
  323. var result = await _userRepository.UpdateUserMuteAsync(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-shake")]
  333. public async Task<bool> UpdateUserShake()
  334. {
  335. var request = new UserShakeRequest { Id = _loginContext.AccountId };
  336. var result = await _userRepository.UpdateUserShakeAsync(request);
  337. if (result == false)
  338. throw new BusinessException("更新失败");
  339. return true;
  340. }
  341. /// <summary>
  342. /// 用户修改手机号码
  343. /// </summary>
  344. /// <param name="request"></param>
  345. /// <returns></returns>
  346. [HttpPost("update-user-phone")]
  347. public async Task<bool> UpdateUserPhone(UserUpdatePhoneRequest request)
  348. {
  349. request.UserId = _loginContext.AccountId;
  350. var result = await _userRepository.UpdateUserPhoneAsync(request);
  351. if (result == false)
  352. throw new BusinessException("更新失败");
  353. return true;
  354. }
  355. /// <summary>
  356. /// 邮箱验证码
  357. /// </summary>
  358. /// <param name="request"></param>
  359. /// <returns></returns>
  360. [HttpPost("send-email-verify-code")]
  361. public async Task<bool> SendEmailVerifyCode(UserEmailVerifyCodeRequest request)
  362. {
  363. request.UserId = _loginContext.AccountId;
  364. var result = await _userRepository.SendEmailVerifyCodeAsync(request);
  365. if (result == false)
  366. throw new BusinessException("更新失败");
  367. return true;
  368. }
  369. /// <summary>
  370. /// 修改邮箱
  371. /// </summary>
  372. /// <param name="request"></param>
  373. /// <returns></returns>
  374. [HttpPost("update-user-email")]
  375. public async Task<bool> UpdateUserEmail(UserUpdateEmailRequest request)
  376. {
  377. request.UserId = _loginContext.AccountId;
  378. var result = await _userRepository.UpdateUserEmailAsync(request);
  379. if (result == false)
  380. throw new BusinessException("更新失败");
  381. return true;
  382. }
  383. /// <summary>
  384. /// 查询联系人
  385. /// </summary>
  386. /// <param name="request"></param>
  387. /// <returns></returns>
  388. [HttpPost("search")]
  389. public async Task<IEnumerable<UserInfoResult>> SearchUserName(SearchUserNameRequest request)
  390. {
  391. return await _userRepository.SearchUserNameAsync(request);
  392. }
  393. /// <summary>
  394. /// 根据部门ID获取自建ID获取用户列表
  395. /// </summary>
  396. /// <param name="request"></param>
  397. /// <returns></returns>
  398. [HttpPost("find")]
  399. public async Task<IEnumerable<UserInfoResult>> FindUser(FindUserRequest request)
  400. {
  401. request.UserId = _loginContext.AccountId;
  402. return await _userService.FindUser(request);
  403. }
  404. /// <summary>
  405. /// 根据部门ID获取自建ID获取用户列表
  406. /// </summary>
  407. /// <param name="name"></param>
  408. /// <returns></returns>
  409. [HttpGet("find-name")]
  410. public async Task<IEnumerable<UserInfoResult>> FindUserByName([FromQuery] string name)
  411. {
  412. return await _userRepository.UserByNameAsync(name);
  413. }
  414. /// <summary>
  415. /// 根据GUID查询用户
  416. /// </summary>
  417. /// <returns></returns>
  418. [HttpPost("guid")]
  419. public async Task<UserDetail> FindUserByGuid(FindUserByGuidRequest request)
  420. {
  421. var user = await _userRepository.GetGuidAsync(request.Guid);
  422. return user;
  423. }
  424. /// <summary>
  425. /// 获取用户工作模块未读数据
  426. /// </summary>
  427. /// <returns></returns>
  428. [HttpGet("user-uread-count")]
  429. public async Task<UserCountResult> GetUserCountAsync()
  430. {
  431. return await _userService.GetUserCountAsync(_loginContext.AccountId);
  432. }
  433. /// <summary>
  434. /// 根据用户名获取电脑上传的数据
  435. /// </summary>
  436. /// <returns></returns>
  437. [HttpGet("user-file-library")]
  438. public async Task<IEnumerable<FileLibraryResult>> GetFileLibraryByUserIdAsync()
  439. {
  440. return await fileLibraryRepository.GetFileLibraryByUserIdAsync(_loginContext.AccountId);
  441. }
  442. }
  443. }