ql_apimanager_backend/Apimanager_backend/Services/AuthService.cs
2024-11-06 23:12:12 +08:00

110 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<IAuthService> 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<AuthService> logger,IConnectionMultiplexer redis,IEmailService emailService)
{
this.apiContext = apiContext;
this.mapper = automapper;
this.logger = logger;
this.redis = redis;
this.emailService = emailService;
}
#region
public async Task<UserInfoDto> 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<UserInfoDto>(user);
}
#endregion
#region
public async Task<UserInfoDto> 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<UserInfoDto>(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}<br>有效期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
}
}