Merge branch 'dev_add_auth_1029' into 'master'

Dev add auth 1029

See merge request ql/apismnagaer_backend!8
This commit is contained in:
2024-11-06 23:12:12 +08:00
committed by 南浔
34 changed files with 1461 additions and 191 deletions
+112
View File
@@ -0,0 +1,112 @@
using Apimanager_backend.Data;
using Apimanager_backend.Dtos;
using Apimanager_backend.Exceptions;
using Apimanager_backend.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
namespace Apimanager_backend.Services
{
public class AdminService : IAdminService
{
private readonly ApiContext context;
private readonly IMapper mapper;
private readonly ILogger<IAdminService> logger;
public AdminService(ApiContext context, IMapper mapper, ILogger<IAdminService> logger)
{
this.context = context;
this.mapper = mapper;
this.logger = logger;
}
#region
public async Task BanUserAsync(int userId)
{
var user = await context.Users.FirstOrDefaultAsync(x => x.Id == userId);
if (user == null)
{
throw new BaseException(2004,"用户不存在");
}
user.IsBan = true;
context.Users.Update(user);
await context.SaveChangesAsync();
}
#endregion
#region
public async Task<UserInfoDto> CreateUserAsync(CreateUserDto dto)
{
//添加用户
var user = mapper.Map<User>(dto);
context.Users.Add(user);
await context.SaveChangesAsync();
//添加默认角色
UserRole userRole = new UserRole
{
UserId = user.Id,
Role = "User"
};
context.UserRoles.Add(userRole);
await context.SaveChangesAsync();
return mapper.Map<UserInfoDto>(user);
}
#endregion
#region
public async Task DeleteUserAsync(int userId)
{
var user = await context.Users.FirstOrDefaultAsync(x => x.Id == userId);
if (user == null)
{
throw new BaseException(2004, "用户不存在");
}
user.IsDelete = true;
context.Users.Update(user);
await context.SaveChangesAsync();
}
#endregion
#region
public async Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc)
{
var query = context.Users.Where(x => true)
.OrderBy(x => x.Id);
//倒序
if (desc)
{
query = query.OrderByDescending(x => x.Id);
}
//分页
var users = await query.Skip((page - 1) * pageSize)
.Take(pageSize).ToListAsync();
return mapper.Map<List<UserInfoDto>>(users);
}
#endregion
#region
public async Task UnbanUserAsync(int userId)
{
var user = await context.Users.FirstOrDefaultAsync(x => x.Id == userId);
if (user == null)
{
throw new BaseException(2004, "用户不存在");
}
user.IsBan = false;
context.Users.Update(user);
await context.SaveChangesAsync();
}
#endregion
#region
public async Task<UserInfoDto> UpdateUserAsync(int userId,AdminUpdateUserDto dto)
{
var user = await context.Users.FirstOrDefaultAsync(x => x.Id == userId);
if(user == null)
{
throw new BaseException(2004,"用户不存在");
}
user.PassHash = dto.Password;
user.Balance = dto.Balance;
context.Users.Update(user);
await context.SaveChangesAsync();
return mapper.Map<UserInfoDto>(user);
}
#endregion
}
}
+69 -1
View File
@@ -2,20 +2,30 @@
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;
public AuthService(ApiContext apiContext, IMapper automapper)
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)
{
//查找用户
@@ -37,5 +47,63 @@ namespace Apimanager_backend.Services
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
}
}
@@ -0,0 +1,49 @@
using Apimanager_backend.Exceptions;
using System.Net;
using System.Net.Mail;
namespace Apimanager_backend.Services
{
public class EmailService:IEmailService
{
private readonly IConfiguration _configuration;
public EmailService(IConfiguration configuration)
{
_configuration = configuration;
SmtpHost = _configuration["EmailSettings:Server"];
Port = int.Parse(_configuration["EmailSettings:Port"]);
Username = _configuration["EmailSettings:Username"];
Password = _configuration["EmailSettings:Password"];
EnableSSL = bool.Parse(_configuration["EmailSettings:Ssl"]);
}
private string SmtpHost { get; set; }
private int Port { get; set; }
public bool EnableSSL { get; set; }
private string Username { get; set; }
private string Password { get; set; }
public async Task SendEmailAsync(string toEmail,string subject,string body)
{
try
{
using SmtpClient smtpClient = new SmtpClient(SmtpHost, Port)
{
Credentials = new NetworkCredential(Username, Password),
EnableSsl = EnableSSL, //启用ssl
Timeout = 30000
};
using var emailMessage = new MailMessage
{
From = new MailAddress(Username),
Subject = subject,
Body = body,
IsBodyHtml = true
};
emailMessage.To.Add(toEmail);
await smtpClient.SendMailAsync(emailMessage);
}catch(Exception e)
{
throw new BaseException(5004,e.Message);
}
}
}
}
@@ -0,0 +1,45 @@
using Apimanager_backend.Dtos;
namespace Apimanager_backend.Services
{
public interface IAdminService
{
/// <summary>
/// 禁用用户,使其无法登录。
/// </summary>
/// <param name="userId">要禁用的用户ID</param>
/// <returns>异步操作</returns>
Task BanUserAsync(int userId);
/// <summary>
/// 取消禁用用户,恢复登录权限。
/// </summary>
/// <param name="userId">要取消禁用的用户ID</param>
/// <returns>异步操作</returns>
Task UnbanUserAsync(int userId);
/// <summary>
/// 获取分页的用户列表。
/// </summary>
/// <param name="page">要获取的页码,从1开始</param>
/// <param name="pageSize">每页的用户数量</param>
/// <param name="desc">是否按降序排序</param>
/// <returns>包含用户信息的 <see cref="List{UserInfoDto}"/></returns>
Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc);
/// <summary>
/// 创建新用户。
/// </summary>
/// <param name="user">包含新用户信息的 <see cref="CreateUserDto"/></param>
/// <returns>创建成功的用户信息 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> CreateUserAsync(CreateUserDto user);
/// <summary>
/// 删除指定的用户。
/// </summary>
/// <param name="userId">用户ID</param>
/// <returns>异步操作</returns>
Task DeleteUserAsync(int userId);
/// <summary>
/// 修改用户信息
/// </summary>
/// <returns></returns>
Task<UserInfoDto> UpdateUserAsync(int userId,AdminUpdateUserDto dto);
}
}
@@ -11,5 +11,17 @@ namespace Apimanager_backend.Services
/// <param name="password">密码</param>
/// <returns>包含用户信息的 <see cref="UserInfoBaseDto"/></returns>
Task<UserInfoDto> LoginAsync(string username, string password);
/// <summary>
/// 用户注册邮箱验证码
/// </summary>
/// <param name="email"></param>
/// <returns></returns>
Task SendRegisterCodeAsync(string email);
/// <summary>
/// 用户注册
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserInfoDto> RegisterAsync(RegisterRequestDto dto);
}
}
@@ -0,0 +1,14 @@
namespace Apimanager_backend.Services
{
public interface IEmailService
{
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="toEmail">收件人邮箱</param>
/// <param name="subject">主题</param>
/// <param name="body">正文</param>
/// <returns></returns>
public Task SendEmailAsync(string toEmail,string subject,string body);
}
}
@@ -13,18 +13,18 @@
/// </summary>
/// <param name="refreshToken">刷新令牌</param>
/// <returns>是否验证通过</returns>
Task<string?> ValidateRefreshTokenAsync(string refreshToken);
Task<bool> ValidateRefreshTokenAsync(string userId,string refreshToken);
/// <summary>
/// 删除刷新令牌
/// </summary>
/// <param name="refreshToken">刷新令牌</param>
/// <returns>是否删除成功</returns>
Task DeleterRefreshTokenAsync(string refreshToken);
Task DeleterRefreshTokenAsync(string userId);
/// <summary>
/// 更新刷新令牌有效期
/// </summary>
/// <param name="refreshToken">刷新令牌</param>
/// <param name="userId">用户id</param>
/// <returns>是否成功</returns>
Task UpdateRefreshTokenAsync(string refreshToken);
Task UpdateRefreshTokenAsync(string userId);
}
}
+38 -65
View File
@@ -6,73 +6,46 @@ namespace Apimanager_backend.Services
{
public interface IUserService
{
/// <summary>
/// 发送密码重置邮件到指定邮箱。
/// </summary>
/// <param name="email">用户注册的邮箱地址</param>
/// <returns>异步操作</returns>
Task SendResetPasswordEmailAsync(string email);
/// <summary>
/// 发送密码重置邮件到指定邮箱
/// </summary>
/// <param name="email">用户注册的邮箱地址</param>
/// <returns>异步操作</returns>
Task SendResetPasswordEmailAsync(string email);
/// <summary>
/// 重置用户密码,验证重置令牌的有效性并更新密码
/// </summary>
/// <param name="email">用户邮箱地址</param>
/// <param name="token">重置密码的令牌</param>
/// <param name="newPassword">新的密码</param>
/// <returns>异步操作</returns>
Task ResetPasswordAsync(string email, string code, string newPassword);
/// <summary>
/// 重置用户密码,验证重置令牌的有效性并更新密码
/// </summary>
/// <param name="email">用户邮箱地址</param>
/// <param name="token">重置密码的令牌</param>
/// <param name="newPassword">新的密码</param>
/// <returns>异步操作</returns>
Task ResetPasswordAsync(string email, string token, string newPassword);
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="userId">用户ID</param>
/// <returns>包含用户信息的 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> GetUserAsync(int userId);
/// <summary>
/// 获取用户信息。
/// </summary>
/// <param name="userId">用户ID</param>
/// <returns>包含用户信息的 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> GetUserAsync(int userId);
/// <summary>
/// 更新用户信息。
/// </summary>
/// <param name="user">包含更新信息的 <see cref="UpdateUserDto"/></param>
/// <returns>更新后的 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> UpdateUserAsync(UpdateUserDto user);
/// <summary>
/// 删除指定的用户。
/// </summary>
/// <param name="username">要删除的用户名</param>
/// <returns>异步操作</returns>
Task DeleteUserAsync(string username);
/// <summary>
/// 创建新用户。
/// </summary>
/// <param name="user">包含新用户信息的 <see cref="CreateUserDto"/></param>
/// <returns>创建成功的用户信息 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> CreateUserAsync(CreateUserDto user);
/// <summary>
/// 禁用用户,使其无法登录。
/// </summary>
/// <param name="username">要禁用的用户名</param>
/// <returns>异步操作</returns>
Task BanUserAsync(string username);
/// <summary>
/// 取消禁用用户,恢复登录权限。
/// </summary>
/// <param name="username">要取消禁用的用户名</param>
/// <returns>异步操作</returns>
Task UnbanUserAsync(string username);
/// <summary>
/// 获取分页的用户列表。
/// </summary>
/// <param name="page">要获取的页码,从1开始</param>
/// <param name="pageSize">每页的用户数量</param>
/// <param name="desc">是否按降序排序</param>
/// <returns>包含用户信息的 <see cref="List{UserInfoDto}"/></returns>
Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc);
/// <summary>
/// 更新用户信息。
/// </summary>
/// <param name="user">包含更新信息的 <see cref="UpdateUserDto"/></param>
/// <returns>更新后的 <see cref="UserInfoDto"/></returns>
Task<UserInfoDto> UpdateUserAsync(int userId,UpdateUserDto user);
/// <summary>
/// 检测用户名是否被使用
/// </summary>
/// <param name="username">用户名</param>
/// <returns></returns>
Task<bool> IsUsernameExist(string username);
/// <summary>
/// 检测邮箱是否被使用
/// </summary>
/// <param name="email">邮箱</param>
/// <returns></returns>
Task<bool> IsEmailExist(string email);
}
}
@@ -7,62 +7,72 @@ namespace Apimanager_backend.Services
{
private readonly IConnectionMultiplexer redis;
private readonly IConfiguration configuration;
private readonly int DbIndex = 0;
public RefreshTokenService(IConnectionMultiplexer redis, IConfiguration configuration)
{
this.redis = redis;
this.configuration = configuration;
}
#region
public async Task<string> CreateRefereshTokenAsync(string userId)
{
var refreshToken = Guid.NewGuid().ToString();
var expiryDays = Convert.ToDouble(configuration["JwtSettings:RefreshTokenExpiryDays"]);
// 保存到Redis,设置过期时间
var db = redis.GetDatabase();
var res = await db.StringSetAsync(refreshToken, userId, TimeSpan.FromDays(expiryDays));
var db = redis.GetDatabase(DbIndex);
var res = await db.StringSetAsync( userId , refreshToken, TimeSpan.FromDays(expiryDays));
if (!res)
{
throw new BaseException(1006, "Service unavailable");
}
return refreshToken;
}
public async Task DeleterRefreshTokenAsync(string refreshToken)
#endregion
#region
public async Task DeleterRefreshTokenAsync(string userId)
{
var db = redis.GetDatabase();
bool res = await db.KeyDeleteAsync(refreshToken);
var db = redis.GetDatabase(DbIndex);
bool res = await db.KeyDeleteAsync(userId);
if (!res)
{
throw new BaseException(1006, "Service unavailable");
}
}
public async Task UpdateRefreshTokenAsync(string refreshToken)
#endregion
#region
public async Task UpdateRefreshTokenAsync(string userId)
{
var db = redis.GetDatabase();
var db = redis.GetDatabase(DbIndex);
var expiryDays = Convert.ToDouble(configuration["JwtSettings:RefreshTokenExpiryDays"]);
//获取refresh剩余有效时间
var time =await db.KeyTimeToLiveAsync(refreshToken);
var time =await db.KeyTimeToLiveAsync(userId);
//判断有效时间是否大于零天小于三天,否则不刷新有效期
if(time <= TimeSpan.Zero || time >= TimeSpan.FromDays(3))
{
return;
}
//刷新过期时间
await db.KeyExpireAsync(refreshToken,TimeSpan.FromDays(expiryDays));
await db.KeyExpireAsync(userId,TimeSpan.FromDays(expiryDays));
}
public async Task<string?> ValidateRefreshTokenAsync(string refreshToken)
#endregion
#region
public async Task<bool> ValidateRefreshTokenAsync(string userId,string refreshToken)
{
var db = redis.GetDatabase();
var redisValue = await db.StringGetAsync(refreshToken);
var db = redis.GetDatabase(DbIndex);
var redisValue = await db.StringGetAsync(userId);
//验证refreshToken是否存在
if (!redisValue.HasValue)
{
return null;
return false;
}
return redisValue.ToString();
string refreshTokenTrue = redisValue.ToString();
if (!refreshToken.Equals(refreshTokenTrue))
{
return false;
}
return true;
}
#endregion
}
}
+59 -28
View File
@@ -3,9 +3,12 @@ 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
@@ -14,26 +17,18 @@ namespace Apimanager_backend.Services
{
private readonly ApiContext apiContext;
private readonly IMapper mapper;
public UserService(ApiContext apiContext,IMapper automapper)
private readonly ILogger<IUserService> logger;
private readonly IConnectionMultiplexer redis;
private readonly IEmailService emailService;
private readonly int DbSet = 2;
public UserService(ApiContext apiContext,IMapper automapper,ILogger<IUserService> logger,IConnectionMultiplexer redis,IEmailService emailService)
{
this.apiContext = apiContext;
this.mapper = automapper;
this.logger = logger;
this.redis = redis;
this.emailService = emailService;
}
public Task BanUserAsync(string username)
{
throw new NotImplementedException();
}
public Task<UserInfoDto> CreateUserAsync(CreateUserDto user)
{
throw new NotImplementedException();
}
public Task DeleteUserAsync(string username)
{
throw new NotImplementedException();
}
public async Task<UserInfoDto> GetUserAsync(int userId)
{
User? user = await apiContext.Users.SingleOrDefaultAsync(x => x.Id == userId);
@@ -45,30 +40,66 @@ namespace Apimanager_backend.Services
return mapper.Map<UserInfoDto>(user);
}
public Task<List<UserInfoDto>> GetUsersAsync(int page, int pageSize, bool desc)
public async Task<bool> IsEmailExist(string email)
{
throw new NotImplementedException();
return await apiContext.Users.AnyAsync(x => x.Email == email);
}
public Task ResetPasswordAsync(string email, string token, string newPassword)
public async Task<bool> IsUsernameExist(string username)
{
throw new NotImplementedException();
return await apiContext.Users.AnyAsync(x => x.Username == username);
}
public Task SendResetPasswordEmailAsync(string email)
public async Task ResetPasswordAsync(string email, string code, string newPassword)
{
throw new NotImplementedException();
//校验验证码
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();
}
public Task UnbanUserAsync(string username)
#region
public async Task SendResetPasswordEmailAsync(string email)
{
throw new NotImplementedException();
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}<br>有效期60分钟!";
//发送邮件
await emailService.SendEmailAsync(email,subject,body);
}
#endregion
public Task<UserInfoDto> UpdateUserAsync(UpdateUserDto user)
public async Task<UserInfoDto> UpdateUserAsync(int userId,UpdateUserDto dto)
{
throw new NotImplementedException();
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<UserInfoDto>(user);
}
}
}