using System.Security.Claims; using ClassNotify.Server.Hubs; using ClassNotify.Server.Services; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace ClassNotify.Server.Controllers; [ApiController] [Route("api/[controller]")] [Authorize(Roles = "Teacher,TenantOwner")] public class TeacherController : ControllerBase { private readonly ISecurityService _securityService; private readonly ILogger _logger; public TeacherController(ISecurityService securityService, ILogger logger) { _securityService = securityService; _logger = logger; } /// /// 获取当前登录教师名下的激活码列表(待使用/已使用及绑定班级,严格按 JWT 提取的用户 ID 隔离,凭证明文已掩码防批量泄漏) /// [HttpGet("activation-codes")] public async Task GetMyActivationCodes() { var tenantId = User.FindFirst("tenant_id")?.Value; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(userId)) { return Unauthorized(new { success = false, message = "未发现合法的用户凭据或租户信息" }); } var codes = await _securityService.GetTeacherActivationCodesAsync(tenantId, userId); Response.Headers.CacheControl = "no-store"; return Ok(codes); } /// /// 教师显式查看或复制激活码明文(按需解密,记录安全暴露审计 SecretExposedAtUtc,防批量泄密,仅允许凭证不透明 Id) /// [HttpPost("activation-codes/{id}/reveal")] public async Task RevealActivationCode(string id) { var tenantId = User.FindFirst("tenant_id")?.Value; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var username = User.FindFirst(ClaimTypes.Name)?.Value ?? userId; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(userId)) { return Unauthorized(new { success = false, message = "未发现合法的用户凭据或租户信息" }); } if (string.IsNullOrWhiteSpace(id)) { return BadRequest(new { success = false, message = "凭证标识符不能为空" }); } try { var rawCode = await _securityService.RevealTeacherActivationCodeAsync(tenantId, userId, id, username, ip); return Ok(new { success = true, code = rawCode, revealedAt = DateTimeOffset.UtcNow }); } catch (KeyNotFoundException ex) { return NotFound(new { success = false, message = ex.Message }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (Exception ex) { _logger.LogError(ex, "Failed to reveal activation code for teacher {UserId}", userId); return StatusCode(500, new { success = false, message = "查看激活码发生异常" }); } } /// /// 教师或个人空间拥有者通过商业卡密/激活码为其名下的大屏设备自主续期 /// [HttpPost("devices/{deviceId}/renew")] public async Task RenewMyDeviceLicense( string deviceId, [FromBody] RenewDeviceLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var tenantId = User.FindFirst("tenant_id")?.Value; var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(userId)) { return Unauthorized(new { success = false, message = "未发现合法的用户凭据或租户信息" }); } if (string.IsNullOrWhiteSpace(deviceId)) { return BadRequest(new { success = false, message = "设备标识符不可为空" }); } if (string.IsNullOrWhiteSpace(dto?.ActivationCode)) { return BadRequest(new { success = false, message = "请输入有效的商业卡密或续期激活码" }); } var devices = await _securityService.GetTenantDevicesAsync(tenantId); if (!devices.Any(d => d.DeviceId == deviceId)) { return NotFound(new { success = false, message = "未找到本账号名下的指定大屏设备" }); } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "Teacher"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); var (success, message, newStatus) = await _securityService.RenewDeviceLicenseAsync( deviceId, dto.ActivationCode.Trim(), null, null, actor, dto.Reason ?? "教师端自主商业卡密续期", null); if (!success) { return BadRequest(new { success = false, message }); } try { if (newStatus != null) { await deviceHubContext.Clients.All.ReceiveLicenseStatus(newStatus); } } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast ReceiveLicenseStatus to device {DeviceId}", deviceId); } return Ok(new { success = true, message, license = newStatus }); } }