using Apimanager_backend.Config; using Apimanager_backend.Data; using Apimanager_backend.Dtos; using Apimanager_backend.Exceptions; using Apimanager_backend.Models; using Apimanager_backend.Tools; using AutoMapper; using Microsoft.AspNetCore.Connections.Features; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using StackExchange.Redis; using System.ComponentModel; namespace Apimanager_backend.Services { public class UserService : IUserService { private readonly ApiContext apiContext; private readonly IMapper mapper; private readonly ILogger logger; private readonly IConnectionMultiplexer redis; private readonly IEmailService emailService; private readonly int DbSet = 2; public UserService(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; } public async Task GetUserAsync(int userId) { User? user = await apiContext.Users.SingleOrDefaultAsync(x => x.Id == userId); //未找到用户 if (user == null) { throw new BaseException(2004, "User not found"); } return mapper.Map(user); } public async Task IsEmailExist(string email) { return await apiContext.Users.AnyAsync(x => x.Email == email); } public async Task IsUsernameExist(string username) { return await apiContext.Users.AnyAsync(x => x.Username == username); } public async Task ResetPasswordAsync(string email, string code, string newPassword) { //校验验证码 var db = redis.GetDatabase(DbSet); var value = await db.StringGetAsync(email); if (!value.HasValue || value.ToString() != code) { throw new BaseException(5005, "验证码错误"); } //验证成功,开始重置流程 var user = await apiContext.Users.FirstOrDefaultAsync(x => x.Email == email); if(user == null) { throw new BaseException(2004, "用户不存在"); } //修改密码 user.PassHash = newPassword; apiContext.Users.Update(user); await apiContext.SaveChangesAsync(); } #region 发送密码重置邮件 public async Task SendResetPasswordEmailAsync(string email) { var randomCode = RandomCodeHelper.GetRandomCodeStr(); //记录到redis var db = redis.GetDatabase(DbSet); bool redisSuccess = await db.StringSetAsync(email,randomCode,TimeSpan.FromHours(1)); if (!redisSuccess) { throw new BaseException(1005, "Redis Str Set Error"); } string subject = "重置验证码"; string body = $"您的重置验证码为:{randomCode}
有效期60分钟!"; //发送邮件 await emailService.SendEmailAsync(email,subject,body); } #endregion public async Task UpdateUserAsync(int userId,UpdateUserDto dto) { var user = await apiContext.Users.FirstOrDefaultAsync(x => x.Id == userId); if (user == null) { throw new BaseException(2004, "用户不存在"); } user.PassHash = dto.password == null ? user.PassHash : dto.password; apiContext.Users.Update(user); await apiContext.SaveChangesAsync(); return mapper.Map(user); } } }