using System.Security.Claims; using ClassNotify.Server.Domain.Entities; 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]")] [Route("api/school-admin")] [Authorize(Roles = "SchoolAdmin,SuperAdmin")] public class SchoolAdminController : ControllerBase { private readonly ISecurityService _securityService; private readonly ILogger _logger; public SchoolAdminController(ISecurityService securityService, ILogger logger) { _securityService = securityService; _logger = logger; } private string? GetTenantId() { // If SuperAdmin, can specify tenant_id via query or header, otherwise use claim var claimTenant = User.FindFirst("tenant_id")?.Value; if (claimTenant == "global" && Request.Query.ContainsKey("tenant_id")) { return Request.Query["tenant_id"].ToString(); } return claimTenant; } /// /// 获取本校基础统计 /// [HttpGet("overview")] public async Task GetOverview() { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var tenant = await _securityService.GetTenantAsync(tenantId); var classes = await _securityService.GetClassroomsAsync(tenantId); var devices = await _securityService.GetTenantDevicesAsync(tenantId); var teachers = await _securityService.GetUsersAsync(tenantId); return Ok(new { tenantId, tenantName = tenant?.Name ?? tenantId, classCount = classes.Count, deviceCount = devices.Count, onlineCount = devices.Count(d => d.IsOnline), teacherCount = teachers.Count }); } /// /// 获取本校所有班级 /// [HttpGet("classes")] public async Task GetClasses() { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var classes = await _securityService.GetClassroomsAsync(tenantId); return Ok(classes); } /// /// 为本校新增班级 /// [HttpPost("classes")] public async Task CreateClass([FromBody] CreateClassroomDto dto) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (string.IsNullOrWhiteSpace(dto.Id) || string.IsNullOrWhiteSpace(dto.DisplayName)) { return BadRequest(new { success = false, message = "班级编号与班级名称不可为空" }); } try { var ok = await _securityService.CreateClassroomAsync(tenantId, dto); if (!ok) { return BadRequest(new { success = false, message = $"班级编号 {dto.Id} 已存在" }); } return Ok(new { success = true, message = "班级创建成功" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 获取本校所有教师与管理员账号 /// [HttpGet("teachers")] public async Task GetTeachers() { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var users = await _securityService.GetUsersAsync(tenantId); var result = users.Select(u => new { u.Id, u.Username, u.FullName, u.Role, u.IsLocked, u.CreatedAt, u.LastLoginAt }); return Ok(result); } /// /// 学校管理员为本校教师重置密码 /// [HttpPost("teachers/{userId}/reset-password")] public async Task ResetTeacherPassword(string userId, [FromBody] ResetPasswordRequest req) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (string.IsNullOrWhiteSpace(req.NewPassword) || req.NewPassword.Length < 8) { return BadRequest(new { success = false, message = "新密码长度不得小于 8 个字符" }); } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); try { await _securityService.ResetSchoolTeacherPasswordAsync(tenantId, userId, req.NewPassword, actor, ip); return Ok(new { success = true, message = "教师密码已成功重置,历史登录会话已失效" }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (UnauthorizedAccessException ex) { return StatusCode(403, new { success = false, message = ex.Message }); } catch (KeyNotFoundException ex) { return NotFound(new { success = false, message = ex.Message }); } } /// /// 学校管理员为本校教师签发一次性重置工单 (教师自设新密码,管理员不接触新密码明文) /// [HttpPost("teachers/{userId}/issue-reset-ticket")] public async Task IssueTeacherResetTicket(string userId) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var teachers = await _securityService.GetUsersAsync(tenantId); if (!teachers.Any(t => t.Id == userId)) { return NotFound(new { success = false, message = "未找到本机构指定教师账号" }); } var actorId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "admin"; var actorName = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); var result = await _securityService.IssueAdminResetTicketAsync(actorId, actorName, userId, ip); if (!result.Success) { return BadRequest(result); } return Ok(result); } /// /// 学校管理员停用或启用本校教师账号 /// [HttpPost("teachers/{userId}/lock")] public async Task SetTeacherLock(string userId, [FromBody] LockUserRequest req) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); try { var changed = await _securityService.SetSchoolTeacherLockAsync(tenantId, userId, req.IsLocked, actor, ip); return Ok(new { success = true, changed, isLocked = req.IsLocked, message = changed ? (req.IsLocked ? "教师账号已停用并强制下线" : "教师账号已恢复启用") : "账号已处于目标状态" }); } catch (UnauthorizedAccessException ex) { return StatusCode(403, new { success = false, message = ex.Message }); } catch (KeyNotFoundException ex) { return NotFound(new { success = false, message = ex.Message }); } } /// /// 为本校创建教师账号 /// [HttpPost("teachers")] public async Task CreateTeacher([FromBody] CreateTeacherDto dto) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (string.IsNullOrWhiteSpace(dto.Username) || string.IsNullOrWhiteSpace(dto.Password) || string.IsNullOrWhiteSpace(dto.FullName)) { return BadRequest(new { success = false, message = "账号、密码和姓名不可为空" }); } // P0-02: Prevent privilege escalation. // SchoolAdmin can only create Teacher accounts. // SuperAdmin can create SchoolAdmin or Teacher, but never SuperAdmin here. if (!User.IsInRole("SuperAdmin")) { dto.Role = "Teacher"; } else { if (dto.Role == "SuperAdmin") { return BadRequest(new { success = false, message = "禁止通过此接口创建平台超级管理员账号" }); } if (string.IsNullOrWhiteSpace(dto.Role)) { dto.Role = "Teacher"; } } var ok = await _securityService.CreateUserAsync(tenantId, dto); if (!ok) { return BadRequest(new { success = false, message = $"用户名 {dto.Username} 已存在" }); } return Ok(new { success = true, message = "教师账号创建成功" }); } /// /// 获取本校所有设备 /// [HttpGet("devices")] public async Task GetDevices() { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var devices = await _securityService.GetTenantDevicesAsync(tenantId); return Ok(devices); } /// /// 获取本校激活码 /// [HttpGet("activation-codes")] public async Task GetActivationCodes() { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var codes = await _securityService.GetActivationCodesAsync(tenantId); return Ok(codes); } /// /// 本校管理员生成班级激活码 (支持批量、授权期限与备注) /// [HttpPost("activation-codes")] public async Task GenerateActivationCode( [FromQuery] string? classId = null, [FromQuery] int? durationDays = null, [FromQuery] string? tier = null, [FromQuery] string? notes = null, [FromQuery] int? count = null, [FromBody] GenerateActivationCodeRequestDto? body = null) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (User.IsInRole("TenantOwner") || User.IsInRole("Teacher")) { return StatusCode(403, new { success = false, message = "普通教师及个人空间用户禁止生成激活码" }); } var finalClassId = !string.IsNullOrWhiteSpace(body?.ClassId) ? body.ClassId.Trim() : classId?.Trim(); var finalTier = !string.IsNullOrWhiteSpace(body?.Tier) ? body.Tier.Trim() : (!string.IsNullOrWhiteSpace(tier) ? tier.Trim() : "Trial"); var finalNotes = !string.IsNullOrWhiteSpace(body?.Notes) ? body.Notes.Trim() : notes?.Trim(); int finalCount = body?.Count ?? count ?? 1; int? finalDurationDays = body?.DurationDays ?? durationDays ?? 7; var explicitPurpose = !string.IsNullOrWhiteSpace(body?.Purpose) ? body.Purpose.Trim() : "ProvisionAndLicense"; var tenant = await _securityService.GetTenantAsync(tenantId); if (tenant == null || !tenant.IsActive) return Unauthorized(); // ChatGPT Turn 54 Blocker 2 Fix: Explicit purpose verification. // Never infer elevated purpose from missing classId. if (explicitPurpose == "PersonalProvisionAndLicense" || explicitPurpose == "BootstrapClassroomAndDevice") { if (tenant.TenantType != "Personal") { return BadRequest(new { success = false, message = "非教师账号(Personal Tenant)禁止生成免班级建班激活凭证" }); } } else { if (string.IsNullOrWhiteSpace(finalClassId)) { return BadRequest(new { success = false, message = "班级编号不可为空" }); } } if (string.Equals(finalTier, "Perpetual", StringComparison.OrdinalIgnoreCase)) { finalDurationDays = null; } else { if (!finalDurationDays.HasValue || finalDurationDays.Value < 1 || finalDurationDays.Value > 3650) { return BadRequest(new { success = false, message = "授权时长必须在 1 至 3650 天之间" }); } } var finalDistributionMethod = !string.IsNullOrWhiteSpace(body?.DistributionMethod) ? body.DistributionMethod.Trim() : "External"; var finalTeacherId = !string.IsNullOrWhiteSpace(body?.AssignedTeacherId) ? body.AssignedTeacherId.Trim() : null; var finalTeacherName = !string.IsNullOrWhiteSpace(body?.AssignedTeacherName) ? body.AssignedTeacherName.Trim() : null; Classroom? classroom = null; string? finalTargetClassName = null; if (!string.IsNullOrWhiteSpace(finalClassId)) { classroom = await _securityService.GetClassroomAsync(tenantId, finalClassId); if (classroom == null) { return NotFound(new { success = false, message = $"班级 {finalClassId} 不存在或不属于该学校" }); } finalTargetClassName = classroom.DisplayName; } else { finalTargetClassName = "待首次激活现场指定"; } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? (tenant.TenantType == "Personal" ? "PersonalTeacher" : "SchoolAdmin"); var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); try { var codes = await _securityService.GenerateActivationCodesAsync( tenantId, finalClassId ?? string.Empty, finalCount, finalDurationDays, finalTier, finalNotes, actor, tenant.TenantType == "Personal" ? "TenantOwner" : "SchoolAdmin", ip, finalDistributionMethod, finalTeacherId, finalTeacherName, finalTargetClassName, explicitPurpose); return Ok(new { success = true, code = codes.FirstOrDefault() ?? string.Empty, codes, count = codes.Count, tenantId, classId = finalClassId, durationDays = finalDurationDays, tier = finalTier, notes = finalNotes, distributionMethod = finalDistributionMethod, assignedTeacherId = finalTeacherId, assignedTeacherName = finalTeacherName, message = codes.Count > 1 ? $"成功批量生成 {codes.Count} 个激活码" : "激活码生成成功" }); } catch (Exception ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 学校管理员指派或重新指派激活码给教师/班级 (Turn 50) /// [HttpPost("activation-codes/assign")] public async Task AssignActivationCode([FromBody] AssignActivationCodeRequestDto dto) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (string.IsNullOrWhiteSpace(dto.Code)) { return BadRequest(new { success = false, message = "激活码不可为空" }); } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); try { var ok = await _securityService.AssignActivationCodeAsync(tenantId, dto, actor, "SchoolAdmin", ip); return Ok(new { success = ok, message = ok ? "激活码指派成功" : "指派失败" }); } catch (KeyNotFoundException ex) { return NotFound(new { success = false, message = ex.Message }); } catch (InvalidOperationException ex) { return BadRequest(new { success = false, message = ex.Message }); } catch (ArgumentException ex) { return BadRequest(new { success = false, message = ex.Message }); } } /// /// 学校管理员批量更新本校激活码备注/标记 /// [HttpPut("activation-codes/notes")] public async Task BatchTagActivationCodes([FromBody] BatchTagActivationCodesRequestDto dto) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); if (dto.Codes == null || dto.Codes.Count == 0) { return BadRequest(new { success = false, message = "未选择任何激活码" }); } // Scope validation: only allow updating codes that belong to this tenant var schoolCodes = await _securityService.GetActivationCodesAsync(tenantId); var allowedCodes = schoolCodes.Select(c => c.Code).ToHashSet(StringComparer.OrdinalIgnoreCase); var filteredCodes = dto.Codes.Where(c => allowedCodes.Contains(c.Trim())).ToList(); if (filteredCodes.Count == 0) { return BadRequest(new { success = false, message = "未找到属于本校的匹配激活码" }); } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); var ok = await _securityService.UpdateActivationCodeNotesAsync( filteredCodes, dto.Notes, actor, "SchoolAdmin", ip); return Ok(new { success = ok, message = ok ? "激活码备注更新成功" : "更新失败" }); } /// /// 学校管理员修改本校设备班级名称 /// [HttpPut("devices/{deviceId}/class-name")] public async Task UpdateDeviceClassName( string deviceId, [FromBody] UpdateClassNameRequestDto dto, [FromServices] IHubContext deviceHubContext) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var devices = await _securityService.GetTenantDevicesAsync(tenantId); if (!devices.Any(d => d.DeviceId == deviceId)) { return NotFound(new { success = false, message = "未找到本校指定设备" }); } if (dto == null || string.IsNullOrWhiteSpace(dto.ClassName)) { return BadRequest(new { success = false, message = "班级名称不可为空" }); } var actor = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var (success, message, newName) = await _securityService.UpdateDeviceClassNameAsync( deviceId, dto.ClassName, actor, "SchoolAdmin"); if (!success) { return BadRequest(new { success = false, message }); } try { await deviceHubContext.Clients.Group($"dev_{deviceId}").ClassDisplayNameChanged(newName ?? dto.ClassName); } catch (Exception ex) { _logger.LogWarning(ex, "Failed to broadcast ClassDisplayNameChanged to device"); } return Ok(new { success = true, message, className = newName }); } /// /// 学校管理员为本校设备延期/续期 (一键续期 / 激活码续期) /// [HttpPost("devices/{deviceId}/license")] public async Task ManageDeviceLicense( string deviceId, [FromBody] RenewDeviceLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); 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 ?? "SchoolAdmin"; var ip = HttpContext.Connection.RemoteIpAddress?.ToString(); var (success, message, newStatus) = await _securityService.RenewDeviceLicenseAsync( deviceId, dto.ActivationCode, dto.ExtendDays, dto.Tier, actor, dto.Reason ?? $"学校管理员延期授权 ({dto.ExtendDays}天)", dto.ValidThroughDate); if (!success) { return BadRequest(new { success = false, message }); } if (newStatus != null) { await deviceHubContext.Clients.All.ReceiveLicenseStatus(newStatus); } return Ok(new { success = true, message, license = newStatus }); } [HttpPost("devices/licenses/batch-renew")] public async Task BatchManageDeviceLicenses( [FromBody] BatchRenewDevicesLicenseRequestDto dto, [FromServices] IHubContext deviceHubContext) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var schoolDevices = await _securityService.GetTenantDevicesAsync(tenantId); var schoolDeviceIds = schoolDevices.Select(d => d.DeviceId).ToHashSet(); var targetIds = dto.DeviceIds.Where(id => schoolDeviceIds.Contains(id)).ToList(); if (targetIds.Count == 0) { return BadRequest(new { success = false, message = "所选设备均不属于本校或不存在" }); } var actor = User.FindFirst(ClaimTypes.Name)?.Value ?? "SchoolAdmin"; var (success, message, renewedList) = await _securityService.BatchRenewDevicesLicenseAsync( targetIds, dto.ExtendDays, dto.Tier, actor, dto.Reason, dto.ValidThroughDate, dto.ClientRequestId, dto.LicenseKind, dto.ValidThroughLocalDate, tenantId); if (!success) { return BadRequest(new { success = false, message }); } foreach (var item in renewedList) { if (item.Status != null) { await deviceHubContext.Clients.All.ReceiveLicenseStatus(item.Status); } } return Ok(new { success = true, message, renewedCount = renewedList.Count }); } /// /// 获取本校通知广播历史记录与设备阅读回执 /// [HttpGet("notifications")] public async Task GetSchoolNotifications([FromQuery] int limit = 50) { var tenantId = GetTenantId(); if (string.IsNullOrEmpty(tenantId)) return Unauthorized(); var list = await _securityService.GetNotificationsAsync(tenantId, null, limit); return Ok(list); } }