ZhiYi/ZhiYi.Core.Application/Services/Implements/UserAppService.cs

157 lines
6.5 KiB
C#

using SlackNet;
using System.Text.RegularExpressions;
using ZhiYi.Core.Application.Dtos.PassInfo;
namespace ZhiYi.Core.Application.Services.Implements
{
public class UserAppService : IUserAppService
{
private readonly SqlSugarClient _client;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<UserAppService> _logger;
private readonly IConfiguration _configuration;
private readonly IDatabase _redis;
private readonly IConnectionClientManagerService _connectionClientManager;
public UserAppService(IConfiguration configuration, IServiceProvider serviceProvider, ILogger<UserAppService> logger, IConnectionMultiplexer redis, IConnectionClientManagerService connectionClientManager)
{
_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;
}
public async Task ChangePassAsync(ChangePassDto input)
{
if (input.PassWord.Length < 8)
throw new Exception("密码过于简单,不少于8位");
var exists = await _client.Queryable<ZhiYi_User>().AnyAsync(x => x.UserName == input.UserName && x.PassWord == input.PassWord);
if (!exists)
throw new Exception("旧密码不正确");
try
{
await _client.Updateable<ZhiYi_User>()
.SetColumns(x => x.PassWord == input.NewPass)
.ExecuteCommandAsync();
}
catch(Exception ex)
{
_logger.LogError("更改密码失败:{message}", ex.Message);
throw new Exception("更改密码失败");
}
}
public Task<string> GetMessageCodeAsync(string phone)
{
//调用短信接口
var code = "";
//账号为key写入缓存 时效1-3分钟 用作手机号+验证码验证
return Task.FromResult(string.Empty);
}
public async Task<string> GetSignature(SignatureCreationDto input)
{
var scope = _serviceProvider.CreateScope();
var tokenService = scope.ServiceProvider.GetService<TokenService>();
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<List<ZhiYi_User>> GetUserAsync()
{
_ = Task.Run(async () =>
{
await _connectionClientManager.SendAsync("1739582595", $"用户1739582595查询数据");
});
return await _client.Queryable<ZhiYi_User>()
.ToListAsync();
}
public async Task<LoginResponseDto> LoginAsync(UserLoginDto input)
{
var scope = _serviceProvider.CreateScope();
var _captcha = scope.ServiceProvider.GetRequiredService<CaptchaService>();
//验证码验证
var vify = _captcha.ValidateCaptcha(input.VifyId, input.VifyCode);
if (!vify)
{
throw new Exception("验证码不正确");
}
//账号密码验证
var user = await _client.Queryable<ZhiYi_User>().FirstAsync(x => x.UserName.Equals(input.UserName) && x.PassWord.Equals(input.PassWord));
if(user == null)
throw new Exception("账号或密码错误");
try
{
var _tokenService = scope.ServiceProvider.GetRequiredService<TokenService>();
//生成token
var token = _tokenService.GenerateTokenAsync(user.Id, user.UserName);
long unixTimestampMilliseconds = ((DateTimeOffset)DateTime.UtcNow.AddMinutes(30)).ToUnixTimeMilliseconds();
_ = Task.Run(async () =>
{
await _connectionClientManager.SendAsync(user.Id.ToString(), $"用户{user.Id}已登录");
});
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<ZhiYi_User>().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<ZhiYi_User> 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<ZhiYi_User>().Where(x => x.UserName == input.UserName).FirstAsync();
}
catch(Exception ex)
{
_logger.LogError("验证失败:{message}", ex.Message);
throw new Exception("验证失败");
}
}
}
}