using F9WebAiTest.Application.Common; using F9WebAiTest.Application.Dtos; using F9WebAiTest.Application.Dtos.Auth; using F9WebAiTest.Application.Services; using F9WebAiTest.Application.Services.Auth; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace F9WebAiTest.Api.Controllers.Auth; [ApiController] [Route("api/auth")] public class AuthController : ControllerBase { private readonly IAuthService _authService; public AuthController(IAuthService authService) { _authService = authService; } [HttpPost("login")] public async Task Login([FromBody] LoginDto dto) { try { var result = await _authService.LoginAsync(dto); return Ok(ApiResult.Ok(result, "登录成功")); } catch (ServiceException ex) { return StatusCode(ex.Code, ApiResult.Fail(ex.Message, ex.Code)); } } [HttpPost("refresh")] public async Task Refresh([FromBody] RefreshTokenDto dto) { try { var result = await _authService.RefreshTokenAsync(dto.RefreshToken); return Ok(ApiResult.Ok(result, "刷新成功")); } catch (ServiceException ex) { return StatusCode(ex.Code, ApiResult.Fail(ex.Message, ex.Code)); } } [Authorize] [HttpPost("logout")] public async Task Logout([FromBody] RefreshTokenDto dto) { await _authService.RevokeRefreshTokenAsync(dto.RefreshToken); return Ok(ApiResult.Ok(null, "已退出登录")); } [Authorize] [HttpGet("me")] public async Task GetCurrentUser() { var id = GetUserId(); var user = await _authService.GetCurrentUserAsync(id); return Ok(ApiResult.Ok(user)); } [Authorize] [HttpGet("menus")] public async Task GetMenus() { var id = GetUserId(); var menus = await _authService.GetUserMenusAsync(id); return Ok(ApiResult>.Ok(menus)); } [Authorize] [HttpGet("permissions")] public async Task GetPermissions() { var id = GetUserId(); var perms = await _authService.GetUserPermissionsAsync(id); return Ok(ApiResult>.Ok(perms)); } [Authorize] [HttpPut("password")] public async Task ChangePassword([FromBody] ChangePasswordDto dto) { try { await _authService.ChangePasswordAsync(GetUserId(), dto); return Ok(ApiResult.Ok(null, "密码修改成功")); } catch (ServiceException ex) { return StatusCode(ex.Code, ApiResult.Fail(ex.Message, ex.Code)); } } [Authorize] [HttpPut("profile")] public async Task UpdateProfile([FromBody] UpdateProfileDto dto) { await _authService.UpdateProfileAsync(GetUserId(), dto); return Ok(ApiResult.Ok(null, "资料更新成功")); } private long GetUserId() => long.Parse(User.FindFirst("id")!.Value); }