using SlackNet; using System.Text.RegularExpressions; using ZhiYi.Core.Application.Dtos.PassInfo; using ZhiYi.Core.Application.RedisServices; namespace ZhiYi.Core.Application.Services.Implements { public class UserAppService : IUserAppService { private readonly SqlSugarClient _client; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; private readonly IConfiguration _configuration; private readonly IDatabase _redis; private readonly IConnectionClientManagerService _connectionClientManager; private readonly SubscribeAndPublishService _subscribeAndPublishService; public UserAppService( IConfiguration configuration, IServiceProvider serviceProvider, ILogger logger, IConnectionMultiplexer redis, IConnectionClientManagerService connectionClientManager, SubscribeAndPublishService subscribeAndPublishService ) { _configuration = configuration; string connStr = _configuration.GetSection("ConnectionStrings:SqlConnection").Value; if (_client == null) { _client = SugarClientInit.Instance.GetDdClient(connStr); } _serviceProvider = serviceProvider; _logger = logger; _redis = redis.GetDatabase(); _connectionClientManager = connectionClientManager; _subscribeAndPublishService = subscribeAndPublishService; } /// /// 更改密码 /// /// /// public async Task ChangePassAsync(ChangePassDto input) { if (input.PassWord.Length < 8) throw new Exception("密码过于简单,不少于8位"); var exists = await _client.Queryable().AnyAsync(x => x.UserName == input.UserName && x.PassWord == input.PassWord); if (!exists) throw new Exception("旧密码不正确"); try { await _client.Updateable() .SetColumns(x => x.PassWord == input.NewPass) .ExecuteCommandAsync(); } catch(Exception ex) { _logger.LogError("更改密码失败:{message}", ex.Message); throw new Exception("更改密码失败"); } } /// /// 获取手机验证码 /// /// /// public Task GetMessageCodeAsync(string phone) { //调用短信接口 var code = ""; //账号为key写入缓存 时效1-3分钟 用作手机号+验证码验证 return Task.FromResult(string.Empty); } /// /// 获取签名 /// /// public async Task GetSignature(SignatureCreationDto input) { var scope = _serviceProvider.CreateScope(); var tokenService = scope.ServiceProvider.GetService(); long unixTimestampMilliseconds = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeMilliseconds(); return await Task.FromResult($"{tokenService.GenerateSignature(input.AppSecret, input.Path, unixTimestampMilliseconds.ToString(), input.Token)}:{unixTimestampMilliseconds.ToString()}"); } /// /// 获取用户列表 /// /// public async Task> GetUserAsync() { _ = Task.Run(async () => { await _connectionClientManager.SendAsync("1739582595", $"用户1739582595查询数据"); }); return await _client.Queryable() .ToListAsync(); } /// /// 登录 /// /// /// public async Task LoginAsync(UserLoginDto input) { var scope = _serviceProvider.CreateScope(); var _captcha = scope.ServiceProvider.GetRequiredService(); //验证码验证 var vify = _captcha.ValidateCaptcha(input.VifyId, input.VifyCode); if (!vify) { throw new Exception("验证码不正确"); } //账号密码验证 var user = await _client.Queryable().FirstAsync(x => x.UserName.Equals(input.UserName) && x.PassWord.Equals(input.PassWord)); if(user == null) throw new Exception("账号或密码错误"); try { var _tokenService = scope.ServiceProvider.GetRequiredService(); //生成token var token = _tokenService.GenerateTokenAsync(user.Id, user.UserName); long unixTimestampMilliseconds = ((DateTimeOffset)DateTime.UtcNow.AddMinutes(30)).ToUnixTimeMilliseconds(); _ = Task.Run(() => { //await _connectionClientManager.SendAsync(user.Id.ToString(), $"用户{user.Id}已登录"); _subscribeAndPublishService.Publish($"用户{user.Id}已登录", user.Id.ToString()); }); return new LoginResponseDto { UserId = user.Id, Token = token, Exp = unixTimestampMilliseconds }; } catch(Exception ex) { _logger.LogError("token获取错误:{message}", ex.Message); throw new Exception("登录失败,服务器出错"); } } /// /// 注册 /// /// 账号 /// public async Task RegisterAsync(UserCreationDto input) { if (!Regex.IsMatch(input.UserName, @"^1[3-9]\d{9}$")) throw new Exception("手机号格式不正确"); var exists = await _client.Queryable().AnyAsync(x => x.UserName == input.UserName); if (exists) throw new Exception("账号已存在"); if (input.PassWord.Length < 8) throw new Exception("密码过于简单,不少于8位"); var user = new ZhiYi_User { Id = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), UserName = input.UserName, PassWord = input.PassWord, CreateTime = DateTime.Now }; try { await _client.Insertable(user).ExecuteCommandAsync(); } catch (Exception ex) { _logger.LogInformation("注册失败:{message}",ex.Message); throw new Exception($"注册失败:{ex.Message}"); } } /// /// 验证码验证 /// /// public async Task VefiyCodeAsync(MessageCodeVefiyDto input) { try { var code = await _redis.StringGetAsync($"Code:{input.UserName}"); if (!code.HasValue) throw new Exception("验证码已失效"); if (code != input.VefiyCode) throw new Exception("验证码不正确"); return await _client.Queryable().Where(x => x.UserName == input.UserName).FirstAsync(); } catch(Exception ex) { _logger.LogError("验证失败:{message}", ex.Message); throw new Exception("验证失败"); } } } }