修改接口
This commit is contained in:
@@ -7,8 +7,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/ai")]
|
||||
[Authorize]
|
||||
public class AIAssistantController : ControllerBase
|
||||
|
||||
public class AIAssistantController : BaseController
|
||||
{
|
||||
private readonly IAIAssistantService _aiAssistantService;
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("writing-assistant")]
|
||||
public async Task<ActionResult<ApiResponse<WritingAssistantResponseDto>>> GetWritingAssistance([FromBody] WritingAssistantRequestDto request)
|
||||
public async Task<IActionResult> GetWritingAssistance([FromBody] WritingAssistantRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -36,7 +36,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("sentiment-analysis")]
|
||||
public async Task<ActionResult<ApiResponse<SentimentAnalysisResponseDto>>> AnalyzeSentiment([FromBody] SentimentAnalysisRequestDto request)
|
||||
public async Task<IActionResult> AnalyzeSentiment([FromBody] SentimentAnalysisRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -54,7 +54,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("future-prediction")]
|
||||
public async Task<ActionResult<ApiResponse<FuturePredictionResponseDto>>> PredictFuture([FromBody] FuturePredictionRequestDto request)
|
||||
public async Task<IActionResult> PredictFuture([FromBody] FuturePredictionRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/ai")]
|
||||
[Authorize]
|
||||
public class AIController : ControllerBase
|
||||
|
||||
public class AIController : BaseController
|
||||
{
|
||||
private readonly IAIAssistantService _aiAssistantService;
|
||||
private readonly ILogger<AIController> _logger;
|
||||
@@ -26,7 +26,7 @@ namespace FutureMailAPI.Controllers
|
||||
/// <param name="request">写作辅助请求</param>
|
||||
/// <returns>AI生成的内容和建议</returns>
|
||||
[HttpPost("writing-assistant")]
|
||||
public async Task<ActionResult<ApiResponse<WritingAssistantResponseDto>>> WritingAssistant([FromBody] WritingAssistantRequestDto request)
|
||||
public async Task<IActionResult> WritingAssistant([FromBody] WritingAssistantRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -57,7 +57,7 @@ namespace FutureMailAPI.Controllers
|
||||
/// <param name="request">情感分析请求</param>
|
||||
/// <returns>情感分析结果</returns>
|
||||
[HttpPost("sentiment-analysis")]
|
||||
public async Task<ActionResult<ApiResponse<SentimentAnalysisResponseDto>>> SentimentAnalysis([FromBody] SentimentAnalysisRequestDto request)
|
||||
public async Task<IActionResult> SentimentAnalysis([FromBody] SentimentAnalysisRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -88,7 +88,7 @@ namespace FutureMailAPI.Controllers
|
||||
/// <param name="request">未来预测请求</param>
|
||||
/// <returns>未来预测结果</returns>
|
||||
[HttpPost("future-prediction")]
|
||||
public async Task<ActionResult<ApiResponse<FuturePredictionResponseDto>>> FuturePrediction([FromBody] FuturePredictionRequestDto request)
|
||||
public async Task<IActionResult> FuturePrediction([FromBody] FuturePredictionRequestDto request)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -112,19 +112,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<FuturePredictionResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +1,184 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using FutureMailAPI.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using FutureMailAPI.DTOs;
|
||||
using FutureMailAPI.Extensions;
|
||||
using FutureMailAPI.Services;
|
||||
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/auth")]
|
||||
public class AuthController : ControllerBase
|
||||
public class AuthController : BaseController
|
||||
{
|
||||
private readonly IAuthService _authService;
|
||||
private readonly IOAuthService _oauthService;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
|
||||
public AuthController(IAuthService authService, ILogger<AuthController> logger)
|
||||
|
||||
public AuthController(IAuthService authService, IOAuthService oauthService, ILogger<AuthController> logger)
|
||||
{
|
||||
_authService = authService;
|
||||
_oauthService = oauthService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("register")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<ApiResponse<AuthResponseDto>>> Register([FromBody] UserRegisterDto registerDto)
|
||||
public async Task<IActionResult> Register([FromBody] UserRegisterDto registerDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ApiResponse<AuthResponseDto>.ErrorResult("输入数据无效"));
|
||||
}
|
||||
|
||||
var result = await _authService.RegisterAsync(registerDto);
|
||||
|
||||
if (!result.Success)
|
||||
try
|
||||
{
|
||||
var result = await _authService.RegisterAsync(registerDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "用户注册时发生错误");
|
||||
return StatusCode(500, ApiResponse<UserResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<ApiResponse<AuthResponseDto>>> Login([FromBody] UserLoginDto loginDto)
|
||||
public async Task<IActionResult> Login([FromBody] UserLoginDto loginDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ApiResponse<AuthResponseDto>.ErrorResult("输入数据无效"));
|
||||
}
|
||||
|
||||
var result = await _authService.LoginAsync(loginDto);
|
||||
|
||||
if (!result.Success)
|
||||
try
|
||||
{
|
||||
var result = await _authService.LoginAsync(loginDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "用户登录时发生错误");
|
||||
return StatusCode(500, ApiResponse<UserResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("logout")]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取当前令牌
|
||||
var authHeader = Request.Headers.Authorization.FirstOrDefault();
|
||||
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
|
||||
{
|
||||
return BadRequest(new { message = "缺少授权令牌" });
|
||||
}
|
||||
|
||||
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||||
|
||||
// 撤销令牌
|
||||
await _oauthService.RevokeTokenAsync(token);
|
||||
|
||||
return Ok(new { message = "退出登录成功" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "用户退出登录时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("token")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> GetToken([FromBody] OAuthLoginRequestDto request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _oauthService.LoginAsync(request);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "OAuth令牌获取时发生错误");
|
||||
return StatusCode(500, ApiResponse<OAuthTokenResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<ApiResponse<AuthResponseDto>>> RefreshToken([FromBody] RefreshTokenRequestDto request)
|
||||
public async Task<IActionResult> RefreshToken([FromBody] OAuthRefreshTokenRequestDto request)
|
||||
{
|
||||
if (request == null || string.IsNullOrEmpty(request.Token))
|
||||
try
|
||||
{
|
||||
return BadRequest(ApiResponse<AuthResponseDto>.ErrorResult("令牌不能为空"));
|
||||
var result = await _oauthService.RefreshTokenAsync(request);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
|
||||
// 使用OAuth刷新令牌
|
||||
var tokenResult = await _authService.RefreshTokenAsync(request.Token);
|
||||
|
||||
if (!tokenResult.Success)
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(ApiResponse<AuthResponseDto>.ErrorResult(tokenResult.Message));
|
||||
_logger.LogError(ex, "OAuth令牌刷新时发生错误");
|
||||
return StatusCode(500, ApiResponse<OAuthTokenResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
|
||||
// 创建认证响应DTO
|
||||
var authResponse = new AuthResponseDto
|
||||
{
|
||||
Token = tokenResult.Data,
|
||||
Expires = DateTime.UtcNow.AddHours(1) // OAuth访问令牌默认1小时过期
|
||||
};
|
||||
|
||||
return Ok(ApiResponse<AuthResponseDto>.SuccessResult(authResponse, "令牌刷新成功"));
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> Logout()
|
||||
|
||||
[HttpPost("revoke")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> RevokeToken([FromBody] string accessToken)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
try
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
var result = await _oauthService.RevokeTokenAsync(accessToken);
|
||||
|
||||
if (result)
|
||||
{
|
||||
return Ok(new { message = "令牌已成功撤销" });
|
||||
}
|
||||
|
||||
return BadRequest(new { message = "无效的令牌" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "OAuth令牌撤销时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
|
||||
// 这里可以实现令牌黑名单或其他注销逻辑
|
||||
// 目前只返回成功响应
|
||||
return Ok(ApiResponse<bool>.SuccessResult(true));
|
||||
}
|
||||
|
||||
private int? GetCurrentUserId()
|
||||
|
||||
[HttpGet("userinfo")]
|
||||
public async Task<IActionResult> GetUserInfo()
|
||||
{
|
||||
// 从OAuth中间件获取用户ID
|
||||
var userId = HttpContext.GetCurrentUserId();
|
||||
if (userId.HasValue)
|
||||
try
|
||||
{
|
||||
return userId.Value;
|
||||
var userId = GetCurrentUserId();
|
||||
var userEmail = GetCurrentUserEmail();
|
||||
var username = GetCurrentUsername();
|
||||
var clientId = GetCurrentClientId();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
userId,
|
||||
username,
|
||||
email = userEmail,
|
||||
clientId
|
||||
});
|
||||
}
|
||||
|
||||
// 兼容旧的JWT方式
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var jwtUserId))
|
||||
catch (Exception ex)
|
||||
{
|
||||
return null;
|
||||
_logger.LogError(ex, "获取用户信息时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
|
||||
return jwtUserId;
|
||||
}
|
||||
}
|
||||
}
|
||||
54
FutureMailAPI/Controllers/BaseController.cs
Normal file
54
FutureMailAPI/Controllers/BaseController.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// 基础控制器,提供通用的用户身份验证方法
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
public class BaseController : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前用户ID
|
||||
/// 兼容OAuth中间件和JWT令牌两种验证方式
|
||||
/// </summary>
|
||||
/// <returns>用户ID,如果未认证则返回0</returns>
|
||||
protected int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户邮箱
|
||||
/// </summary>
|
||||
/// <returns>用户邮箱,如果未认证则返回空字符串</returns>
|
||||
protected string GetCurrentUserEmail()
|
||||
{
|
||||
return User.FindFirst(ClaimTypes.Email)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户名
|
||||
/// </summary>
|
||||
/// <returns>用户名,如果未认证则返回空字符串</returns>
|
||||
protected string GetCurrentUsername()
|
||||
{
|
||||
return User.FindFirst(ClaimTypes.Name)?.Value ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前客户端ID
|
||||
/// </summary>
|
||||
/// <returns>客户端ID,如果未认证则返回空字符串</returns>
|
||||
protected string GetCurrentClientId()
|
||||
{
|
||||
return User.FindFirst("client_id")?.Value ?? string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,9 @@ using FutureMailAPI.DTOs;
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/capsules")]
|
||||
[Authorize]
|
||||
public class CapsulesController : ControllerBase
|
||||
[Route("api/v1/[controller]")]
|
||||
|
||||
public class CapsulesController : BaseController
|
||||
{
|
||||
private readonly ITimeCapsuleService _timeCapsuleService;
|
||||
private readonly ILogger<CapsulesController> _logger;
|
||||
@@ -20,17 +20,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleViewResponseDto>>> GetCapsules()
|
||||
public async Task<IActionResult> GetCapsules()
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleViewResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleViewAsync(currentUserId.Value);
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleViewAsync(currentUserId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -41,7 +41,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPut("{capsuleId}/style")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> UpdateCapsuleStyle(int capsuleId, [FromBody] TimeCapsuleStyleUpdateDto updateDto)
|
||||
public async Task<IActionResult> UpdateCapsuleStyle(int capsuleId, [FromBody] TimeCapsuleStyleUpdateDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -51,12 +51,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleStyleAsync(currentUserId.Value, capsuleId, updateDto);
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleStyleAsync(currentUserId, capsuleId, updateDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -65,17 +65,5 @@ namespace FutureMailAPI.Controllers
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")]
|
||||
[Authorize]
|
||||
public class FileUploadController : ControllerBase
|
||||
|
||||
public class FileUploadController : BaseController
|
||||
{
|
||||
private readonly IFileUploadService _fileUploadService;
|
||||
private readonly ILogger<FileUploadController> _logger;
|
||||
@@ -171,19 +171,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<FileUploadResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从当前请求中获取用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,25 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using FutureMailAPI.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using FutureMailAPI.DTOs;
|
||||
using System.Security.Claims;
|
||||
using FutureMailAPI.Services;
|
||||
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")]
|
||||
[Authorize]
|
||||
public class MailsController : ControllerBase
|
||||
[Route("api/v1/mails")]
|
||||
public class MailsController : BaseController
|
||||
{
|
||||
private readonly IMailService _mailService;
|
||||
|
||||
public MailsController(IMailService mailService)
|
||||
private readonly ILogger<MailsController> _logger;
|
||||
|
||||
public MailsController(IMailService mailService, ILogger<MailsController> logger)
|
||||
{
|
||||
_mailService = mailService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ApiResponse<SentMailResponseDto>>> CreateMail([FromBody] SentMailCreateDto createDto)
|
||||
public async Task<IActionResult> CreateMail([FromBody] SentMailCreateDto createDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -29,12 +29,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.CreateMailAsync(currentUserId.Value, createDto);
|
||||
var result = await _mailService.CreateMailAsync(currentUserId, createDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -48,17 +48,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("{mailId}")]
|
||||
public async Task<ActionResult<ApiResponse<SentMailResponseDto>>> GetMail(int mailId)
|
||||
public async Task<IActionResult> GetMail(int mailId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.GetSentMailByIdAsync(currentUserId.Value, mailId);
|
||||
var result = await _mailService.GetSentMailByIdAsync(currentUserId, mailId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -69,23 +69,36 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<ApiResponse<PagedResponse<SentMailResponseDto>>>> GetMails([FromQuery] MailListQueryDto queryDto)
|
||||
public async Task<IActionResult> GetMails([FromQuery] MailListQueryDto queryDto)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
try
|
||||
{
|
||||
return Unauthorized(ApiResponse<PagedResponse<SentMailResponseDto>>.ErrorResult("未授权访问"));
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<PagedResponse<SentMailResponseDto>>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.GetSentMailsAsync(currentUserId, queryDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "获取邮件列表时发生错误");
|
||||
return StatusCode(500, ApiResponse<PagedResponse<SentMailResponseDto>>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
|
||||
var result = await _mailService.GetSentMailsAsync(currentUserId.Value, queryDto);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{mailId}")]
|
||||
public async Task<ActionResult<ApiResponse<SentMailResponseDto>>> UpdateMail(int mailId, [FromBody] SentMailUpdateDto updateDto)
|
||||
public async Task<IActionResult> UpdateMail(int mailId, [FromBody] SentMailUpdateDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -95,12 +108,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<SentMailResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.UpdateMailAsync(currentUserId.Value, mailId, updateDto);
|
||||
var result = await _mailService.UpdateMailAsync(currentUserId, mailId, updateDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -111,17 +124,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete("{mailId}")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> DeleteMail(int mailId)
|
||||
public async Task<IActionResult> DeleteMail(int mailId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.DeleteMailAsync(currentUserId.Value, mailId);
|
||||
var result = await _mailService.DeleteMailAsync(currentUserId, mailId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -132,33 +145,33 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("received")]
|
||||
public async Task<ActionResult<ApiResponse<PagedResponse<ReceivedMailResponseDto>>>> GetReceivedMails([FromQuery] MailListQueryDto queryDto)
|
||||
public async Task<IActionResult> GetReceivedMails([FromQuery] MailListQueryDto queryDto)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<PagedResponse<ReceivedMailResponseDto>>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.GetReceivedMailsAsync(currentUserId.Value, queryDto);
|
||||
var result = await _mailService.GetReceivedMailsAsync(currentUserId, queryDto);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("received/{id}")]
|
||||
public async Task<ActionResult<ApiResponse<ReceivedMailResponseDto>>> GetReceivedMail(int id)
|
||||
public async Task<IActionResult> GetReceivedMail(int id)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<ReceivedMailResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.GetReceivedMailByIdAsync(currentUserId.Value, id);
|
||||
var result = await _mailService.GetReceivedMailByIdAsync(currentUserId, id);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -169,17 +182,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("received/{id}/mark-read")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> MarkReceivedMailAsRead(int id)
|
||||
public async Task<IActionResult> MarkReceivedMailAsRead(int id)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.MarkReceivedMailAsReadAsync(currentUserId.Value, id);
|
||||
var result = await _mailService.MarkReceivedMailAsReadAsync(currentUserId, id);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -190,17 +203,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("{mailId}/revoke")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> RevokeMail(int mailId)
|
||||
public async Task<IActionResult> RevokeMail(int mailId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _mailService.RevokeMailAsync(currentUserId.Value, mailId);
|
||||
var result = await _mailService.RevokeMailAsync(currentUserId, mailId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -209,17 +222,5 @@ namespace FutureMailAPI.Controllers
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/notification")]
|
||||
[Authorize]
|
||||
public class NotificationController : ControllerBase
|
||||
|
||||
public class NotificationController : BaseController
|
||||
{
|
||||
private readonly INotificationService _notificationService;
|
||||
private readonly ILogger<NotificationController> _logger;
|
||||
@@ -87,19 +87,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<NotificationSettingsDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,295 +0,0 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using FutureMailAPI.Services;
|
||||
using FutureMailAPI.DTOs;
|
||||
using FutureMailAPI.Models;
|
||||
using FutureMailAPI.Extensions;
|
||||
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/oauth")]
|
||||
public class OAuthController : ControllerBase
|
||||
{
|
||||
private readonly IOAuthService _oauthService;
|
||||
private readonly ILogger<OAuthController> _logger;
|
||||
|
||||
public OAuthController(IOAuthService oauthService, ILogger<OAuthController> logger)
|
||||
{
|
||||
_oauthService = oauthService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OAuth登录端点
|
||||
/// </summary>
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] OAuthLoginDto loginDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _oauthService.LoginAsync(loginDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "OAuth登录时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建OAuth客户端
|
||||
/// </summary>
|
||||
[HttpPost("clients")]
|
||||
public async Task<IActionResult> CreateClient([FromBody] OAuthClientCreateDto createDto)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 从OAuth中间件获取当前用户ID
|
||||
var userId = HttpContext.GetCurrentUserId();
|
||||
if (!userId.HasValue)
|
||||
{
|
||||
return Unauthorized(new { message = "未授权访问" });
|
||||
}
|
||||
|
||||
var result = await _oauthService.CreateClientAsync(userId.Value, createDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "创建OAuth客户端时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取OAuth客户端信息
|
||||
/// </summary>
|
||||
[HttpGet("clients/{clientId}")]
|
||||
public async Task<IActionResult> GetClient(string clientId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _oauthService.GetClientAsync(clientId);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return NotFound(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "获取OAuth客户端信息时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OAuth授权端点
|
||||
/// </summary>
|
||||
[HttpGet("authorize")]
|
||||
public async Task<IActionResult> Authorize([FromQuery] OAuthAuthorizationRequestDto request)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 从OAuth中间件获取当前用户ID
|
||||
var userId = HttpContext.GetCurrentUserId();
|
||||
if (!userId.HasValue)
|
||||
{
|
||||
// 如果用户未登录,重定向到登录页面
|
||||
var loginRedirectUri = $"/api/v1/auth/login?redirect_uri={Uri.EscapeDataString(request.RedirectUri)}";
|
||||
if (!string.IsNullOrEmpty(request.State))
|
||||
{
|
||||
loginRedirectUri += $"&state={request.State}";
|
||||
}
|
||||
return Redirect(loginRedirectUri);
|
||||
}
|
||||
|
||||
var result = await _oauthService.AuthorizeAsync(userId.Value, request);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
// 重定向到客户端,携带授权码
|
||||
var redirectUri = $"{request.RedirectUri}?code={result.Data.Code}";
|
||||
if (!string.IsNullOrEmpty(request.State))
|
||||
{
|
||||
redirectUri += $"&state={request.State}";
|
||||
}
|
||||
|
||||
return Redirect(redirectUri);
|
||||
}
|
||||
|
||||
// 错误重定向
|
||||
var errorRedirectUri = $"{request.RedirectUri}?error={result.Message}";
|
||||
if (!string.IsNullOrEmpty(request.State))
|
||||
{
|
||||
errorRedirectUri += $"&state={request.State}";
|
||||
}
|
||||
|
||||
return Redirect(errorRedirectUri);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "OAuth授权时发生错误");
|
||||
|
||||
// 错误重定向
|
||||
var errorRedirectUri = $"{request.RedirectUri}?error=server_error";
|
||||
if (!string.IsNullOrEmpty(request.State))
|
||||
{
|
||||
errorRedirectUri += $"&state={request.State}";
|
||||
}
|
||||
|
||||
return Redirect(errorRedirectUri);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OAuth令牌端点
|
||||
/// </summary>
|
||||
[HttpPost("token")]
|
||||
[Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
||||
public async Task<IActionResult> ExchangeToken([FromForm] OAuthTokenRequestDto request)
|
||||
{
|
||||
_logger.LogInformation("OAuth令牌端点被调用");
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("OAuth令牌交换请求: GrantType={GrantType}, ClientId={ClientId}, Username={Username}",
|
||||
request.GrantType, request.ClientId, request.Username);
|
||||
|
||||
if (request.GrantType == "authorization_code")
|
||||
{
|
||||
var result = await _oauthService.ExchangeCodeForTokenAsync(request);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
else if (request.GrantType == "refresh_token")
|
||||
{
|
||||
var result = await _oauthService.RefreshTokenAsync(request);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
else if (request.GrantType == "password")
|
||||
{
|
||||
_logger.LogInformation("处理密码授权类型登录请求");
|
||||
|
||||
// 创建OAuth登录请求
|
||||
var loginDto = new OAuthLoginDto
|
||||
{
|
||||
UsernameOrEmail = request.Username,
|
||||
Password = request.Password,
|
||||
ClientId = request.ClientId,
|
||||
ClientSecret = request.ClientSecret,
|
||||
Scope = request.Scope
|
||||
};
|
||||
|
||||
var result = await _oauthService.LoginAsync(loginDto);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
_logger.LogInformation("密码授权类型登录成功");
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
_logger.LogWarning("密码授权类型登录失败: {Message}", result.Message);
|
||||
return BadRequest(result);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("不支持的授权类型: {GrantType}", request.GrantType);
|
||||
return BadRequest(new { message = "不支持的授权类型" });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "OAuth令牌交换时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 撤销令牌
|
||||
/// </summary>
|
||||
[HttpPost("revoke")]
|
||||
public async Task<IActionResult> RevokeToken([FromForm] string token, [FromForm] string token_type_hint = "access_token")
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _oauthService.RevokeTokenAsync(token);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
return Ok(new { message = "令牌已撤销" });
|
||||
}
|
||||
|
||||
return BadRequest(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "撤销令牌时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证令牌
|
||||
/// </summary>
|
||||
[HttpPost("introspect")]
|
||||
public async Task<IActionResult> IntrospectToken([FromForm] string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _oauthService.ValidateTokenAsync(token);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
var accessToken = await _oauthService.GetAccessTokenAsync(token);
|
||||
|
||||
if (accessToken != null)
|
||||
{
|
||||
return Ok(new
|
||||
{
|
||||
active = true,
|
||||
scope = accessToken.Scopes,
|
||||
client_id = accessToken.Client.ClientId,
|
||||
username = accessToken.User.Email,
|
||||
exp = ((DateTimeOffset)accessToken.ExpiresAt).ToUnixTimeSeconds(),
|
||||
iat = ((DateTimeOffset)accessToken.CreatedAt).ToUnixTimeSeconds()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(new { active = false });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "验证令牌时发生错误");
|
||||
return StatusCode(500, new { message = "服务器内部错误" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")]
|
||||
[Authorize]
|
||||
public class PersonalSpaceController : ControllerBase
|
||||
|
||||
public class PersonalSpaceController : BaseController
|
||||
{
|
||||
private readonly IPersonalSpaceService _personalSpaceService;
|
||||
private readonly ILogger<PersonalSpaceController> _logger;
|
||||
@@ -156,19 +156,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<UserProfileResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从当前请求中获取用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/statistics")]
|
||||
[Authorize]
|
||||
public class StatisticsController : ControllerBase
|
||||
|
||||
public class StatisticsController : BaseController
|
||||
{
|
||||
private readonly IPersonalSpaceService _personalSpaceService;
|
||||
private readonly ILogger<StatisticsController> _logger;
|
||||
@@ -50,19 +50,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<StatisticsResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
77
FutureMailAPI/Controllers/TempFixController.cs
Normal file
77
FutureMailAPI/Controllers/TempFixController.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using FutureMailAPI.Data;
|
||||
using FutureMailAPI.Models;
|
||||
using FutureMailAPI.Helpers;
|
||||
|
||||
namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/temp-fix")]
|
||||
public class TempFixController : ControllerBase
|
||||
{
|
||||
private readonly FutureMailDbContext _context;
|
||||
private readonly IPasswordHelper _passwordHelper;
|
||||
|
||||
public TempFixController(FutureMailDbContext context, IPasswordHelper passwordHelper)
|
||||
{
|
||||
_context = context;
|
||||
_passwordHelper = passwordHelper;
|
||||
}
|
||||
|
||||
[HttpPost("fix-passwords")]
|
||||
public async Task<IActionResult> FixPasswordHashes()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取所有用户
|
||||
var users = await _context.Users.ToListAsync();
|
||||
int fixedCount = 0;
|
||||
|
||||
foreach (var user in users)
|
||||
{
|
||||
// 如果salt为空但passwordHash有值,说明需要修复
|
||||
if (string.IsNullOrEmpty(user.Salt) && !string.IsNullOrEmpty(user.PasswordHash))
|
||||
{
|
||||
// 使用默认密码重新设置密码哈希
|
||||
var newPasswordHash = _passwordHelper.HashPassword("password123");
|
||||
user.PasswordHash = newPasswordHash;
|
||||
user.Salt = _passwordHelper.GenerateSalt();
|
||||
fixedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(new {
|
||||
success = true,
|
||||
message = $"已修复 {fixedCount} 个用户的密码哈希",
|
||||
fixedUsers = fixedCount
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(new {
|
||||
success = false,
|
||||
message = $"修复失败: {ex.Message}"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("users")]
|
||||
public async Task<IActionResult> GetUsers()
|
||||
{
|
||||
var users = await _context.Users
|
||||
.Select(u => new {
|
||||
u.Id,
|
||||
u.Username,
|
||||
u.Email,
|
||||
PasswordHashLength = u.PasswordHash.Length,
|
||||
HasSalt = !string.IsNullOrEmpty(u.Salt)
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(users);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/[controller]")]
|
||||
[Authorize]
|
||||
public class TimeCapsulesController : ControllerBase
|
||||
|
||||
public class TimeCapsulesController : BaseController
|
||||
{
|
||||
private readonly ITimeCapsuleService _timeCapsuleService;
|
||||
private readonly ILogger<TimeCapsulesController> _logger;
|
||||
@@ -20,7 +20,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> CreateTimeCapsule([FromBody] TimeCapsuleCreateDto createDto)
|
||||
public async Task<IActionResult> CreateTimeCapsule([FromBody] TimeCapsuleCreateDto createDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -30,12 +30,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.CreateTimeCapsuleAsync(currentUserId.Value, createDto);
|
||||
var result = await _timeCapsuleService.CreateTimeCapsuleAsync(currentUserId, createDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -49,17 +49,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("{capsuleId}")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> GetTimeCapsule(int capsuleId)
|
||||
public async Task<IActionResult> GetTimeCapsule(int capsuleId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleByIdAsync(currentUserId.Value, capsuleId);
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleByIdAsync(currentUserId, capsuleId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -70,23 +70,23 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<ApiResponse<PagedResponse<TimeCapsuleResponseDto>>>> GetTimeCapsules([FromQuery] TimeCapsuleListQueryDto queryDto)
|
||||
public async Task<IActionResult> GetTimeCapsules([FromQuery] TimeCapsuleListQueryDto queryDto)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<PagedResponse<TimeCapsuleResponseDto>>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.GetTimeCapsulesAsync(currentUserId.Value, queryDto);
|
||||
var result = await _timeCapsuleService.GetTimeCapsulesAsync(currentUserId, queryDto);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{capsuleId}")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> UpdateTimeCapsule(int capsuleId, [FromBody] TimeCapsuleUpdateDto updateDto)
|
||||
public async Task<IActionResult> UpdateTimeCapsule(int capsuleId, [FromBody] TimeCapsuleUpdateDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -96,12 +96,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleAsync(currentUserId.Value, capsuleId, updateDto);
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleAsync(currentUserId, capsuleId, updateDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -112,17 +112,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete("{capsuleId}")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> DeleteTimeCapsule(int capsuleId)
|
||||
public async Task<IActionResult> DeleteTimeCapsule(int capsuleId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.DeleteTimeCapsuleAsync(currentUserId.Value, capsuleId);
|
||||
var result = await _timeCapsuleService.DeleteTimeCapsuleAsync(currentUserId, capsuleId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -134,7 +134,7 @@ namespace FutureMailAPI.Controllers
|
||||
|
||||
[HttpGet("public")]
|
||||
[AllowAnonymous]
|
||||
public async Task<ActionResult<ApiResponse<PagedResponse<TimeCapsuleResponseDto>>>> GetPublicTimeCapsules([FromQuery] TimeCapsuleListQueryDto queryDto)
|
||||
public async Task<IActionResult> GetPublicTimeCapsules([FromQuery] TimeCapsuleListQueryDto queryDto)
|
||||
{
|
||||
var result = await _timeCapsuleService.GetPublicTimeCapsulesAsync(queryDto);
|
||||
|
||||
@@ -142,17 +142,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("public/{capsuleId}/claim")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> ClaimPublicCapsule(int capsuleId)
|
||||
public async Task<IActionResult> ClaimPublicCapsule(int capsuleId)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.ClaimPublicCapsuleAsync(currentUserId.Value, capsuleId);
|
||||
var result = await _timeCapsuleService.ClaimPublicCapsuleAsync(currentUserId, capsuleId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -163,17 +163,17 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("view")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleViewResponseDto>>> GetTimeCapsuleView()
|
||||
public async Task<IActionResult> GetTimeCapsuleView()
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleViewResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleViewAsync(currentUserId.Value);
|
||||
var result = await _timeCapsuleService.GetTimeCapsuleViewAsync(currentUserId);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -184,7 +184,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPut("{capsuleId}/style")]
|
||||
public async Task<ActionResult<ApiResponse<TimeCapsuleResponseDto>>> UpdateTimeCapsuleStyle(int capsuleId, [FromBody] TimeCapsuleStyleUpdateDto updateDto)
|
||||
public async Task<IActionResult> UpdateTimeCapsuleStyle(int capsuleId, [FromBody] TimeCapsuleStyleUpdateDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -194,12 +194,12 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<TimeCapsuleResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleStyleAsync(currentUserId.Value, capsuleId, updateDto);
|
||||
var result = await _timeCapsuleService.UpdateTimeCapsuleStyleAsync(currentUserId, capsuleId, updateDto);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
@@ -209,16 +209,5 @@ namespace FutureMailAPI.Controllers
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/timeline")]
|
||||
[Authorize]
|
||||
public class TimelineController : ControllerBase
|
||||
|
||||
public class TimelineController : BaseController
|
||||
{
|
||||
private readonly IPersonalSpaceService _personalSpaceService;
|
||||
private readonly ILogger<TimelineController> _logger;
|
||||
@@ -63,19 +63,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<TimelineResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/upload")]
|
||||
[Authorize]
|
||||
public class UploadController : ControllerBase
|
||||
|
||||
public class UploadController : BaseController
|
||||
{
|
||||
private readonly IFileUploadService _fileUploadService;
|
||||
private readonly ILogger<UploadController> _logger;
|
||||
@@ -97,19 +97,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<FileUploadResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/user")]
|
||||
[Authorize]
|
||||
public class UserController : ControllerBase
|
||||
|
||||
public class UserController : BaseController
|
||||
{
|
||||
private readonly IPersonalSpaceService _personalSpaceService;
|
||||
private readonly ILogger<UserController> _logger;
|
||||
@@ -81,19 +81,5 @@ namespace FutureMailAPI.Controllers
|
||||
return StatusCode(500, ApiResponse<UserProfileResponseDto>.ErrorResult("服务器内部错误"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从JWT令牌中获取当前用户ID
|
||||
/// </summary>
|
||||
/// <returns>用户ID</returns>
|
||||
private int GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace FutureMailAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/v1/users")]
|
||||
[Authorize]
|
||||
public class UsersController : ControllerBase
|
||||
|
||||
public class UsersController : BaseController
|
||||
{
|
||||
private readonly IUserService _userService;
|
||||
private readonly ILogger<UsersController> _logger;
|
||||
@@ -20,12 +20,12 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
public async Task<ActionResult<ApiResponse<UserResponseDto>>> GetUser(int id)
|
||||
public async Task<IActionResult> GetUser(int id)
|
||||
{
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<UserResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
@@ -47,7 +47,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPut("{id}")]
|
||||
public async Task<ActionResult<ApiResponse<UserResponseDto>>> UpdateUser(int id, [FromBody] UserUpdateDto updateDto)
|
||||
public async Task<IActionResult> UpdateUser(int id, [FromBody] UserUpdateDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -57,7 +57,7 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<UserResponseDto>.ErrorResult("未授权访问"));
|
||||
}
|
||||
@@ -79,7 +79,7 @@ namespace FutureMailAPI.Controllers
|
||||
}
|
||||
|
||||
[HttpPost("{id}/change-password")]
|
||||
public async Task<ActionResult<ApiResponse<bool>>> ChangePassword(int id, [FromBody] ChangePasswordDto changePasswordDto)
|
||||
public async Task<IActionResult> ChangePassword(int id, [FromBody] ChangePasswordDto changePasswordDto)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
@@ -89,7 +89,7 @@ namespace FutureMailAPI.Controllers
|
||||
// 从JWT令牌中获取当前用户ID
|
||||
var currentUserId = GetCurrentUserId();
|
||||
|
||||
if (currentUserId == null)
|
||||
if (currentUserId <= 0)
|
||||
{
|
||||
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
||||
}
|
||||
@@ -109,17 +109,5 @@ namespace FutureMailAPI.Controllers
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
|
||||
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user