using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Datory.Utils; using GxPress.Api.Tools; using GxPress.Auth; using GxPress.Common.Exceptions; using GxPress.Common.Tools; using GxPress.Common.Validation; using GxPress.Entity; using GxPress.EnumConst; using GxPress.Repository.Interface; using GxPress.Request.App.User; using GxPress.Request.User; using GxPress.Result.App.FileLibrary; using GxPress.Result.App.User; using GxPress.Result.User; using GxPress.Service.Interface; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace GxPress.Api.AppControllers { /// /// 用户 /// [Route("/api/app/user")] [ApiController] [Authorize] public class UserController : ControllerBase { private readonly JwtOptions _jwtOptions; private readonly ILogger _logger; private readonly IUserRepository _userRepository; private readonly IDepartmentRepository _departmentRepository; private readonly ILoginContext _loginContext; private readonly IUserService _userService; private readonly IFileLibraryRepository fileLibraryRepository; private readonly IDistributedCache _cache; public UserController(IUserRepository userRepository, IOptions jwtOptions, ILogger logger, IDepartmentRepository departmentRepository, ILoginContext loginContext, IUserService userService, IFileLibraryRepository fileLibraryRepository, IDistributedCache cache) { _userRepository = userRepository; _departmentRepository = departmentRepository; _userService = userService; _jwtOptions = jwtOptions.Value; _logger = logger; _loginContext = loginContext; this.fileLibraryRepository = fileLibraryRepository; _cache = cache; } ///// ///// 添加 ///// ///// ///// //[HttpPost] //public async Task Add([FromBody] User request) //{ // request.Id = await _userRepository.InsertAsync(request); // return request; //} /// /// 登录 /// /// /// [HttpPost("signin")] [AllowAnonymous] public async Task SignIn(UserSignInRequest request) { var result = await _userRepository.SignInAsync(request); if (result.IsAddUser) { //添加环信 await _userRepository.CreateMiUserAsync(result.UserEntity); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()), new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString()), new Claim(ClaimTypes.GroupSid,result.DepartmentId.ToString()) }; result.Token = TokenHelper.BuildToken(_jwtOptions, claims); return result; } /// /// 绑定opendId /// /// /// [HttpPost("set-opend-Id")] [AllowAnonymous] public async Task SetOpenId(UserSignInRequest request) { var success = await _userRepository.UpdateByOpendIdAsync(request); if (success) { var result = await _userRepository.SignInAsync(request); if (result.IsAddUser) { //添加环信 await _userRepository.CreateMiUserAsync(result.UserEntity); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, result.UserId.ToString()), new Claim(ClaimTypes.Role, AccountTypeConst.User.ToString()), new Claim(ClaimTypes.GroupSid,result.DepartmentId.ToString()) }; result.Token = TokenHelper.BuildToken(_jwtOptions, claims); return result; } return new UserSignInResult(); } /// /// 查询opendId是否存在 /// /// /// [HttpGet("find-opend-Id/{opendId}")] [AllowAnonymous] public async Task FindOpenId(string opendId) { var user = await _userRepository.GetByOpenIdAsync(opendId); if (user == null) return false; return true; } /////// /////// 登录验证码发送 /////// /////// /////// ////[HttpGet("sendSmsCode")] ////[AllowAnonymous] ////public async Task SendSmsCode([FromQuery] [Required] [Mobile] string phone) ////{ //// var user = await _userRepository.GetByPhoneAsync(phone); //// //用户不存在 //// if (user == null) //// { //// throw new BusinessException("该用户不存在"); //// } //// //TODO 短信验证码发送 //// //return await _smsService. //// //SendValidationCodeAsync(phone); //// var key = $"login:{phone}"; //// if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁"); //// var code = RandomGenerator.GetNumberString(6); //// _logger.LogInformation("{phone}验证码:{code}", phone, code); //// //发送验证码阿里云 //// IClientProfile profile = //// DefaultProfile.GetProfile("cn-hangzhou", "LTAI2E47R4DlcYfo", "5epQRUGRrDSoF7yukyYf4HX6dUlvF3"); //// DefaultAcsClient client = new DefaultAcsClient(profile); //// CommonRequest request = new CommonRequest //// { //// Method = MethodType.POST, //// Domain = "dysmsapi.aliyuncs.com", //// Version = "2017-05-25", //// Action = "SendSms" //// }; //// request.AddQueryParameters("PhoneNumbers", $"{phone}"); //// request.AddQueryParameters("SignName", "泰德合众"); //// request.AddQueryParameters("TemplateCode", "SMS_168126117"); //// request.AddQueryParameters("TemplateParam", "{\"code\":\"" + code + "\"}"); //// try //// { //// CommonResponse response = client.GetCommonResponse(request); //// _logger.LogInformation(Encoding.Default.GetString(response.HttpResponse.Content)); //// } //// catch (ServerException e) //// { //// throw new BusinessException(e.Message); //// } //return await RedisHelper.SetAsync(key, code, 300); ////} /// /// 登录验证码发送 /// /// /// [HttpGet("sendSmsCode")] [AllowAnonymous] public async Task SendSmsCode([FromQuery][Required][Mobile] string phone) { var user = await _userRepository.GetByPhoneAsync(phone); //用户不存在 if (user == null) { user = new User(); user.Name = phone; user.Phone = phone; user.ImId = phone; user.Id = await _userRepository.InsertAsync(user); if (user.Id > 0 && await _userRepository.CreateMiUserAsync(user)) { } } //TODO 短信验证码发送 //return await _smsService. //SendValidationCodeAsync(phone); //发送短信 var key = $"login:{phone}"; var code = await _cache.GetStringAsync(key); if (!string.IsNullOrEmpty(code)) throw new BusinessException("请求太频繁!"); code = RandomGenerator.GetNumberString(6); //code = "123456"; if (Common.Sms.AliySms.SendSms(phone, code)) { _logger.LogInformation("{phone}验证码:{code}", phone, code); var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code)); await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) }); return true; } return false; } /// /// 更换手机号码验证码发送 /// /// /// [HttpGet("send-sms-code")] public async Task SendSmsCodeReplace([FromQuery][Required][Mobile] string phone) { var user = await _userRepository.GetByPhoneAsync(phone); if (user != null) throw new BusinessException("号码以被使用"); //TODO 短信验证码发送 //发送短信 var key = $"login:{phone}"; var code = await _cache.GetStringAsync(key); if (!string.IsNullOrEmpty(code)) throw new BusinessException("请求太频繁!"); code = RandomGenerator.GetNumberString(6); //code = "123456"; if (Common.Sms.AliySms.SendSms(phone, code)) { _logger.LogInformation("{phone}验证码:{code}", phone, code); var codeByte = Encoding.UTF8.GetBytes(Utilities.JsonSerialize(code)); await _cache.SetAsync($"{key}", codeByte, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) }); return true; } return false; } /// /// app查询用户详情 /// /// [HttpGet("detail")] public async Task GetDetail() { var id = _loginContext.AccountId; var user = await _userRepository.GetAsync(id); if (user == null) throw new BusinessException("用户id有误"); return await _userRepository.GetDetailAsync(id); } /// /// app查询他人用户详情 /// /// [HttpGet("detail/{id}")] public async Task GetDetail(int id) { if (id <= 0) throw new BusinessException("用户id有误"); return await _userService.GetUserByIdAsync(_loginContext.AccountId, id); } /// /// app更新用户信息 /// /// /// [HttpPut("update")] public async Task Update([FromBody] User request) { var id = _loginContext.AccountId; var result = await _userRepository.UpdateAsync(id, request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 私信 /// /// [HttpPost("update-user-private-letter")] public async Task UpdateUserPrivateLetter() { UserPrivateLetterRequest request = new UserPrivateLetterRequest { Id = _loginContext.AccountId }; var result = await _userRepository.UpdateUserPrivateLetterAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 通知 /// /// [HttpPost("update-user-notice")] public async Task UpdateUserNotice() { var request = new UserNoticeRequest { Id = _loginContext.AccountId }; var result = await _userRepository.UpdateUserNoticeAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 回复 /// /// [HttpPost("update-user-reply")] public async Task UpdateUserReply() { var request = new UserReplyRequest { Id = _loginContext.AccountId }; var result = await _userRepository.UpdateUserReplyAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 静音 /// /// [HttpPost("update-user-mute")] public async Task UpdateUserMute() { var request = new UserMuteRequest { Id = _loginContext.AccountId }; var result = await _userRepository.UpdateUserMuteAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 震动 /// /// [HttpPost("update-user-shake")] public async Task UpdateUserShake() { var request = new UserShakeRequest { Id = _loginContext.AccountId }; var result = await _userRepository.UpdateUserShakeAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 用户修改手机号码 /// /// /// [HttpPost("update-user-phone")] public async Task UpdateUserPhone(UserUpdatePhoneRequest request) { request.UserId = _loginContext.AccountId; var result = await _userRepository.UpdateUserPhoneAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 邮箱验证码 /// /// /// [HttpPost("send-email-verify-code")] public async Task SendEmailVerifyCode(UserEmailVerifyCodeRequest request) { request.UserId = _loginContext.AccountId; var result = await _userRepository.SendEmailVerifyCodeAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 修改邮箱 /// /// /// [HttpPost("update-user-email")] public async Task UpdateUserEmail(UserUpdateEmailRequest request) { request.UserId = _loginContext.AccountId; var result = await _userRepository.UpdateUserEmailAsync(request); if (result == false) throw new BusinessException("更新失败"); return true; } /// /// 查询联系人 /// /// /// [HttpPost("search")] public async Task> SearchUserName(SearchUserNameRequest request) { return await _userRepository.SearchUserNameAsync(request); } /// /// 根据部门ID获取自建ID获取用户列表 /// /// /// [HttpPost("find")] public async Task> FindUser(FindUserRequest request) { request.UserId = _loginContext.AccountId; return await _userService.FindUser(request); } /// /// 根据部门ID获取自建ID获取用户列表 /// /// /// [HttpGet("find-name")] public async Task> FindUserByName([FromQuery] string name) { return await _userRepository.UserByNameAsync(name); } /// /// 根据GUID查询用户 /// /// [HttpPost("guid")] public async Task FindUserByGuid(FindUserByGuidRequest request) { var user = await _userRepository.GetGuidAsync(request.Guid); return user; } /// /// 获取用户工作模块未读数据 /// /// [HttpGet("user-uread-count")] public async Task GetUserCountAsync() { return await _userService.GetUserCountAsync(_loginContext.AccountId); } /// /// 根据用户名获取电脑上传的数据 /// /// [HttpGet("user-file-library")] public async Task> GetFileLibraryByUserIdAsync() { return await fileLibraryRepository.GetFileLibraryByUserIdAsync(_loginContext.AccountId); } } }