修改接口
This commit is contained in:
		@@ -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;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user