UserController.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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.MasSms.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. //return await _smsService.
  221. //SendValidationCodeAsync(phone);
  222. var key = $"login:{phone}";
  223. // if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  224. var code = "180606";
  225. _logger.LogInformation("{phone}验证码:{code}", phone, code);
  226. //var result = await RedisHelper.SetAsync(key, code, 300);
  227. //if (result == false)
  228. // throw new BusinessException("发送失败");
  229. return true;
  230. }
  231. /// <summary>
  232. /// app查询用户详情
  233. /// </summary>
  234. /// <returns></returns>
  235. [HttpGet("detail")]
  236. public async Task<UserDetail> GetDetail()
  237. {
  238. var id = _loginContext.AccountId;
  239. var user = await _userRepository.GetAsync(id);
  240. if (user == null)
  241. throw new BusinessException("用户id有误");
  242. return await _userRepository.GetDetailAsync(id);
  243. }
  244. /// <summary>
  245. /// app查询他人用户详情
  246. /// </summary>
  247. /// <returns></returns>
  248. [HttpGet("detail/{id}")]
  249. public async Task<UserDetail> GetDetail(int id)
  250. {
  251. if (id <= 0)
  252. throw new BusinessException("用户id有误");
  253. return await _userService.GetUserByIdAsync(_loginContext.AccountId, id);
  254. }
  255. /// <summary>
  256. /// app更新用户信息
  257. /// </summary>
  258. /// <param name="request"></param>
  259. /// <returns></returns>
  260. [HttpPut("update")]
  261. public async Task<bool> Update([FromBody] User request)
  262. {
  263. var id = _loginContext.AccountId;
  264. var result = await _userRepository.UpdateAsync(id, request);
  265. if (result == false)
  266. throw new BusinessException("更新失败");
  267. return true;
  268. }
  269. /// <summary>
  270. /// 私信
  271. /// </summary>
  272. /// <returns></returns>
  273. [HttpPost("update-user-private-letter")]
  274. public async Task<bool> UpdateUserPrivateLetter()
  275. {
  276. UserPrivateLetterRequest request = new UserPrivateLetterRequest { Id = _loginContext.AccountId };
  277. var result = await _userRepository.UpdateUserPrivateLetterAsync(request);
  278. if (result == false)
  279. throw new BusinessException("更新失败");
  280. return true;
  281. }
  282. /// <summary>
  283. /// 通知
  284. /// </summary>
  285. /// <returns></returns>
  286. [HttpPost("update-user-notice")]
  287. public async Task<bool> UpdateUserNotice()
  288. {
  289. var request = new UserNoticeRequest { Id = _loginContext.AccountId };
  290. var result = await _userRepository.UpdateUserNoticeAsync(request);
  291. if (result == false)
  292. throw new BusinessException("更新失败");
  293. return true;
  294. }
  295. /// <summary>
  296. /// 回复
  297. /// </summary>
  298. /// <returns></returns>
  299. [HttpPost("update-user-reply")]
  300. public async Task<bool> UpdateUserReply()
  301. {
  302. var request = new UserReplyRequest { Id = _loginContext.AccountId };
  303. var result = await _userRepository.UpdateUserReplyAsync(request);
  304. if (result == false)
  305. throw new BusinessException("更新失败");
  306. return true;
  307. }
  308. /// <summary>
  309. /// 静音
  310. /// </summary>
  311. /// <returns></returns>
  312. [HttpPost("update-user-mute")]
  313. public async Task<bool> UpdateUserMute()
  314. {
  315. var request = new UserMuteRequest { Id = _loginContext.AccountId };
  316. var result = await _userRepository.UpdateUserMuteAsync(request);
  317. if (result == false)
  318. throw new BusinessException("更新失败");
  319. return true;
  320. }
  321. /// <summary>
  322. /// 震动
  323. /// </summary>
  324. /// <returns></returns>
  325. [HttpPost("update-user-shake")]
  326. public async Task<bool> UpdateUserShake()
  327. {
  328. var request = new UserShakeRequest { Id = _loginContext.AccountId };
  329. var result = await _userRepository.UpdateUserShakeAsync(request);
  330. if (result == false)
  331. throw new BusinessException("更新失败");
  332. return true;
  333. }
  334. /// <summary>
  335. /// 用户修改手机号码
  336. /// </summary>
  337. /// <param name="request"></param>
  338. /// <returns></returns>
  339. [HttpPost("update-user-phone")]
  340. public async Task<bool> UpdateUserPhone(UserUpdatePhoneRequest request)
  341. {
  342. request.UserId = _loginContext.AccountId;
  343. var result = await _userRepository.UpdateUserPhoneAsync(request);
  344. if (result == false)
  345. throw new BusinessException("更新失败");
  346. return true;
  347. }
  348. /// <summary>
  349. /// 邮箱验证码
  350. /// </summary>
  351. /// <param name="request"></param>
  352. /// <returns></returns>
  353. [HttpPost("send-email-verify-code")]
  354. public async Task<bool> SendEmailVerifyCode(UserEmailVerifyCodeRequest request)
  355. {
  356. request.UserId = _loginContext.AccountId;
  357. var result = await _userRepository.SendEmailVerifyCodeAsync(request);
  358. if (result == false)
  359. throw new BusinessException("更新失败");
  360. return true;
  361. }
  362. /// <summary>
  363. /// 修改邮箱
  364. /// </summary>
  365. /// <param name="request"></param>
  366. /// <returns></returns>
  367. [HttpPost("update-user-email")]
  368. public async Task<bool> UpdateUserEmail(UserUpdateEmailRequest request)
  369. {
  370. request.UserId = _loginContext.AccountId;
  371. var result = await _userRepository.UpdateUserEmailAsync(request);
  372. if (result == false)
  373. throw new BusinessException("更新失败");
  374. return true;
  375. }
  376. /// <summary>
  377. /// 查询联系人
  378. /// </summary>
  379. /// <param name="request"></param>
  380. /// <returns></returns>
  381. [HttpPost("search")]
  382. public async Task<IEnumerable<UserInfoResult>> SearchUserName(SearchUserNameRequest request)
  383. {
  384. return await _userRepository.SearchUserNameAsync(request);
  385. }
  386. /// <summary>
  387. /// 根据部门ID获取自建ID获取用户列表
  388. /// </summary>
  389. /// <param name="request"></param>
  390. /// <returns></returns>
  391. [HttpPost("find")]
  392. public async Task<IEnumerable<UserInfoResult>> FindUser(FindUserRequest request)
  393. {
  394. request.UserId = _loginContext.AccountId;
  395. return await _userService.FindUser(request);
  396. }
  397. /// <summary>
  398. /// 根据部门ID获取自建ID获取用户列表
  399. /// </summary>
  400. /// <param name="name"></param>
  401. /// <returns></returns>
  402. [HttpGet("find-name")]
  403. public async Task<IEnumerable<UserInfoResult>> FindUserByName([FromQuery] string name)
  404. {
  405. return await _userRepository.UserByNameAsync(name);
  406. }
  407. /// <summary>
  408. /// 根据GUID查询用户
  409. /// </summary>
  410. /// <returns></returns>
  411. [HttpPost("guid")]
  412. public async Task<UserDetail> FindUserByGuid(FindUserByGuidRequest request)
  413. {
  414. var user = await _userRepository.GetGuidAsync(request.Guid);
  415. return user;
  416. }
  417. /// <summary>
  418. /// 获取用户工作模块未读数据
  419. /// </summary>
  420. /// <returns></returns>
  421. [HttpGet("user-uread-count")]
  422. public async Task<UserCountResult> GetUserCountAsync()
  423. {
  424. return await _userService.GetUserCountAsync(_loginContext.AccountId);
  425. }
  426. /// <summary>
  427. /// 根据用户名获取电脑上传的数据
  428. /// </summary>
  429. /// <returns></returns>
  430. [HttpGet("user-file-library")]
  431. public async Task<IEnumerable<FileLibraryResult>> GetFileLibraryByUserIdAsync()
  432. {
  433. return await fileLibraryRepository.GetFileLibraryByUserIdAsync(_loginContext.AccountId);
  434. }
  435. }
  436. }