using System.Security.Claims;
using ClassNotify.Server.Services;
using ClassNotify.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace ClassNotify.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("AuthLimiter")]
public class AuthController : ControllerBase
{
private readonly ISecurityService _securityService;
public AuthController(ISecurityService securityService)
{
_securityService = securityService;
}
///
/// 统一登录接口 (返回包含 Role / TenantId 的 JWT Token)
///
[HttpPost("login")]
public async Task Login([FromBody] TeacherLoginDto dto)
{
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var result = await _securityService.LoginTeacherAsync(dto, remoteIp);
if (!result.Success)
{
return Unauthorized(result);
}
return Ok(result);
}
///
/// 独立教师注册接口 (无需填写学校信息,自动开辟独立个人教学空间)
///
[HttpPost("register-personal")]
public async Task RegisterPersonal([FromBody] RegisterPersonalTeacherDto dto)
{
if (dto == null)
{
return BadRequest(new { success = false, message = "注册参数不可为空" });
}
if (string.IsNullOrWhiteSpace(dto.Username) || dto.Username.Trim().Length < 3 || dto.Username.Trim().Length > 64)
{
return BadRequest(new { success = false, message = "用户名长度必须在 3 至 64 个字符之间" });
}
if (string.IsNullOrWhiteSpace(dto.Password) || dto.Password.Length < 8 || dto.Password.Length > 128)
{
return BadRequest(new { success = false, message = "密码长度必须在 8 至 128 个字符之间" });
}
if (string.IsNullOrWhiteSpace(dto.FullName) || dto.FullName.Trim().Length < 2 || dto.FullName.Trim().Length > 50)
{
return BadRequest(new { success = false, message = "教师姓名或称谓长度必须在 2 至 50 个字符之间" });
}
if (!string.IsNullOrWhiteSpace(dto.PhoneNumber) && dto.PhoneNumber.Trim().Length > 20)
{
return BadRequest(new { success = false, message = "手机号码长度不能超过 20 位" });
}
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var result = await _securityService.RegisterPersonalTeacherAsync(dto, remoteIp);
if (!result.Success)
{
return BadRequest(result);
}
return Ok(result);
}
///
/// 获取当前登录用户画像与角色
///
[HttpGet("me")]
[Authorize]
public async Task GetMe()
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
var hasRecoveryKey = !string.IsNullOrEmpty(userId) && await _securityService.HasRecoveryKeyAsync(userId);
return Ok(new
{
userId,
name = User.FindFirst(ClaimTypes.Name)?.Value,
role = User.FindFirst(ClaimTypes.Role)?.Value,
tenantId = User.FindFirst("tenant_id")?.Value,
tenantType = User.FindFirst("tenant_type")?.Value ?? "School",
hasRecoveryKey
});
}
///
/// 登录用户验证当前密码后自主安全轮换恢复密钥(返回一次性明文,旧密钥失效)
///
[HttpPost("rotate-recovery-key")]
[Authorize]
public async Task RotateRecoveryKey([FromBody] RotateRecoveryKeyDto dto)
{
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId)) return Unauthorized();
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var (success, message, newKey) = await _securityService.RotateRecoveryKeyAsync(userId, dto?.CurrentPassword ?? string.Empty, remoteIp);
if (!success)
{
return BadRequest(new { success = false, message });
}
return Ok(new { success = true, message, recoveryKey = newKey });
}
///
/// 凭安全恢复密钥 (Recovery Key) 离线自救重置密码 (100% 零第三方成本,密钥用后即轮换)
///
[HttpPost("reset-password/recovery-key")]
public async Task ResetPasswordByRecoveryKey([FromBody] ResetPasswordByRecoveryKeyDto dto)
{
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var result = await _securityService.ResetPasswordByRecoveryKeyAsync(dto, remoteIp);
if (!result.Success)
{
return BadRequest(result);
}
return Ok(result);
}
///
/// 请求通过邮件链接重置密码 (15分钟有效,零成本邮件链接,防账号枚举)
///
[HttpPost("forgot-password")]
public async Task ForgotPassword([FromBody] RequestPasswordResetEmailDto dto)
{
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var (success, message) = await _securityService.RequestPasswordResetEmailAsync(dto, remoteIp);
return Ok(new { success, message });
}
///
/// 凭邮件链接 Token 或管理员签发的 Reset Ticket 重置密码
///
[HttpPost("reset-password/token")]
public async Task ResetPasswordByToken([FromBody] ResetPasswordByTokenDto dto)
{
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var (success, message) = await _securityService.ResetPasswordByTokenAsync(dto, remoteIp);
if (!success)
{
return BadRequest(new { success, message });
}
return Ok(new { success, message });
}
///
/// 用户自行修改/设置最终密码(支持临时密码首次登录设置最终密码)
///
[HttpPost("change-password")]
[Authorize]
public async Task ChangePassword([FromBody] ChangePasswordRequest req)
{
var userId = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userId)) return Unauthorized();
if (req == null || string.IsNullOrWhiteSpace(req.NewPassword))
{
return BadRequest(new { success = false, message = "新密码不可为空" });
}
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var (success, message, newToken) = await _securityService.ChangePasswordAsync(userId, req.NewPassword, User.Identity?.Name, remoteIp);
if (!success)
{
return BadRequest(new { success = false, message });
}
return Ok(new { success = true, message, token = newToken });
}
}
public class ChangePasswordRequest
{
public string NewPassword { get; set; } = string.Empty;
}