using Apimanager_backend.Data; using Apimanager_backend.Dtos; using Apimanager_backend.Exceptions; using Apimanager_backend.Models; using Apimanager_backend.Tools; using AutoMapper; using Microsoft.EntityFrameworkCore; using StackExchange.Redis; namespace Apimanager_backend.Services { public class AuthService:IAuthService { private readonly ApiContext apiContext; private readonly ILogger logger; private readonly IConnectionMultiplexer redis; private readonly IEmailService emailService; private readonly IMapper mapper; private readonly int DbIndex = 1; public AuthService(ApiContext apiContext, IMapper automapper,ILogger logger,IConnectionMultiplexer redis,IEmailService emailService) { this.apiContext = apiContext; this.mapper = automapper; this.logger = logger; this.redis = redis; this.emailService = emailService; } #region 用户登录 public async Task LoginAsync(string username, string password) { //查找用户 User? user = await apiContext.Users.Include(x => x.Roles).SingleOrDefaultAsync(x => x.Username == username && x.PassHash == password ); //用户不存在或密码错误都为登录失败 if (user == null) { throw new BaseException(2001, "Invalid username or password"); } //用户被禁用 if (user.IsBan) { throw new BaseException(2002, "User account is disabled"); } return mapper.Map(user); } #endregion #region 用户注册 public async Task RegisterAsync(RegisterRequestDto dto) { var db = redis.GetDatabase(DbIndex); //获取邮箱对应验证码 var code = await db.StringGetAsync(dto.Email); if(!code.HasValue || code.ToString() != dto.VerificationCode) { throw new BaseException(5005,"验证码错误"); } User user = new User { Username = dto.Username, PassHash = dto.Password, Email = dto.Email, IsBan = false, IsDelete = false, Balance = 0, }; try { //添加新用户 await apiContext.Users.AddAsync(user); await apiContext.SaveChangesAsync(); UserRole userRole = new UserRole { UserId = user.Id, Role = "User" }; await apiContext.UserRoles.AddAsync(userRole); await apiContext.SaveChangesAsync(); return mapper.Map(user); }catch(Exception e) { throw new BaseException(1005,e.Message); } } #endregion #region 发送注册验证码 public async Task SendRegisterCodeAsync(string email) { //生成随机码 string code = RandomCodeHelper.GetRandomCodeStr(); string subject = "注册验证码"; string body = $"您的注册验证码为:{code}
有效期60分钟!"; //随机码写入redis var db = redis.GetDatabase(DbIndex); bool redisSuccess = await db.StringSetAsync(email,code,TimeSpan.FromHours(1)); if (!redisSuccess) { throw new BaseException(1005,"Redis Str Set Error"); } //发送邮件 await emailService.SendEmailAsync(email,subject,body); } #endregion } }