113 lines
3.4 KiB
C#
113 lines
3.4 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using FutureMailAPI.Services;
|
|
using FutureMailAPI.DTOs;
|
|
|
|
namespace FutureMailAPI.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/v1/users")]
|
|
|
|
public class UsersController : BaseController
|
|
{
|
|
private readonly IUserService _userService;
|
|
private readonly ILogger<UsersController> _logger;
|
|
|
|
public UsersController(IUserService userService, ILogger<UsersController> logger)
|
|
{
|
|
_userService = userService;
|
|
_logger = logger;
|
|
}
|
|
|
|
[HttpGet("{id}")]
|
|
public async Task<IActionResult> GetUser(int id)
|
|
{
|
|
// 从JWT令牌中获取当前用户ID
|
|
var currentUserId = GetCurrentUserId();
|
|
|
|
if (currentUserId <= 0)
|
|
{
|
|
return Unauthorized(ApiResponse<UserResponseDto>.ErrorResult("未授权访问"));
|
|
}
|
|
|
|
// 只有用户本人可以查看自己的信息
|
|
if (currentUserId != id)
|
|
{
|
|
return Forbid();
|
|
}
|
|
|
|
var result = await _userService.GetUserByIdAsync(id);
|
|
|
|
if (!result.Success)
|
|
{
|
|
return NotFound(result);
|
|
}
|
|
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> UpdateUser(int id, [FromBody] UserUpdateDto updateDto)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return BadRequest(ApiResponse<UserResponseDto>.ErrorResult("输入数据无效"));
|
|
}
|
|
|
|
// 从JWT令牌中获取当前用户ID
|
|
var currentUserId = GetCurrentUserId();
|
|
|
|
if (currentUserId <= 0)
|
|
{
|
|
return Unauthorized(ApiResponse<UserResponseDto>.ErrorResult("未授权访问"));
|
|
}
|
|
|
|
// 只有用户本人可以更新自己的信息
|
|
if (currentUserId != id)
|
|
{
|
|
return Forbid();
|
|
}
|
|
|
|
var result = await _userService.UpdateUserAsync(id, updateDto);
|
|
|
|
if (!result.Success)
|
|
{
|
|
return BadRequest(result);
|
|
}
|
|
|
|
return Ok(result);
|
|
}
|
|
|
|
[HttpPost("{id}/change-password")]
|
|
public async Task<IActionResult> ChangePassword(int id, [FromBody] ChangePasswordDto changePasswordDto)
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return BadRequest(ApiResponse<bool>.ErrorResult("输入数据无效"));
|
|
}
|
|
|
|
// 从JWT令牌中获取当前用户ID
|
|
var currentUserId = GetCurrentUserId();
|
|
|
|
if (currentUserId <= 0)
|
|
{
|
|
return Unauthorized(ApiResponse<bool>.ErrorResult("未授权访问"));
|
|
}
|
|
|
|
// 只有用户本人可以修改自己的密码
|
|
if (currentUserId != id)
|
|
{
|
|
return Forbid();
|
|
}
|
|
|
|
var result = await _userService.ChangePasswordAsync(id, changePasswordDto);
|
|
|
|
if (!result.Success)
|
|
{
|
|
return BadRequest(result);
|
|
}
|
|
|
|
return Ok(result);
|
|
}
|
|
}
|
|
} |