You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
3.0 KiB

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MediatR;
using CellularManagement.Application.Features.Permissions.Commands.CreatePermission;
using CellularManagement.Application.Common;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using CellularManagement.Presentation.Abstractions;
using CellularManagement.Domain.Common;
namespace CellularManagement.Presentation.Controllers;
/// <summary>
/// 权限管理控制器
/// 提供权限管理相关的 API 接口,包括创建、删除和查询权限功能
/// </summary>
[Route("api/permissions")]
[ApiController]
[Authorize(Roles = "Admin")] // 只有管理员可以访问
public class PermissionsController : ApiController
{
private readonly ILogger<PermissionsController> _logger;
/// <summary>
/// 初始化权限控制器
/// </summary>
/// <param name="mediator">MediatR 中介者,用于处理命令和查询</param>
/// <param name="logger">日志记录器</param>
public PermissionsController(
IMediator mediator,
ILogger<PermissionsController> logger) : base(mediator)
{
_logger = logger;
}
/// <summary>
/// 创建新权限
/// </summary>
/// <remarks>
/// 示例请求:
///
/// POST /api/permissions/create
/// {
/// "name": "CreateUser",
/// "description": "创建用户的权限"
/// }
///
/// </remarks>
/// <param name="command">创建权限命令,包含权限名称和描述</param>
/// <returns>
/// 创建结果,包含:
/// - 成功:返回权限ID
/// - 失败:返回错误信息
/// </returns>
/// <response code="200">创建成功,返回权限ID</response>
/// <response code="400">创建失败,返回错误信息</response>
[HttpPost]
[ProducesResponseType(typeof(OperationResult<CreatePermissionResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(OperationResult<CreatePermissionResponse>), StatusCodes.Status400BadRequest)]
public async Task<ActionResult<OperationResult<CreatePermissionResponse>>> CreatePermission([FromBody] CreatePermissionCommand command)
{
try
{
var result = await mediator.Send(command);
if (result.IsSuccess)
{
_logger.LogInformation("权限 {PermissionName} 创建成功", command.Name);
}
else
{
_logger.LogWarning("权限 {PermissionName} 创建失败: {Error}",
command.Name,
result.ErrorMessages?.FirstOrDefault());
}
return Ok(result);
}
catch (Exception ex)
{
_logger.LogError(ex, "创建权限 {PermissionName} 时发生异常", command.Name);
return StatusCode(StatusCodes.Status500InternalServerError,
OperationResult<CreatePermissionResponse>.CreateFailure("系统错误,请稍后重试"));
}
}
}