Files
QYZH.InteractiveMagazine/QYZH.InteractiveMagazine.Service/AdminAuthService.cs
glz 831f8ba7f5 feat: 初始化后台管理模块与基础业务框架
1.  新增依赖注入生命周期标记接口、基础仓储与管理员仓储实现
2.  新增管理员认证与用户服务接口,补充认证相关DTO
3.  重构实体审计字段命名,统一Created/UpdatedAt规范
4.  新增大量业务实体类与API版本枚举配置
5.  集成Autofac依赖注入、JWT自动刷新与跨域配置
6.  替换原有微信小程序与旧认证服务为后台管理系统架构
7.  完善Swagger文档配置与项目基础部署配置
2026-06-01 17:59:23 +08:00

169 lines
5.9 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 BCrypt.Net;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using QYZH.InteractiveMagazine.Infrastructure.Auth;
using QYZH.InteractiveMagazine.Infrastructure.Cache;
using QYZH.InteractiveMagazine.IService;
using QYZH.InteractiveMagazine.IService.Dto;
using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Entity;
using QYZH.InteractiveMagazine.Models.Settings;
using QYZH.InteractiveMagazine.Repository;
namespace QYZH.InteractiveMagazine.Service;
public class AdminAuthService : IAdminAuthService
{
private readonly IAdminUserRepository _adminUserRepository;
private readonly IConfiguration _configuration;
private readonly ILogger<AdminAuthService> _logger;
private const string TokenKeyPrefix = "InteractiveMagazine:AdminAuth:Token";
private const string UserInfoKeyPrefix = "InteractiveMagazine:AdminAuth:UserInfo";
public AdminAuthService(IAdminUserRepository adminUserRepository, IConfiguration configuration, ILogger<AdminAuthService> logger)
{
_adminUserRepository = adminUserRepository;
_configuration = configuration;
_logger = logger;
}
public async Task<AdminLoginOutput> LoginAsync(AdminLoginInput input)
{
_logger.LogInformation("管理员登录尝试,用户名: {UserName}", input.UserName);
if (string.IsNullOrWhiteSpace(input.UserName))
{
throw new BusinessException("用户名不能为空", 400);
}
if (string.IsNullOrWhiteSpace(input.Password))
{
throw new BusinessException("密码不能为空", 400);
}
var adminUser = await _adminUserRepository.GetByUserNameAsync(input.UserName);
if (adminUser == null)
{
_logger.LogWarning("管理员登录失败,用户名不存在: {UserName}", input.UserName);
throw new BusinessException("用户名或密码错误", 401);
}
if (!BCrypt.Net.BCrypt.Verify(input.Password, adminUser.PasswordHash))
{
_logger.LogWarning("管理员登录失败,密码错误: {UserName}", input.UserName);
throw new BusinessException("用户名或密码错误", 401);
}
if (adminUser.Status != "Active")
{
_logger.LogWarning("管理员登录失败,账号已禁用: {UserName}", input.UserName);
throw new BusinessException("账号已被禁用,请联系系统管理员", 403);
}
var jwtSettings = GetJwtSettings();
var token = JwtHelper.GenerateToken((long)adminUser.Id, adminUser.UserName, jwtSettings);
await RedisHelper.StringSetAsync($"{TokenKeyPrefix}:{adminUser.Id}", token, TimeSpan.FromMinutes(jwtSettings.ExpiryMinutes));
_logger.LogInformation("管理员登录成功,用户名: {UserName}, ID: {UserId}", input.UserName, adminUser.Id);
return new AdminLoginOutput
{
Token = token,
UserId = (long)adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type
};
}
public async Task LogoutAsync(long userId)
{
_logger.LogInformation("管理员登出ID: {UserId}", userId);
await RedisHelper.KeyDeleteAsync($"{TokenKeyPrefix}:{userId}");
_logger.LogInformation("管理员登出成功ID: {UserId}", userId);
}
public async Task<AdminUserInfoOutput> GetAdminInfoAsync(long userId)
{
_logger.LogInformation("获取管理员信息ID: {UserId}", userId);
var adminUser = await _adminUserRepository.GetByIdAsync(userId);
if (adminUser == null)
{
_logger.LogWarning("未找到管理员ID: {UserId}", userId);
throw new BusinessException("用户不存在", 404);
}
return new AdminUserInfoOutput
{
UserId = adminUser.Id,
UserName = adminUser.UserName,
Type = adminUser.Type,
Status = adminUser.Status
};
}
public async Task ChangePasswordAsync(long userId, string oldPassword, string newPassword)
{
_logger.LogInformation("管理员修改密码尝试ID: {UserId}", userId);
if (string.IsNullOrWhiteSpace(oldPassword))
{
throw new BusinessException("原密码不能为空", 400);
}
if (string.IsNullOrWhiteSpace(newPassword))
{
throw new BusinessException("新密码不能为空", 400);
}
var adminUser = await _adminUserRepository.GetByIdAsync(userId);
if (adminUser == null)
{
_logger.LogWarning("未找到管理员ID: {UserId}", userId);
throw new BusinessException("用户不存在", 404);
}
if (!BCrypt.Net.BCrypt.Verify(oldPassword, adminUser.PasswordHash))
{
_logger.LogWarning("管理员修改密码失败原密码错误ID: {UserId}", userId);
throw new BusinessException("原密码错误", 400);
}
adminUser.PasswordHash = BCrypt.Net.BCrypt.HashPassword(newPassword);
var result = await _adminUserRepository.UpdateAsync(adminUser);
if (!result)
{
throw new BusinessException("修改密码失败", 500);
}
await RedisHelper.KeyDeleteAsync($"{TokenKeyPrefix}:{userId}");
_logger.LogInformation("管理员修改密码成功ID: {UserId}", userId);
}
private JwtSettings GetJwtSettings()
{
var jwtSettings = _configuration.GetSection("JwtSettings").Get<JwtSettings>()
?? new JwtSettings
{
Issuer = "QYZH.InteractiveMagazine",
Audience = "QYZH.InteractiveMagazine",
SecretKey = "your-256-bit-secret-key-here-change-in-production",
ExpiryMinutes = 120
};
if (string.IsNullOrWhiteSpace(jwtSettings.SecretKey))
{
throw new BusinessException("JWT 配置不完整", 500);
}
return jwtSettings;
}
}