================================================================================
CLASSNOTIFY P2.4 ALL-IN-ONE IMMUTABLE AUDIT SOURCE BUNDLE
Release ID: 20260924-P24-REMEDIATED-C3F740EF
Generated At: 2026-09-24T12:40:31.462Z
Target: Tokyo Oracle Linux Production Deployment (158.179.179.29)
Public Audit URL: https://audit.paradise.eu.org/latest-source.txt
================================================================================
SECURITY & QUALITY COMPLIANCE:
1. SecurityService.cs: Strict Teacher-only Reset & Lock; SuperAdmin Global Immunity; Strict SenderUserId cancel authorization.
2. NotificationController.cs: Tenant-isolated group broadcasting; Idempotent First-Writer-Wins cancel semantics.
3. AdminController.cs: Real device receipt breakdown endpoint /api/admin/broadcasts/{id}/receipt-summary.
4. 10/10 Targeted Verification Gates 100% Passed on Tokyo Production VPS.
================================================================================
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/AndroidManifest.xml
SIZE: 1300 chars
SHA256: 924A7C43A5AFADCEDD51107FD6CA8F7E08E58B58AB377A3BA7747923AACBB2DF
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/drawable/ic_launcher_foreground.xml
SIZE: 388 chars
SHA256: AE120FA3B69940A91125E6060030CE7D06895CECB5DA8375ABA7CDF8BD6B7DA8
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
SIZE: 268 chars
SHA256: 5F3B1ED2282AF327C78539428C3398A99A7E9A09051C2AE2CF7AA27068201319
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
SIZE: 268 chars
SHA256: 5F3B1ED2282AF327C78539428C3398A99A7E9A09051C2AE2CF7AA27068201319
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/mipmap/ic_launcher_round.xml
SIZE: 500 chars
SHA256: 75B960B60283D396B2568EFA0BC2A8AE766E58DC8CB5F3A658229B5C93959FBB
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/mipmap/ic_launcher.xml
SIZE: 474 chars
SHA256: A20785C0D94F4E8998D0299A7852447E0D17E6BD5837E896ACE4F96BC2D2D0C8
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/values/colors.xml
SIZE: 121 chars
SHA256: 608FE474242268A30B917C53F81F4882A017FE420656C16DAEE66D81972E1EE3
===================================================================== */
#2563EB
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/values/strings.xml
SIZE: 74 chars
SHA256: B0A57EF6E50727C113993C03FC8D7373B8143AE7B238A4C9D910683A8C3E2335
===================================================================== */
ClassNotify
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/values/themes.xml
SIZE: 286 chars
SHA256: D2BD473394289104B890E405EDDDE6C8751D1CE66B9416CD61E6C3C9B8ADB69F
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/xml/backup_rules.xml
SIZE: 211 chars
SHA256: A432106C6BDB4CAD937E2F2FA90A8AC5BAF59314A53191CBC7D69CDD0253BC91
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/app/src/main/res/xml/data_extraction_rules.xml
SIZE: 450 chars
SHA256: 0538936547885AAFD7DBDCCF1ABAA58474F249B86B47D54CBF02C9BFA1FA9332
===================================================================== */
/* =====================================================================
FILE: src/Android/ClassNotify.Android/README.md
SIZE: 1158 chars
SHA256: 217D6D077841E596D7CCFF29A45D0F88F1BE9983DA8C5C6896089B45621C53EA
===================================================================== */
# ClassNotify Android 教师端应用
采用 **Kotlin + Jetpack Compose + Material 3** 原生开发,直连东京云端服务器(`https://classnotify.paradise.eu.org`)。
---
## 🌟 核心功能特性
1. **登录与会话保持**:
- 教师工号 + 密码鉴权,JWT 自动持久化存储,下次启动免登录。
- 内置 **“⚡ 快捷体验:张老师”** 一键填充与登录。
2. **班级看板与实时硬件状态**:
- 横向滑动查看所带班级(八年级(1)班、八年级(2)班等)。
- **教室大屏硬件实时状态指示灯**(🟢 在线 / 🔴 离线),由 SignalR WebSocket 毫秒级动态推送。
3. **呼叫表单与高频短语**:
- 支持呼叫指定学生姓名(选填),留空则全班广播。
- 常用快捷短语标签一键填入(“请带作业本到办公室”、“马上到操场集合”等)。
- 控制开关:TTS 语音朗读、窗口震颤、置顶紧急广播、倒计时时长。
4. **实时回执时间线 (ACK)**:
- 直连云端 `SignalR`(`com.microsoft.signalr:signalr:8.0.0`),长连接监听回执事件。
- 毫秒级动态展示:
- `云端下发中...`(Sent)
- `教室大屏已接收`(Delivered)
- `学生已点击确认`(Acknowledged,附精确确认时间)
---
## 🛠️ 构建与运行
### 方式 1:Android Studio(推荐)
1. 使用 **Android Studio Hedgehog (2023.1.1)** 或更高版本打开目录:
`src/Android/ClassNotify.Android`
2. 等待 Gradle Sync 完成。
3. 连接 Android 真机(开启 USB 调试)或启动 Android 模拟器。
4. 点击 **Run 'app'** 即可直接在手机上运行调试。
5. 生成发布版 APK:点击菜单 **Build > Build Bundle(s) / APK(s) > Build APK(s)**。
### 方式 2:命令行构建(需 JDK 17+ 和 Android SDK)
```bash
cd src/Android/ClassNotify.Android
./gradlew assembleDebug
```
产物路径:`app/build/outputs/apk/debug/app-debug.apk`。
/* =====================================================================
FILE: src/Scripts/Install-ClassNotify.ps1
SIZE: 3727 chars
SHA256: C3CACA1336ECA4A160DF472DE52848E9C1DC5E9AD1DDF84CC52DB05AC1E4FC48
===================================================================== */
# Install-ClassNotify.ps1 - Enterprise Windows Service Maintenance Installer
# Note: For production deployments, use ClassNotify.Setup.exe which handles activation,
# DPAPI LocalMachine credential encryption, hardened NTFS ACLs, and automatic self-check.
param(
[string]$ClassId = "801",
[string]$ClassName = "八年级(1)班",
[string]$ServerUrl = "https://notice.yourdomain.com/hubs/device"
)
# Ensure running as Administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "请以管理员身份运行此脚本!(Run as Administrator)"
exit 1
}
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host " ClassNotify V2.0 商业级服务端部署程序 " -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan
$InstallDir = "C:\ProgramData\ClassNotify"
$SourceDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# 1. Prepare Directory
Write-Host "[1/4] 创建企业级安装目录: $InstallDir ..." -ForegroundColor Yellow
if (-not (Test-Path $InstallDir)) {
New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
}
$logDir = Join-Path $InstallDir "logs"
if (-not (Test-Path $logDir)) {
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
}
# 2. Copy Binaries
Write-Host "[2/4] 部署服务与客户端二进制文件..." -ForegroundColor Yellow
$binaries = @("ClassNotify.Service.exe", "ClassNotify.Client.exe", "ClassNotify.Shared.dll")
foreach ($bin in $binaries) {
$src = Join-Path $SourceDir $bin
if (Test-Path $src) {
Copy-Item -Path $src -Destination $InstallDir -Force
}
}
# 3. Generate AppSettings (No plaintext secret tokens! Credentials managed via DPAPI)
Write-Host "[3/4] 写入服务运行配置 appsettings.json..." -ForegroundColor Yellow
$configObj = @{
Logging = @{
LogLevel = @{
Default = "Information"
"Microsoft.Hosting.Lifetime" = "Information"
}
}
ClassNotify = @{
ServerUrl = $ServerUrl
ClassId = $ClassId
ClassName = $ClassName
HeartbeatIntervalSeconds = 15
PipeName = "ClassNotify_Ipc_Pipe"
}
}
$configPath = Join-Path $InstallDir "appsettings.json"
$configObj | ConvertTo-Json -Depth 5 | Set-Content -Path $configPath -Encoding UTF8
# 4. Clean up legacy autorun tasks & Register Windows Service
Write-Host "[4/4] 注册 Windows Service (ClassNotifyService)..." -ForegroundColor Yellow
$legacyTasks = @("ClassNotifyClient", "ClassNotify_Client_UI", "ClassNotify")
foreach ($t in $legacyTasks) {
cmd /c "schtasks /delete /tn `"$t`" /f" 2>$null
}
$serviceExe = Join-Path $InstallDir "ClassNotify.Service.exe"
$existingService = Get-Service -Name "ClassNotifyService" -ErrorAction SilentlyContinue
if ($existingService) {
Stop-Service -Name "ClassNotifyService" -Force -ErrorAction SilentlyContinue
sc.exe delete ClassNotifyService | Out-Null
Start-Sleep -Seconds 1
}
sc.exe create ClassNotifyService binPath= "`"$serviceExe`"" start= auto DisplayName= "ClassNotify 班级实时通信服务" | Out-Null
sc.exe failure ClassNotifyService reset= 86400 actions= restart/60000/restart/60000/restart/60000 | Out-Null
# Start Service (Service watchdog will securely launch Client with ephemeral token)
Start-Service -Name "ClassNotifyService" -ErrorAction SilentlyContinue
Write-Host "`n=========================================" -ForegroundColor Green
Write-Host " [成功] ClassNotify V2.0 商业级部署完成!" -ForegroundColor Green
Write-Host " 服务名称: ClassNotifyService (自动重启看门狗已启用)" -ForegroundColor Green
Write-Host " 教室编号: $ClassName ($ClassId)" -ForegroundColor Green
Write-Host "=========================================" -ForegroundColor Green
/* =====================================================================
FILE: src/Scripts/Repair-ClassNotify.ps1
SIZE: 3328 chars
SHA256: CDAD4EB8C35A6A6AB02AF69AB2E41E8AE194C6160DBEFC108A93748DDAE5268F
===================================================================== */
# Repair-ClassNotify.ps1 - One-click enterprise diagnosis & self-healing script
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "请以管理员身份运行此脚本!(Run as Administrator)"
exit 1
}
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host " ClassNotify 一键自动化诊断与修复工具 " -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan
$InstallDir = "C:\ProgramData\ClassNotify"
$configPath = Join-Path $InstallDir "appsettings.json"
# 1. Check Service
Write-Host "[1/4] 检查 Windows 服务状态..." -ForegroundColor Yellow
$svc = Get-Service -Name "ClassNotifyService" -ErrorAction SilentlyContinue
if (-not $svc) {
Write-Host " [警告] ClassNotifyService 未安装,正在尝试重新注册..." -ForegroundColor Red
$serviceExe = Join-Path $InstallDir "ClassNotify.Service.exe"
if (Test-Path $serviceExe) {
sc.exe create ClassNotifyService binPath= "`"$serviceExe`"" start= auto DisplayName= "ClassNotify 班级实时通信服务" | Out-Null
sc.exe failure ClassNotifyService reset= 86400 actions= restart/60000/restart/60000/restart/60000 | Out-Null
Start-Service -Name "ClassNotifyService"
Write-Host " [恢复] 服务已重新注册并启动!" -ForegroundColor Green
}
} elseif ($svc.Status -ne "Running") {
Write-Host " [警告] 服务当前处于停止状态 ($($svc.Status)),正在强制重启..." -ForegroundColor Yellow
Restart-Service -Name "ClassNotifyService" -Force
Write-Host " [恢复] 服务已重新启动!" -ForegroundColor Green
} else {
Write-Host " [正常] ClassNotifyService 运行正常。" -ForegroundColor Green
}
# 2. Check UI Process
Write-Host "[2/4] 检查前台 UI 进程..." -ForegroundColor Yellow
$uiProc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue
if (-not $uiProc) {
Write-Host " [提示] 前台 UI 进程未运行。根据 Batch 8 安全规范,客户端必须由守护服务通过动态 Launch Token 安全拉起。" -ForegroundColor Yellow
Write-Host " [恢复] 正在通知并重启 ClassNotifyService 看门狗拉起客户端..." -ForegroundColor Green
Restart-Service -Name "ClassNotifyService" -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
} else {
Write-Host " [正常] 前台 UI 进程运行正常。" -ForegroundColor Green
}
# 3. Check Network & SignalR
Write-Host "[3/4] 检查云端连通性..." -ForegroundColor Yellow
if (Test-Path $configPath) {
try {
$cfg = Get-Content -Path $configPath -Raw | ConvertFrom-Json
$serverUrl = $cfg.ClassNotify.ServerUrl
$uri = [System.Uri]$serverUrl
$ip = [System.Net.Dns]::GetHostAddresses($uri.DnsSafeHost)
if ($ip.Length -gt 0) {
Write-Host " [正常] 云端域名解析成功 ($($uri.DnsSafeHost) -> $($ip[0]))" -ForegroundColor Green
}
} catch {
Write-Host " [警告] 云端解析异常: $_" -ForegroundColor Red
}
}
# 4. Check TTS Sound Engine
Write-Host "[4/4] 测试本地 TTS 中文语音引擎..." -ForegroundColor Yellow
try {
Add-Type -AssemblyName System.Speech -ErrorAction Stop
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$voices = $synth.GetInstalledVoices()
if ($voices.Count -gt 0) {
Write-Host " [正常] 发现 $($voices.Count) 个系统语音包,TTS 引擎就绪。" -ForegroundColor Green
}
$synth.Dispose()
} catch {
Write-Host " [警告] TTS 引擎初始化失败: $_" -ForegroundColor Red
}
Write-Host "`n[诊断完成] 核心组件与自愈排错流程已执行完毕。" -ForegroundColor Cyan
/* =====================================================================
FILE: src/Scripts/SelfCheck.ps1
SIZE: 1468 chars
SHA256: 84777E8D8C5115C07C73947C29FC2171E043A35F07EED6FE6651362AD7AE9190
===================================================================== */
# SelfCheck.ps1 - Detailed environment diagnostic tool
$InstallDir = "C:\ProgramData\ClassNotify"
$configPath = Join-Path $InstallDir "appsettings.json"
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host " ClassNotify 运行环境与组件健康自检 " -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan
$report = [PSCustomObject]@{
WindowsService = "Missing"
UiProcess = "Stopped"
ConfigValid = (Test-Path $configPath)
TtsAvailable = $false
DnsResolution = $false
}
# 1. Service
$svc = Get-Service -Name "ClassNotifyService" -ErrorAction SilentlyContinue
if ($svc) { $report.WindowsService = $svc.Status.ToString() }
# 2. UI Process
$proc = Get-Process -Name "ClassNotify.Client" -ErrorAction SilentlyContinue
if ($proc) { $report.UiProcess = "Running" }
# 3. TTS
try {
Add-Type -AssemblyName System.Speech -ErrorAction Stop
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
if ($synth.GetInstalledVoices().Count -gt 0) { $report.TtsAvailable = $true }
$synth.Dispose()
} catch {}
# 4. Network DNS
if (Test-Path $configPath) {
try {
$cfg = Get-Content -Path $configPath -Raw | ConvertFrom-Json
$uri = [System.Uri]$cfg.ClassNotify.ServerUrl
if ([System.Net.Dns]::GetHostAddresses($uri.DnsSafeHost).Length -gt 0) {
$report.DnsResolution = $true
}
} catch {}
}
$report | Format-List
/* =====================================================================
FILE: src/Scripts/Uninstall-ClassNotify.ps1
SIZE: 996 chars
SHA256: 572843ADF44AE2ADBE1B356158AAFD813C68BAE37BA75FE651C5F2B271DA37D8
===================================================================== */
# Uninstall-ClassNotify.ps1 - Clean enterprise uninstaller
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Error "请以管理员身份运行此脚本!(Run as Administrator)"
exit 1
}
Write-Host "正在停止并清理 ClassNotifyService..." -ForegroundColor Yellow
Stop-Service -Name "ClassNotifyService" -Force -ErrorAction SilentlyContinue
sc.exe delete ClassNotifyService | Out-Null
Write-Host "正在停止前台 UI 进程..." -ForegroundColor Yellow
Stop-Process -Name "ClassNotify.Client" -Force -ErrorAction SilentlyContinue
Write-Host "清理计划任务..." -ForegroundColor Yellow
cmd /c "schtasks /delete /tn `"ClassNotify_Client_UI`" /f" 2>$null
Write-Host "清理安装文件目录..." -ForegroundColor Yellow
$InstallDir = "C:\ProgramData\ClassNotify"
if (Test-Path $InstallDir) {
Remove-Item -Path $InstallDir -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host "ClassNotify 商业级组件已彻底卸载干净。" -ForegroundColor Green
/* =====================================================================
FILE: src/Server/ClassNotify.Server/ClassNotify.Server.csproj
SIZE: 1102 chars
SHA256: D3C1FD688D4F64AEFACC78D82ED13F23D059976FA740B6DF6A9AF438EA6755A9
===================================================================== */
net8.0
enable
enable
all
runtime; build; native; contentfiles; analyzers; buildtransitive
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Configuration/JwtOptions.cs
SIZE: 299 chars
SHA256: 683BE25CF64E2BB25F147EF9D14AE496EA3234902956331B7E5200B793E26E60
===================================================================== */
namespace ClassNotify.Server.Configuration;
public sealed class JwtOptions
{
public string SigningKey { get; set; } = string.Empty;
public string Issuer { get; set; } = string.Empty;
public string Audience { get; set; } = string.Empty;
public int LifetimeDays { get; set; } = 14;
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Configuration/RateLimitOptions.cs
SIZE: 239 chars
SHA256: 638D4FD6837CD3C60071BD73B6C82B8D3B4EF8B63DCADD03377ABC04844967C8
===================================================================== */
namespace ClassNotify.Server.Configuration;
public class RateLimitOptions
{
public int AuthPermitLimit { get; set; } = 60;
public int ActivationPermitLimit { get; set; } = 30;
public int SendPermitLimit { get; set; } = 120;
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/AdminController.cs
SIZE: 19711 chars
SHA256: CD2FBB2D94677F1A77158D1B4E7AF07F605DAA2BC7A297FEAB4A3B3C017CC572
===================================================================== */
using System.Security.Claims;
using ClassNotify.Server.Hubs;
using ClassNotify.Server.Services;
using ClassNotify.Shared.Contracts;
using ClassNotify.Shared.Enums;
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 = "SuperAdmin")]
public class AdminController : ControllerBase
{
private readonly ISecurityService _securityService;
private readonly IHubContext _deviceHub;
private readonly IHubContext _teacherHub;
private readonly ILogger _logger;
public AdminController(
ISecurityService securityService,
IHubContext deviceHub,
IHubContext teacherHub,
ILogger logger)
{
_securityService = securityService;
_deviceHub = deviceHub;
_teacherHub = teacherHub;
_logger = logger;
}
private string GetActorUsername() => User.FindFirst(ClaimTypes.Name)?.Value ?? "admin";
private string GetActorRole() => User.FindFirst(ClaimTypes.Role)?.Value ?? "SuperAdmin";
private string? GetClientIp() => HttpContext.Connection.RemoteIpAddress?.ToString();
///
/// 获取平台总体运行指标
///
[HttpGet("metrics")]
public async Task GetMetrics()
{
var metrics = await _securityService.GetAdminMetricsAsync();
return Ok(metrics);
}
///
/// 获取所有学校/租户概览
///
[HttpGet("tenants")]
public async Task GetTenants()
{
var tenants = await _securityService.GetTenantsOverviewAsync();
return Ok(tenants);
}
///
/// 创建新学校/租户
///
[HttpPost("tenants")]
public async Task CreateTenant([FromBody] CreateTenantRequest req)
{
if (string.IsNullOrWhiteSpace(req.Id) || string.IsNullOrWhiteSpace(req.Name))
{
return BadRequest(new { success = false, message = "学校代码与名称不能为空" });
}
try
{
var tenant = await _securityService.CreateTenantAsync(req.Id.Trim(), req.Name.Trim(), GetActorUsername(), GetActorRole(), GetClientIp());
return Ok(tenant);
}
catch (InvalidOperationException ex)
{
return Conflict(new { success = false, message = ex.Message });
}
}
///
/// 更新学校信息或停用/启用学校
///
[HttpPatch("tenants/{tenantId}")]
public async Task UpdateTenant(string tenantId, [FromBody] UpdateTenantRequest req)
{
if (string.IsNullOrWhiteSpace(req.Name))
{
return BadRequest(new { success = false, message = "学校名称不能为空" });
}
var updated = await _securityService.UpdateTenantAsync(tenantId, req.Name.Trim(), req.IsActive, GetActorUsername(), GetActorRole(), GetClientIp());
if (updated == null)
{
return NotFound(new { success = false, message = "未找到指定学校" });
}
return Ok(updated);
}
///
/// 获取平台用户列表 (支持按租户和角色筛选)
///
[HttpGet("users")]
public async Task GetUsers([FromQuery] string? tenantId, [FromQuery] string? role)
{
var users = await _securityService.GetAllUsersAdminAsync(tenantId, role);
return Ok(users);
}
///
/// 创建新用户 (严格执行角色白名单校验: 仅限 SchoolAdmin 或 Teacher)
///
[HttpPost("users")]
public async Task CreateUser([FromBody] CreateUserAdminRequest req)
{
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
{
return BadRequest(new { success = false, message = "用户名与密码不能为空" });
}
if (req.Password.Length < 8)
{
return BadRequest(new { success = false, message = "用户密码长度不得小于 8 个字符" });
}
if (string.IsNullOrWhiteSpace(req.TenantId))
{
return BadRequest(new { success = false, message = "必须指定归属学校" });
}
if (req.Role != "SchoolAdmin" && req.Role != "Teacher")
{
return BadRequest(new { success = false, message = "只允许创建校区管理员 (SchoolAdmin) 或教师账号 (Teacher)" });
}
try
{
var user = await _securityService.CreateUserAdminAsync(req, GetActorUsername(), GetActorRole(), GetClientIp());
return Ok(user);
}
catch (InvalidOperationException ex)
{
return Conflict(new { success = false, message = ex.Message });
}
}
///
/// 管理员重置指定用户密码
///
[HttpPost("users/{userId}/reset-password")]
public async Task ResetPassword(string userId, [FromBody] ResetPasswordRequest req)
{
if (string.IsNullOrWhiteSpace(req.NewPassword))
{
return BadRequest(new { success = false, message = "新密码不能为空" });
}
if (req.NewPassword.Length < 8)
{
return BadRequest(new { success = false, message = "新密码长度不得小于 8 个字符" });
}
var ok = await _securityService.ResetPasswordAsync(userId, req.NewPassword, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "用户不存在" });
}
return Ok(new { success = true, message = "密码已成功重置" });
}
///
/// 锁定或解锁用户账号
///
[HttpPost("users/{userId}/lock")]
public async Task SetUserLock(string userId, [FromBody] LockUserRequest req)
{
var ok = await _securityService.SetUserLockAsync(userId, req.IsLocked, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "用户不存在" });
}
var detail = req.IsLocked ? "锁定账号 (禁止登录)" : "解锁账号 (恢复登录)";
return Ok(new { success = true, isLocked = req.IsLocked, message = detail });
}
///
/// 删除指定用户
///
[HttpDelete("users/{userId}")]
public async Task DeleteUser(string userId)
{
var ok = await _securityService.DeleteUserAsync(userId, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "用户不存在或无法删除" });
}
return Ok(new { success = true, message = "用户已删除" });
}
///
/// 获取全网所有设备及其在线状态、心跳、版本
///
[HttpGet("devices")]
public async Task GetDevices()
{
var devices = await _securityService.GetAllDevicesAsync();
return Ok(devices);
}
///
/// 更新设备信息 (主机名/重命名、绑定班级)
///
[HttpPatch("devices/{deviceId}")]
public async Task UpdateDevice(string deviceId, [FromBody] UpdateDeviceRequest req)
{
try
{
var ok = await _securityService.UpdateDeviceAsync(deviceId, req.Hostname, req.ClassroomId, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "设备不存在" });
}
return Ok(new { success = true, message = "设备信息已更新" });
}
catch (InvalidOperationException ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
}
///
/// 清退并注销指定设备
///
[HttpPost("devices/{deviceId}/decommission")]
public async Task DecommissionDevice(string deviceId)
{
var ok = await _securityService.DecommissionDeviceAsync(deviceId, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "设备不存在" });
}
return Ok(new { success = true, message = "设备已注销并清退" });
}
///
/// 向指定设备下发远程维护指令 (SelfCheck, RestartClient, Reconnect, RefreshConfig)
///
[HttpPost("devices/{deviceId}/command")]
public async Task SendDeviceCommand(string deviceId, [FromBody] RemoteCommandRequestDto req)
{
if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(req.Command))
{
return BadRequest(new { success = false, message = "设备编号与指令内容不可为空" });
}
try
{
var adminUser = GetActorUsername();
var cmdType = req.Command;
if (cmdType.Equals("ping", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.SelfCheck;
else if (cmdType.Equals("restart_client", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RestartClient;
else if (cmdType.Equals("refresh_config", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.RefreshConfig;
else if (cmdType.Equals("reconnect", StringComparison.OrdinalIgnoreCase)) cmdType = DeviceCommandTypes.Reconnect;
if (!DeviceCommandTypes.IsSupported(cmdType))
{
return BadRequest(new { success = false, message = $"不支持的指令类型: '{req.Command}'。允许指令: {string.Join(", ", DeviceCommandTypes.AllSupported)}" });
}
var cmdDto = await _securityService.CreateDeviceCommandAsync(null, deviceId, cmdType, req.Parameters, adminUser, GetActorRole(), GetClientIp());
var connId = _securityService.GetDeviceConnectionId(deviceId);
if (!string.IsNullOrEmpty(connId))
{
await _deviceHub.Clients.Client(connId).ReceiveRemoteCommand(cmdDto);
await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId);
cmdDto.Status = DeviceCommandStatuses.Dispatched;
_logger.LogInformation("Admin dispatched remote command {CommandId} ('{Command}') to device {DeviceId} ({ConnId})",
cmdDto.CommandId, cmdDto.CommandType, deviceId, connId);
await _securityService.LogAdminAuditAsync(
adminUser, GetActorRole(), "REMOTE_COMMAND_DISPATCHED", "Device", deviceId,
$"指令已实时通过 SignalR 下发: {cmdDto.CommandType} (CommandId: {cmdDto.CommandId})", GetClientIp());
}
else
{
_logger.LogInformation("Device {DeviceId} is offline. Remote command {CommandId} queued as Pending (expires at {ExpiresAt})",
deviceId, cmdDto.CommandId, cmdDto.ExpiresAt);
await _securityService.LogAdminAuditAsync(
adminUser, GetActorRole(), "REMOTE_COMMAND_QUEUED", "Device", deviceId,
$"设备离线,指令已入队待补发: {cmdDto.CommandType} (CommandId: {cmdDto.CommandId})", GetClientIp());
}
return Ok(new
{
success = true,
commandId = cmdDto.CommandId,
deviceId,
command = cmdDto.CommandType,
status = cmdDto.Status,
expiresAt = cmdDto.ExpiresAt,
message = string.IsNullOrEmpty(connId)
? $"设备当前离线,指令 [{cmdDto.CommandType}] 已入队,将在设备上线时自动补发 (有效期至 {cmdDto.ExpiresAt:u})"
: $"远程指令 [{cmdDto.CommandType}] 已通过 SignalR 实时下发至设备"
});
}
catch (ArgumentException ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
catch (InvalidOperationException ex)
{
return NotFound(new { success = false, message = ex.Message });
}
}
///
/// 获取指定学校的所有班级列表 (供管理端激活码生成等下拉选择)
///
[HttpGet("classes")]
public async Task GetClasses([FromQuery] string tenantId)
{
if (string.IsNullOrWhiteSpace(tenantId))
{
return BadRequest(new { success = false, message = "租户代码不可为空" });
}
var classes = await _securityService.GetClassroomsAsync(tenantId.Trim());
return Ok(classes);
}
///
/// 获取全网激活码列表
///
[HttpGet("activation-codes")]
public async Task GetActivationCodes()
{
var codes = await _securityService.GetActivationCodesAsync(null);
return Ok(codes);
}
///
/// 超级管理员直接生成指定学校指定班级的激活码
///
[HttpPost("activation-codes")]
public async Task GenerateActivationCode([FromQuery] string tenantId, [FromQuery] string classId)
{
if (string.IsNullOrWhiteSpace(tenantId) || string.IsNullOrWhiteSpace(classId))
{
return BadRequest(new { success = false, message = "租户与班级不可为空" });
}
try
{
var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId, GetActorUsername(), GetActorRole(), GetClientIp());
return Ok(new
{
success = true,
code,
tenantId,
classId,
message = "激活码生成成功"
});
}
catch (InvalidOperationException ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
}
///
/// 作废或删除激活码
///
[HttpDelete("activation-codes/{code}")]
public async Task DeleteActivationCode(string code)
{
var ok = await _securityService.DeleteActivationCodeAsync(code, GetActorUsername(), GetActorRole(), GetClientIp());
if (!ok)
{
return NotFound(new { success = false, message = "激活码不存在" });
}
return Ok(new { success = true, message = "激活码已成功作废" });
}
///
/// 获取全平台最新通知历史记录与 ACK
///
[HttpGet("notifications")]
public async Task GetNotifications([FromQuery] int limit = 50)
{
var list = await _securityService.GetNotificationsAsync(null, null, limit);
return Ok(list);
}
///
/// 超级管理员跨租户/全网紧急广播下发
///
[HttpPost("broadcasts")]
public async Task EmergencyBroadcast([FromBody] EmergencyBroadcastRequest req)
{
if (string.IsNullOrWhiteSpace(req.Message))
{
return BadRequest(new { success = false, message = "广播内容不能为空" });
}
if (req.Message.Length > 2000)
{
return BadRequest(new { success = false, message = "广播内容长度不能超过 2000 字符" });
}
if (!string.IsNullOrWhiteSpace(req.Title) && req.Title.Length > 100)
{
return BadRequest(new { success = false, message = "广播标题长度不能超过 100 字符" });
}
if (req.DurationSeconds < 5 || req.DurationSeconds > 600)
{
return BadRequest(new { success = false, message = "广播显示时长必须在 5 至 600 秒之间" });
}
var actor = GetActorUsername();
var targetTenants = new List();
if (string.IsNullOrWhiteSpace(req.TenantId) || req.TenantId == "*")
{
var all = await _securityService.GetTenantsOverviewAsync();
targetTenants = all.Where(t => t.IsActive).ToList();
}
else
{
var all = await _securityService.GetTenantsOverviewAsync();
var found = all.FirstOrDefault(t => t.Id == req.TenantId);
if (found != null)
{
if (!found.IsActive)
{
return BadRequest(new { success = false, message = $"目标学校 '{found.Name}' 当前已被停用,无法接收应急广播" });
}
targetTenants.Add(found);
}
else return NotFound(new { success = false, message = $"未找到指定学校: {req.TenantId}" });
}
// P0-FailClosed Audit: Persist BROADCAST_REQUESTED audit BEFORE triggering any SignalR broadcast.
// If audit write fails (e.g. DB error or trigger block), an exception is thrown and NO broadcast is ever dispatched.
await _securityService.LogAdminAuditAsync(
actor, GetActorRole(), "EMERGENCY_BROADCAST_REQUESTED", "System", req.TenantId ?? "ALL",
$"请求下发紧急广播: {req.Title} (计划覆盖 {targetTenants.Count} 所学校)", GetClientIp());
var broadcastId = $"bcast_{Guid.NewGuid():N}";
int dispatchedCount = 0;
var duration = req.DurationSeconds;
foreach (var tenant in targetTenants)
{
var classrooms = await _securityService.GetClassroomsAsync(tenant.Id);
foreach (var cls in classrooms)
{
var notif = new NotificationDto
{
Id = $"msg_emerg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}",
BroadcastId = broadcastId,
TenantId = tenant.Id,
ClassId = cls.Id,
Title = string.IsNullOrWhiteSpace(req.Title) ? "⚠️ 全校紧急通知" : req.Title,
Message = req.Message,
Type = NotificationType.Urgent,
CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = DateTimeOffset.UtcNow.AddSeconds(duration + 120),
DurationSeconds = duration,
Voice = req.Voice,
Shake = req.Shake
};
await _securityService.RecordNotificationAsync(notif, null, "系统超级管理员 (应急广播)");
// Dispatch to SignalR classroom group
await _deviceHub.Clients.Group($"t:{tenant.Id}:c:{cls.Id}").ReceiveNotification(notif);
// Dispatch to Teacher Hub
await _teacherHub.Clients.Group($"t:{tenant.Id}:teachers").OnNewNotificationBroadcast(notif);
dispatchedCount++;
}
}
await _securityService.LogAdminAuditAsync(
actor, GetActorRole(), "EMERGENCY_BROADCAST_COMPLETED", "System", req.TenantId ?? "ALL",
$"紧急广播下发完成: {req.Title} - {req.Message} (覆盖 {dispatchedCount} 个班级, BroadcastId: {broadcastId})", GetClientIp());
return Ok(new
{
success = true,
broadcastId,
dispatchedCount,
targetSchools = targetTenants.Count,
message = $"紧急广播已成功下发至 {targetTenants.Count} 所学校共 {dispatchedCount} 个班级,正在等待设备回执"
});
}
///
/// 获取紧急广播真实设备回执聚合状态
///
[HttpGet("broadcasts/{broadcastId}/receipt-summary")]
public async Task GetBroadcastReceiptSummary(string broadcastId, CancellationToken ct)
{
var summary = await _securityService.GetBroadcastReceiptSummaryAsync(broadcastId, ct);
if (summary == null)
{
return NotFound(new { success = false, message = "未找到该广播记录" });
}
return Ok(summary);
}
///
/// 获取平台真实系统健康状态 (数据库连通性、延迟、内存、运行时间、连接数)
///
[HttpGet("system/health")]
public async Task GetSystemHealth()
{
var health = await _securityService.GetSystemHealthAsync();
return Ok(health);
}
///
/// 获取超级管理员关键操作审计日志
///
[HttpGet("audit-logs")]
public async Task GetAuditLogs([FromQuery] int limit = 100)
{
var logs = await _securityService.GetAdminAuditLogsAsync(limit);
return Ok(logs);
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/AuthController.cs
SIZE: 1460 chars
SHA256: 3B11304893E563B8232AE99DAFE5BE4870CFC11A1F4B6D09EECC02A4B5085C1A
===================================================================== */
using System.Security.Claims;
using ClassNotify.Server.Services;
using ClassNotify.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace ClassNotify.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("AuthLimiter")]
public class AuthController : ControllerBase
{
private readonly ISecurityService _securityService;
public AuthController(ISecurityService securityService)
{
_securityService = securityService;
}
///
/// 统一登录接口 (返回包含 Role / TenantId 的 JWT Token)
///
[HttpPost("login")]
public async Task Login([FromBody] TeacherLoginDto dto)
{
var remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
var result = await _securityService.LoginTeacherAsync(dto, remoteIp);
if (!result.Success)
{
return Unauthorized(result);
}
return Ok(result);
}
///
/// 获取当前登录用户画像与角色
///
[HttpGet("me")]
[Authorize]
public IActionResult GetMe()
{
return Ok(new
{
userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
name = User.FindFirst(ClaimTypes.Name)?.Value,
role = User.FindFirst(ClaimTypes.Role)?.Value,
tenantId = User.FindFirst("tenant_id")?.Value
});
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/DeviceCommandController.cs
SIZE: 5204 chars
SHA256: 71F0D64FD4979D7EEB4A5B7BC51C659393CB23A6FF48CB09B8F9491E619E45B3
===================================================================== */
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;
public class SendDeviceCommandRequest
{
public string DeviceId { get; set; } = string.Empty;
public string CommandType { get; set; } = string.Empty;
public string? Parameters { get; set; }
}
[ApiController]
[Route("api/device-command")]
[Authorize]
public class DeviceCommandController : ControllerBase
{
private readonly ISecurityService _securityService;
private readonly IHubContext _deviceHub;
private readonly ILogger _logger;
public DeviceCommandController(
ISecurityService securityService,
IHubContext deviceHub,
ILogger logger)
{
_securityService = securityService;
_deviceHub = deviceHub;
_logger = logger;
}
///
/// 下发受控远程运维命令 (SelfCheck, RestartClient, Reconnect, RefreshConfig)
///
[HttpPost("send")]
[Authorize(Roles = "SuperAdmin,SchoolAdmin,Teacher")]
public async Task SendCommand([FromBody] SendDeviceCommandRequest req)
{
if (req == null || string.IsNullOrWhiteSpace(req.DeviceId) || string.IsNullOrWhiteSpace(req.CommandType))
{
return BadRequest(new { success = false, message = "设备编号与指令类型不可为空" });
}
var isSuperAdmin = User.IsInRole("SuperAdmin");
var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value;
var callerUser = User.Identity?.Name ?? User.FindFirst("name")?.Value ?? "User";
try
{
var cmdDto = await _securityService.CreateDeviceCommandAsync(
tenantId, req.DeviceId, req.CommandType, req.Parameters, callerUser);
var connId = _securityService.GetDeviceConnectionId(req.DeviceId);
if (!string.IsNullOrEmpty(connId))
{
await _deviceHub.Clients.Client(connId).ReceiveRemoteCommand(cmdDto);
await _securityService.MarkCommandDispatchedAsync(cmdDto.CommandId);
cmdDto.Status = DeviceCommandStatuses.Dispatched;
_logger.LogInformation("Dispatched command {CommandId} ({Type}) to device {DeviceId} via SignalR {ConnId}",
cmdDto.CommandId, cmdDto.CommandType, req.DeviceId, connId);
}
else
{
_logger.LogInformation("Device {DeviceId} is offline. Command {CommandId} queued as Pending until {ExpiresAt:u}",
req.DeviceId, cmdDto.CommandId, cmdDto.ExpiresAt);
}
return Ok(new
{
success = true,
command = cmdDto,
isDispatched = !string.IsNullOrEmpty(connId),
message = string.IsNullOrEmpty(connId)
? $"设备当前离线,指令已排队,将在设备上线且未过期时补发 (过期时间: {cmdDto.ExpiresAt:u})"
: $"指令已通过 SignalR 实时下发至设备 (过期时间: {cmdDto.ExpiresAt:u})"
});
}
catch (ArgumentException ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
catch (UnauthorizedAccessException ex)
{
return StatusCode(StatusCodes.Status403Forbidden, new { success = false, message = ex.Message });
}
catch (InvalidOperationException ex)
{
return NotFound(new { success = false, message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error sending command to device {DeviceId}", req.DeviceId);
return StatusCode(500, new { success = false, message = "下发指令内部错误" });
}
}
///
/// 查询单条命令当前状态与执行结果
///
[HttpGet("{commandId}")]
public async Task GetCommand(string commandId)
{
if (string.IsNullOrWhiteSpace(commandId))
{
return BadRequest(new { success = false, message = "CommandId 不可为空" });
}
var isSuperAdmin = User.IsInRole("SuperAdmin");
var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value;
var cmd = await _securityService.GetDeviceCommandAsync(commandId, tenantId);
if (cmd == null)
{
return NotFound(new { success = false, message = "命令未找到或无权访问" });
}
return Ok(cmd);
}
///
/// 获取命令审计流水历史记录
///
[HttpGet("history")]
public async Task GetHistory(
[FromQuery] string? deviceId = null,
[FromQuery] string? status = null,
[FromQuery] int limit = 50)
{
var isSuperAdmin = User.IsInRole("SuperAdmin");
var tenantId = isSuperAdmin ? null : User.FindFirst("tenant_id")?.Value;
var history = await _securityService.GetDeviceCommandHistoryAsync(tenantId, deviceId, status, limit);
return Ok(history);
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/DeviceController.cs
SIZE: 4164 chars
SHA256: 2F5D5BA2DBB53D861406118DB23A21B8680313F8AEA7235C65193B90244E1B78
===================================================================== */
using ClassNotify.Server.Services;
using ClassNotify.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace ClassNotify.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
[EnableRateLimiting("ActivationLimiter")]
public class DeviceController : ControllerBase
{
private readonly ISecurityService _securityService;
private readonly IVisualReceiptService _visualReceiptService;
public DeviceController(ISecurityService securityService, IVisualReceiptService visualReceiptService)
{
_securityService = securityService;
_visualReceiptService = visualReceiptService;
}
///
/// 教室端初次安装激活接口 (通过一次性激活码换取永久硬件凭据)
///
[HttpPost("activate")]
public async Task Activate([FromBody] DeviceActivationRequestDto dto)
{
var result = await _securityService.ActivateDeviceAsync(dto);
if (!result.Success)
{
if (result.ErrorMessage?.Contains("其他设备安装实例") == true)
{
return Conflict(result);
}
return BadRequest(result);
}
return Ok(result);
}
///
/// 学校教师/管理员在线生成班级一次性设备激活码
///
[HttpPost("generate-code")]
[Microsoft.AspNetCore.Authorization.Authorize(Roles = "SuperAdmin,SchoolAdmin")]
public async Task GenerateCode([FromQuery] string classId)
{
var tenantId = User.FindFirst("tenant_id")?.Value;
if (string.IsNullOrEmpty(tenantId))
{
return Unauthorized(new { success = false, message = "未发现合法的租户信息" });
}
if (string.IsNullOrWhiteSpace(classId))
{
return BadRequest(new { success = false, message = "班级编号不可为空" });
}
var classroom = await _securityService.GetClassroomAsync(tenantId, classId);
if (classroom == null)
{
return NotFound(new { success = false, message = $"班级 {classId} 不存在或不属于当前学校" });
}
try
{
var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId);
return Ok(new
{
success = true,
code,
tenantId,
classId,
message = "激活码已生成,有效期 7 天"
});
}
catch (Exception ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
}
///
/// 教室 Windows 客户端上传单帧通知视觉回执 (JPEG 格式, 最大 512KB)
///
[HttpPost("notifications/{notificationId}/visual-receipt")]
[HttpPost("/api/devices/notifications/{notificationId}/visual-receipt")]
[RequestSizeLimit(524288)] // 512 KiB
public async Task UploadVisualReceipt(string notificationId)
{
var deviceId = Request.Headers["X-Device-Id"].FirstOrDefault();
var deviceToken = Request.Headers["X-Device-Token"].FirstOrDefault();
if (string.IsNullOrWhiteSpace(deviceId) || string.IsNullOrWhiteSpace(deviceToken))
{
return Unauthorized(new { success = false, message = "缺少设备鉴权凭据 (X-Device-Id / X-Device-Token)" });
}
if (Request.ContentType?.StartsWith("image/jpeg", StringComparison.OrdinalIgnoreCase) != true)
{
return StatusCode(415, new { success = false, message = "仅支持 image/jpeg 格式内容" });
}
using var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms);
var bytes = ms.ToArray();
var result = await _visualReceiptService.SaveVisualReceiptAsync(notificationId, deviceId, deviceToken, bytes);
if (!result.Success)
{
return StatusCode(result.StatusCode, new { success = false, message = result.Message });
}
return Ok(new
{
success = true,
receiptId = result.ReceiptId,
notificationId,
visualReceiptState = "Available",
capturedAt = result.CapturedAt,
expiresAt = result.ExpiresAt,
message = result.Message
});
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/NotificationController.cs
SIZE: 9733 chars
SHA256: 4776B79CDF8E1B8FF9FA14100C84B71AE4B293727F29C8DD3B087E5940A67D76
===================================================================== */
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.RateLimiting;
using Microsoft.AspNetCore.SignalR;
namespace ClassNotify.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
[Authorize]
[EnableRateLimiting("SendLimiter")]
public class NotificationController : ControllerBase
{
private readonly IHubContext _deviceHubContext;
private readonly IHubContext _teacherHubContext;
private readonly ISecurityService _securityService;
private readonly IVisualReceiptService _visualReceiptService;
private readonly ILogger _logger;
public NotificationController(
IHubContext deviceHubContext,
IHubContext teacherHubContext,
ISecurityService securityService,
IVisualReceiptService visualReceiptService,
ILogger logger)
{
_deviceHubContext = deviceHubContext;
_teacherHubContext = teacherHubContext;
_securityService = securityService;
_visualReceiptService = visualReceiptService;
_logger = logger;
}
///
/// 教师向指定班级下发呼叫通知 (严格校验租户与班级权限)
///
[HttpPost("send")]
public async Task SendNotification([FromBody] NotificationDto notification)
{
// 1. Extract and validate tenant from authenticated teacher claims
var teacherTenantId = User.FindFirst("tenant_id")?.Value;
var teacherName = User.FindFirst(ClaimTypes.Name)?.Value ?? "未知老师";
var teacherId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(teacherTenantId))
{
return Unauthorized(new { success = false, message = "未发现合法的租户信息" });
}
if (string.IsNullOrWhiteSpace(notification.ClassId) || string.IsNullOrWhiteSpace(notification.Message))
{
return BadRequest(new { success = false, message = "班级编号与通知内容不可为空" });
}
// 2. Multi-tenant Scope Validation: Ensure target classroom exists in teacher's tenant!
var classroom = await _securityService.GetClassroomAsync(teacherTenantId, notification.ClassId);
if (classroom == null)
{
_logger.LogWarning("Cross-tenant attempt or invalid class: Teacher {TeacherId} (Tenant: {TenantId}) tried to notify Class {ClassId}",
teacherId, teacherTenantId, notification.ClassId);
return StatusCode(403, new { success = false, message = "无权访问该班级,或班级不属于当前学校" });
}
// 3. Stamp metadata & Business TTL Policy
notification.Id = $"msg_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid().ToString("N")[..4]}";
notification.TenantId = teacherTenantId;
notification.CreatedAt = DateTimeOffset.UtcNow;
if (notification.ExpiresAt.HasValue)
{
if (notification.ExpiresAt.Value <= notification.CreatedAt)
{
return BadRequest(new { success = false, message = "消息过期时间必须在创建时间之后" });
}
// Max TTL cap: 7 days
var maxExpiresAt = notification.CreatedAt.AddDays(7);
if (notification.ExpiresAt.Value > maxExpiresAt)
{
notification.ExpiresAt = maxExpiresAt;
}
}
else
{
// Default TTL based on NotificationType urgency
notification.ExpiresAt = notification.Type switch
{
ClassNotify.Shared.Enums.NotificationType.Call => notification.CreatedAt.AddMinutes(10),
ClassNotify.Shared.Enums.NotificationType.Notice => notification.CreatedAt.AddMinutes(60),
ClassNotify.Shared.Enums.NotificationType.Urgent => notification.CreatedAt.AddHours(24),
_ => notification.CreatedAt.AddMinutes(15)
};
}
await _securityService.RecordNotificationAsync(notification, teacherId, teacherName);
_logger.LogInformation("Teacher {TeacherName} ({TenantId}) sending notification to {ClassName} ({ClassId}): {Message}",
teacherName, teacherTenantId, classroom.DisplayName, classroom.Id, notification.Message);
// 4. Send to tenant-isolated SignalR classroom group
var tenantClassGroup = $"t:{teacherTenantId}:c:{notification.ClassId}";
await _deviceHubContext.Clients.Group(tenantClassGroup).ReceiveNotification(notification);
// 5. Broadcast only to teachers of THIS tenant
var tenantTeacherGroup = $"t:{teacherTenantId}:teachers";
await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnNewNotificationBroadcast(notification);
return Ok(new
{
success = true,
messageId = notification.Id,
tenantId = teacherTenantId,
classId = notification.ClassId,
className = classroom.DisplayName,
message = "通知已成功下发至教室大屏"
});
}
///
/// 获取当前教师所在学校的班级列表
///
[HttpGet("classes")]
public async Task GetTeacherClasses()
{
var tenantId = User.FindFirst("tenant_id")?.Value;
if (string.IsNullOrEmpty(tenantId)) return Unauthorized();
var classes = await _securityService.GetClassroomsAsync(tenantId);
return Ok(classes);
}
///
/// 获取当前教师所在学校的历史通知记录与回执
///
[HttpGet("history")]
public async Task GetNotificationHistory([FromQuery] string? classId, [FromQuery] int limit = 50)
{
var tenantId = User.FindFirst("tenant_id")?.Value;
if (string.IsNullOrEmpty(tenantId)) return Unauthorized();
var list = await _securityService.GetNotificationsAsync(tenantId, classId, limit);
return Ok(list);
}
///
/// 查看指定通知在指定教室设备的视觉回执现场画面 (受权限保护的短效 JPEG)
///
[HttpGet("{notificationId}/receipts/{deviceId}/visual-receipt")]
[HttpGet("/api/notifications/{notificationId}/receipts/{deviceId}/visual-receipt")]
public async Task GetVisualReceipt(string notificationId, string deviceId)
{
var result = await _visualReceiptService.GetVisualReceiptFileAsync(notificationId, deviceId, User);
if (!result.Success)
{
return StatusCode(result.StatusCode, new { success = false, message = result.ErrorMessage });
}
Response.Headers["Cache-Control"] = "private, no-store, max-age=0";
Response.Headers["Pragma"] = "no-cache";
Response.Headers["X-Content-Type-Options"] = "nosniff";
return PhysicalFile(result.FilePath!, "image/jpeg");
}
///
/// 撤回/提前关闭正在显示的通知
///
[HttpPost("{id}/cancel")]
[HttpPost("/api/notifications/{id}/cancel")]
public async Task CancelNotification(string id, CancellationToken ct)
{
var tenantId = User.FindFirst("tenant_id")?.Value;
var userName = User.FindFirst(ClaimTypes.Name)?.Value ?? "未知操作者";
var userRole = User.FindFirst(ClaimTypes.Role)?.Value ?? "Teacher";
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "";
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
if (string.IsNullOrEmpty(tenantId)) return Unauthorized();
CancelNotificationResult result;
try
{
result = await _securityService.CancelNotificationAsync(
id,
userId,
userName,
userRole,
tenantId,
ip,
ct);
}
catch (KeyNotFoundException ex)
{
return NotFound(new { success = false, message = ex.Message });
}
catch (UnauthorizedAccessException ex)
{
return StatusCode(403, new { success = false, message = ex.Message });
}
bool devicePushOk = true;
bool teacherPushOk = true;
if (!string.IsNullOrEmpty(result.ClassroomId))
{
try
{
var tenantClassGroup = $"t:{result.TenantId}:c:{result.ClassroomId}";
await _deviceHubContext.Clients.Group(tenantClassGroup).CancelNotification(id);
}
catch (Exception ex)
{
devicePushOk = false;
_logger.LogError(ex, "Failed to broadcast CancelNotification to device group for {NotificationId}", id);
}
}
try
{
var tenantTeacherGroup = $"t:{result.TenantId}:teachers";
await _teacherHubContext.Clients.Group(tenantTeacherGroup).OnNotificationCancelled(id);
}
catch (Exception ex)
{
teacherPushOk = false;
_logger.LogError(ex, "Failed to broadcast OnNotificationCancelled to teacher group for {NotificationId}", id);
}
return Ok(new
{
success = true,
notificationId = id,
alreadyCancelled = result.AlreadyCancelled,
cancelledAt = result.CancelledAt,
realtimeDeviceCloseSent = devicePushOk,
realtimeTeacherUpdateSent = teacherPushOk,
message = result.AlreadyCancelled
? "通知此前已被撤回"
: devicePushOk
? "通知已成功撤回并请求大屏立即关闭"
: "通知已撤回;实时关闭信令部分失败,但该通知不会再次补发"
});
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Controllers/SchoolAdminController.cs
SIZE: 9359 chars
SHA256: F3CD1C6506E2B00D62D8D81C215565E12AE018A89813BD7D2E01032EF5A52FC9
===================================================================== */
using System.Security.Claims;
using ClassNotify.Server.Services;
using ClassNotify.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
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 = "班级编号与班级名称不可为空" });
}
var ok = await _securityService.CreateClassroomAsync(tenantId, dto);
if (!ok)
{
return BadRequest(new { success = false, message = $"班级编号 {dto.Id} 已存在" });
}
return Ok(new { success = true, 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}/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)
{
var tenantId = GetTenantId();
if (string.IsNullOrEmpty(tenantId)) return Unauthorized();
if (string.IsNullOrWhiteSpace(classId))
{
return BadRequest(new { success = false, message = "班级编号不可为空" });
}
var classroom = await _securityService.GetClassroomAsync(tenantId, classId);
if (classroom == null)
{
return NotFound(new { success = false, message = $"班级 {classId} 不存在或不属于该学校" });
}
try
{
var code = await _securityService.GenerateActivationCodeAsync(tenantId, classId);
return Ok(new
{
success = true,
code,
tenantId,
classId,
message = "激活码生成成功"
});
}
catch (Exception ex)
{
return BadRequest(new { success = false, message = ex.Message });
}
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/ClassNotifyDbContext.cs
SIZE: 9036 chars
SHA256: D1E4022F664EE439A42AA256751754B1CE1E084A836D6FB6EE3A7DE9FD68823E
===================================================================== */
using ClassNotify.Server.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace ClassNotify.Server.Data;
public class ClassNotifyDbContext : DbContext
{
public ClassNotifyDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet Tenants => Set();
public DbSet Classrooms => Set();
public DbSet Users => Set();
public DbSet Devices => Set();
public DbSet DeviceCredentials => Set();
public DbSet ActivationCodes => Set();
public DbSet Notifications => Set();
public DbSet NotificationReceipts => Set();
public DbSet MigrationMarkers => Set();
public DbSet DeviceCommands => Set();
public DbSet AdminAuditEvents => Set();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 1. Tenant
modelBuilder.Entity(entity =>
{
entity.HasKey(t => t.Id);
entity.Property(t => t.Name).IsRequired().HasMaxLength(200);
});
// 2. Classroom (Composite key for multi-tenant isolation)
modelBuilder.Entity(entity =>
{
entity.HasKey(c => new { c.TenantId, c.Id });
entity.Property(c => c.DisplayName).IsRequired().HasMaxLength(100);
entity.Property(c => c.Grade).HasMaxLength(50);
entity.Property(c => c.RoomNumber).HasMaxLength(50);
entity.HasOne(c => c.Tenant)
.WithMany(t => t.Classrooms)
.HasForeignKey(c => c.TenantId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasIndex(c => new { c.TenantId, c.Id });
});
// 3. User
modelBuilder.Entity(entity =>
{
entity.HasKey(u => u.Id);
entity.Property(u => u.Username).IsRequired().HasMaxLength(100);
entity.Property(u => u.PasswordHash).IsRequired();
entity.Property(u => u.FullName).IsRequired().HasMaxLength(100);
entity.Property(u => u.Role).IsRequired().HasMaxLength(50);
entity.HasIndex(u => u.Username).IsUnique();
entity.HasIndex(u => u.TenantId);
entity.HasOne(u => u.Tenant)
.WithMany(t => t.Users)
.HasForeignKey(u => u.TenantId)
.OnDelete(DeleteBehavior.Restrict);
});
// 4. Device
modelBuilder.Entity(entity =>
{
entity.HasKey(d => d.Id);
entity.Property(d => d.DeviceTokenHash).IsRequired();
entity.Property(d => d.InstallationId).HasMaxLength(100);
entity.Property(d => d.Hostname).HasMaxLength(200);
entity.HasIndex(d => d.Id).IsUnique();
entity.HasIndex(d => d.InstallationId).IsUnique().HasFilter("\"InstallationId\" IS NOT NULL");
entity.HasIndex(d => new { d.TenantId, d.ClassroomId });
entity.HasIndex(d => d.TenantId);
entity.HasOne(d => d.Tenant)
.WithMany(t => t.Devices)
.HasForeignKey(d => d.TenantId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne(d => d.Classroom)
.WithMany(c => c.Devices)
.HasForeignKey(d => new { d.TenantId, d.ClassroomId })
.OnDelete(DeleteBehavior.Restrict);
});
// 5. DeviceCredentialRecord
modelBuilder.Entity(entity =>
{
entity.HasKey(c => c.DeviceId);
entity.Property(c => c.InstallationId).IsRequired().HasMaxLength(100);
entity.Property(c => c.DeviceTokenHash).IsRequired();
entity.Property(c => c.EncryptedRecoverableToken).IsRequired();
entity.HasIndex(c => c.DeviceId).IsUnique();
entity.HasIndex(c => c.InstallationId).IsUnique();
});
// 6. ActivationCode
modelBuilder.Entity(entity =>
{
entity.HasKey(a => a.Code);
entity.Property(a => a.Code).HasMaxLength(50);
entity.Property(a => a.ClassroomId).IsRequired().HasMaxLength(50);
entity.Property(a => a.InstallationId).HasMaxLength(100);
entity.HasIndex(a => a.Code).IsUnique();
entity.HasIndex(a => a.TenantId);
entity.HasIndex(a => a.ClassroomId);
entity.HasIndex(a => a.InstallationId);
entity.HasOne(a => a.Tenant)
.WithMany(t => t.ActivationCodes)
.HasForeignKey(a => a.TenantId)
.OnDelete(DeleteBehavior.Restrict);
});
// 7. Notification
modelBuilder.Entity(entity =>
{
entity.HasKey(n => n.Id);
entity.Property(n => n.Id).HasMaxLength(100);
entity.Property(n => n.ClassroomId).IsRequired().HasMaxLength(50);
entity.Property(n => n.SenderName).IsRequired().HasMaxLength(100);
entity.Property(n => n.Message).IsRequired();
entity.Property(n => n.Title).IsRequired().HasMaxLength(200);
entity.Property(n => n.Priority).IsRequired().HasMaxLength(50);
entity.HasIndex(n => new { n.TenantId, n.CreatedAt }).IsDescending(false, true);
entity.HasIndex(n => new { n.ClassroomId, n.CreatedAt }).IsDescending(false, true);
entity.HasIndex(n => new { n.TenantId, n.ClassroomId, n.ExpiresAt });
entity.HasOne(n => n.Tenant)
.WithMany(t => t.Notifications)
.HasForeignKey(n => n.TenantId)
.OnDelete(DeleteBehavior.Cascade);
});
// 8. NotificationReceipt (per-device ACK state isolation)
modelBuilder.Entity(entity =>
{
entity.HasKey(r => r.Id);
entity.Property(r => r.Id).HasMaxLength(100);
entity.Property(r => r.NotificationId).IsRequired().HasMaxLength(100);
entity.Property(r => r.DeviceId).IsRequired().HasMaxLength(100);
entity.Property(r => r.Status).IsRequired().HasMaxLength(50);
entity.Property(r => r.FailureReason).HasMaxLength(500);
entity.Property(r => r.VisualReceiptState).IsRequired().HasMaxLength(32).HasDefaultValue("None");
entity.Property(r => r.VisualReceiptPath).HasMaxLength(500);
entity.Property(r => r.VisualReceiptSha256).HasMaxLength(64);
entity.HasIndex(r => new { r.NotificationId, r.DeviceId }).IsUnique();
entity.HasIndex(r => new { r.DeviceId, r.UpdatedAt }).IsDescending(false, true);
entity.HasIndex(r => new { r.DeviceId, r.Status });
entity.HasIndex(r => r.VisualReceiptExpiresAt);
entity.HasOne(r => r.Notification)
.WithMany(n => n.Receipts)
.HasForeignKey(r => r.NotificationId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(r => r.Device)
.WithMany(d => d.Receipts)
.HasForeignKey(r => r.DeviceId)
.OnDelete(DeleteBehavior.Cascade);
});
// 9. MigrationMarker
modelBuilder.Entity(entity =>
{
entity.HasKey(m => m.Id);
entity.Property(m => m.Id).HasMaxLength(100);
});
// 10. DeviceCommand
modelBuilder.Entity(entity =>
{
entity.HasKey(c => c.Id);
entity.Property(c => c.Id).HasMaxLength(100);
entity.Property(c => c.TenantId).IsRequired().HasMaxLength(100);
entity.Property(c => c.DeviceId).IsRequired().HasMaxLength(100);
entity.Property(c => c.CommandType).IsRequired().HasMaxLength(50);
entity.Property(c => c.CreatedBy).IsRequired().HasMaxLength(100);
entity.Property(c => c.Status).IsRequired().HasMaxLength(50);
entity.Property(c => c.DurationMs);
entity.Property(c => c.ResultMessage).HasMaxLength(1000);
entity.HasIndex(c => new { c.TenantId, c.DeviceId, c.CreatedAt }).IsDescending(false, false, true);
entity.HasIndex(c => new { c.DeviceId, c.Status });
entity.HasIndex(c => new { c.Status, c.ExpiresAt });
entity.HasOne(c => c.Tenant)
.WithMany()
.HasForeignKey(c => c.TenantId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(c => c.Device)
.WithMany()
.HasForeignKey(c => c.DeviceId)
.OnDelete(DeleteBehavior.Cascade);
});
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/ClassNotifyDbContextFactory.cs
SIZE: 874 chars
SHA256: 2BE10071544EF5D652C1776174492E92BE79FFDE57B84802F292447B17D7D7E1
===================================================================== */
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace ClassNotify.Server.Data;
public class ClassNotifyDbContextFactory : IDesignTimeDbContextFactory
{
public ClassNotifyDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder();
// Default local/development connection string for migrations design-time
// Note: Real production connection strings are loaded via EnvironmentFile on the VPS
var connStr = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection")
?? "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=CHANGEME_DEV;";
optionsBuilder.UseNpgsql(connStr);
return new ClassNotifyDbContext(optionsBuilder.Options);
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/DbInitializer.cs
SIZE: 5297 chars
SHA256: 3CEB6AA53B59A906CA47669BFF68AB1801F5629CBF34B14466BF6F68F80E2E2D
===================================================================== */
using System.Security.Cryptography;
using System.Text;
using ClassNotify.Server.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace ClassNotify.Server.Data;
public static class DbInitializer
{
public static async Task InitializeAsync(ClassNotifyDbContext dbContext, IHostEnvironment env, IConfiguration config, ILogger logger)
{
// 1. Always ensure 'global' tenant exists for SuperAdmin users
if (!await dbContext.Tenants.AnyAsync(t => t.Id == "global"))
{
dbContext.Tenants.Add(new Tenant
{
Id = "global",
Name = "全局平台管理",
IsActive = true,
CreatedAt = DateTimeOffset.UtcNow
});
await dbContext.SaveChangesAsync();
}
// 2. HARD PRODUCTION SEED GUARD:
// In Production environment, NEVER allow development seeding under any circumstances,
// even if SeedDevelopmentData is erroneously set to true in configuration.
if (env.IsProduction())
{
if (config.GetValue("SeedDevelopmentData"))
{
logger.LogWarning("SECURITY ALERT: SeedDevelopmentData=true was configured in Production environment! Hard guard engaged: development seeding is strictly prohibited in Production.");
}
logger.LogInformation("Production environment: Development seeding is strictly prohibited. Skipping.");
return;
}
// Only seed sample schools/classes/devices in non-production development environments
bool seedDevData = config.GetValue("SeedDevelopmentData") || env.IsDevelopment();
if (!seedDevData)
{
logger.LogInformation("Skipping development data seeding.");
return;
}
// If tenants other than 'global' already exist, skip development seed
if (await dbContext.Tenants.AnyAsync(t => t.Id != "global"))
{
return;
}
logger.LogInformation("Seeding initial development tenants, classrooms, users, and activation codes...");
// Development Tenants
var t1 = new Tenant { Id = "t_beijing_no4", Name = "北京四中", IsActive = true, CreatedAt = DateTimeOffset.UtcNow };
var t2 = new Tenant { Id = "t_shanghai_high", Name = "上海实验学校", IsActive = true, CreatedAt = DateTimeOffset.UtcNow };
dbContext.Tenants.AddRange(t1, t2);
// Development Classrooms
var c1 = new Classroom { Id = "cls_801", TenantId = "t_beijing_no4", DisplayName = "八年级(1)班", Grade = "初二", RoomNumber = "综合楼301" };
var c2 = new Classroom { Id = "cls_802", TenantId = "t_beijing_no4", DisplayName = "八年级(2)班", Grade = "初二", RoomNumber = "综合楼302" };
var c3 = new Classroom { Id = "cls_801", TenantId = "t_shanghai_high", DisplayName = "高一(1)班", Grade = "高一", RoomNumber = "实验楼101" };
dbContext.Classrooms.AddRange(c1, c2, c3);
// Development Users
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher();
var uSuper = new User { Id = "usr_super", TenantId = "global", Username = "admin", FullName = "超级管理员", Role = "SuperAdmin" };
uSuper.PasswordHash = hasher.HashPassword(uSuper, "admin888");
var uAdminBj = new User { Id = "usr_admin_bj", TenantId = "t_beijing_no4", Username = "admin_bj4", FullName = "北京四中管理员", Role = "SchoolAdmin" };
uAdminBj.PasswordHash = hasher.HashPassword(uAdminBj, "admin123");
var uAdminSh = new User { Id = "usr_admin_sh", TenantId = "t_shanghai_high", Username = "admin_sh", FullName = "上海实验管理员", Role = "SchoolAdmin" };
uAdminSh.PasswordHash = hasher.HashPassword(uAdminSh, "admin123");
var u101 = new User { Id = "usr_101", TenantId = "t_beijing_no4", Username = "teacher_zhang", FullName = "张老师", Role = "Teacher" };
u101.PasswordHash = hasher.HashPassword(u101, "teacher123");
var u201 = new User { Id = "usr_201", TenantId = "t_shanghai_high", Username = "teacher_li", FullName = "李老师", Role = "Teacher" };
u201.PasswordHash = hasher.HashPassword(u201, "teacher123");
dbContext.Users.AddRange(uSuper, uAdminBj, uAdminSh, u101, u201);
// Development Activation Codes
dbContext.ActivationCodes.AddRange(
new ActivationCode { Code = "TEST-2026", TenantId = "t_beijing_no4", ClassroomId = "cls_801", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false },
new ActivationCode { Code = "BJ81-2026", TenantId = "t_beijing_no4", ClassroomId = "cls_801", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false },
new ActivationCode { Code = "BJ82-2026", TenantId = "t_beijing_no4", ClassroomId = "cls_802", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false },
new ActivationCode { Code = "BJ81-DEMO", TenantId = "t_beijing_no4", ClassroomId = "cls_801", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false },
new ActivationCode { Code = "SH01-2026", TenantId = "t_shanghai_high", ClassroomId = "cls_801", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30), IsUsed = false }
);
await dbContext.SaveChangesAsync();
logger.LogInformation("Development seed completed successfully.");
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/JsonMigrationService.cs
SIZE: 14495 chars
SHA256: 5094565BB6FCD1D33B83469E72A8C6627BA7FBE5A391B22A1BBDAD8B2962F0C3
===================================================================== */
using System.Text.Json;
using ClassNotify.Server.Domain.Entities;
using ClassNotify.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace ClassNotify.Server.Data;
public class JsonMigrationResult
{
public bool Migrated { get; set; }
public string? BackupPath { get; set; }
public int TenantsCount { get; set; }
public int ClassroomsCount { get; set; }
public int UsersCount { get; set; }
public int DevicesCount { get; set; }
public int CredentialsCount { get; set; }
public int ActivationCodesCount { get; set; }
public int NotificationsCount { get; set; }
}
public static class JsonMigrationService
{
public static async Task MigrateAsync(ClassNotifyDbContext dbContext, string? dataDirectory, ILogger logger)
{
var result = new JsonMigrationResult();
var marker = await dbContext.MigrationMarkers.FindAsync("JsonMigration_v1");
if (marker != null)
{
logger.LogInformation("JSON migration marker 'JsonMigration_v1' already exists (migrated at {MigratedAt}). Skipping migration.", marker.MigratedAt);
return result;
}
var dataDir = dataDirectory ?? Path.Combine(AppContext.BaseDirectory, "data");
if (!Directory.Exists(dataDir))
{
logger.LogInformation("No 'data' directory found at {DataDir}. Skipping JSON migration.", dataDir);
return result;
}
var tenantsFile = Path.Combine(dataDir, "tenants.json");
var classroomsFile = Path.Combine(dataDir, "classrooms.json");
var usersFile = Path.Combine(dataDir, "users.json");
var devicesFile = Path.Combine(dataDir, "devices.json");
var credsFile = Path.Combine(dataDir, "device_credentials.json");
var codesFile = Path.Combine(dataDir, "activation_codes.json");
var notifsFile = Path.Combine(dataDir, "notifications.json");
if (!File.Exists(tenantsFile) && !File.Exists(classroomsFile) && !File.Exists(usersFile) &&
!File.Exists(devicesFile) && !File.Exists(credsFile) && !File.Exists(codesFile) && !File.Exists(notifsFile))
{
logger.LogInformation("No legacy JSON data files found in {DataDir}. Skipping JSON migration.", dataDir);
return result;
}
logger.LogInformation("Starting one-time legacy JSON to PostgreSQL transactional migration from {DataDir}...", dataDir);
using var tx = await dbContext.Database.BeginTransactionAsync();
try
{
// 1. Tenants
var tenantDict = new Dictionary();
if (!await dbContext.Tenants.AnyAsync(t => t.Id == "global"))
{
var globalTenant = new Tenant { Id = "global", Name = "全局平台管理", IsActive = true, CreatedAt = DateTimeOffset.UtcNow };
dbContext.Tenants.Add(globalTenant);
tenantDict["global"] = globalTenant;
}
if (File.Exists(tenantsFile))
{
var json = await File.ReadAllTextAsync(tenantsFile);
var tenants = JsonSerializer.Deserialize>(json) ?? new();
foreach (var t in tenants)
{
if (!await dbContext.Tenants.AnyAsync(existing => existing.Id == t.Id) && !tenantDict.ContainsKey(t.Id))
{
dbContext.Tenants.Add(t);
tenantDict[t.Id] = t;
result.TenantsCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 2. Classrooms
if (File.Exists(classroomsFile))
{
var json = await File.ReadAllTextAsync(classroomsFile);
var classrooms = JsonSerializer.Deserialize>(json) ?? new();
foreach (var c in classrooms)
{
if (!await dbContext.Classrooms.AnyAsync(existing => existing.TenantId == c.TenantId && existing.Id == c.Id))
{
dbContext.Classrooms.Add(c);
result.ClassroomsCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 3. Users
if (File.Exists(usersFile))
{
var json = await File.ReadAllTextAsync(usersFile);
var users = JsonSerializer.Deserialize>(json) ?? new();
foreach (var u in users)
{
if (!await dbContext.Users.AnyAsync(existing => existing.Username == u.Username))
{
// Ensure tenant exists
if (!string.IsNullOrEmpty(u.TenantId) && !await dbContext.Tenants.AnyAsync(t => t.Id == u.TenantId))
{
var newTenant = new Tenant { Id = u.TenantId, Name = u.TenantId, IsActive = true, CreatedAt = DateTimeOffset.UtcNow };
dbContext.Tenants.Add(newTenant);
await dbContext.SaveChangesAsync();
}
dbContext.Users.Add(u);
result.UsersCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 4. Devices
var migratedDevices = new List();
if (File.Exists(devicesFile))
{
var json = await File.ReadAllTextAsync(devicesFile);
var devices = JsonSerializer.Deserialize>(json) ?? new();
var usedInstallationIds = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var d in devices)
{
if (!await dbContext.Devices.AnyAsync(existing => existing.Id == d.Id))
{
// Ensure tenant and classroom exist
if (!await dbContext.Tenants.AnyAsync(t => t.Id == d.TenantId))
{
dbContext.Tenants.Add(new Tenant { Id = d.TenantId, Name = d.TenantId, IsActive = true, CreatedAt = DateTimeOffset.UtcNow });
await dbContext.SaveChangesAsync();
}
if (!await dbContext.Classrooms.AnyAsync(c => c.TenantId == d.TenantId && c.Id == d.ClassroomId))
{
dbContext.Classrooms.Add(new Classroom { TenantId = d.TenantId, Id = d.ClassroomId, DisplayName = d.ClassroomId });
await dbContext.SaveChangesAsync();
}
// Handle legacy duplicate InstallationId gracefully
if (!string.IsNullOrEmpty(d.InstallationId))
{
if (usedInstallationIds.Contains(d.InstallationId) ||
await dbContext.Devices.AnyAsync(existing => existing.InstallationId == d.InstallationId))
{
logger.LogWarning("Legacy duplicate InstallationId {InstId} detected for Device {DeviceId}. Renaming for unique constraint.",
d.InstallationId, d.Id);
d.InstallationId = $"{d.InstallationId}_dup_{d.Id}";
}
usedInstallationIds.Add(d.InstallationId);
}
dbContext.Devices.Add(d);
migratedDevices.Add(d);
result.DevicesCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 5. Device Credentials
if (File.Exists(credsFile))
{
var json = await File.ReadAllTextAsync(credsFile);
var creds = JsonSerializer.Deserialize>(json) ?? new();
var usedCredInstIds = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var c in creds)
{
if (!await dbContext.DeviceCredentials.AnyAsync(existing => existing.DeviceId == c.DeviceId))
{
if (!string.IsNullOrEmpty(c.InstallationId))
{
if (usedCredInstIds.Contains(c.InstallationId) ||
await dbContext.DeviceCredentials.AnyAsync(existing => existing.InstallationId == c.InstallationId))
{
c.InstallationId = $"{c.InstallationId}_dup_{c.DeviceId}";
}
usedCredInstIds.Add(c.InstallationId);
}
dbContext.DeviceCredentials.Add(c);
result.CredentialsCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 6. Activation Codes
if (File.Exists(codesFile))
{
var json = await File.ReadAllTextAsync(codesFile);
var codes = JsonSerializer.Deserialize>(json) ?? new();
foreach (var a in codes)
{
if (!await dbContext.ActivationCodes.AnyAsync(existing => existing.Code == a.Code))
{
if (!await dbContext.Tenants.AnyAsync(t => t.Id == a.TenantId))
{
dbContext.Tenants.Add(new Tenant { Id = a.TenantId, Name = a.TenantId, IsActive = true, CreatedAt = DateTimeOffset.UtcNow });
await dbContext.SaveChangesAsync();
}
dbContext.ActivationCodes.Add(a);
result.ActivationCodesCount++;
}
}
await dbContext.SaveChangesAsync();
}
// 7. Notifications
if (File.Exists(notifsFile))
{
var json = await File.ReadAllTextAsync(notifsFile);
var notifDtos = JsonSerializer.Deserialize>(json) ?? new();
var allDevices = await dbContext.Devices.ToListAsync();
foreach (var n in notifDtos)
{
if (!await dbContext.Notifications.AnyAsync(existing => existing.Id == n.Id))
{
var notifEntity = new Notification
{
Id = n.Id,
TenantId = n.TenantId,
ClassroomId = n.ClassId,
SenderName = string.IsNullOrWhiteSpace(n.SenderName) ? "系统" : n.SenderName,
Message = n.Message,
Title = "🔔 老师呼叫",
Priority = string.IsNullOrWhiteSpace(n.Priority) ? "Normal" : n.Priority,
CreatedAt = n.CreatedAt
};
dbContext.Notifications.Add(notifEntity);
result.NotificationsCount++;
// Associate receipt if device exists in classroom
var targetDev = allDevices.FirstOrDefault(d => d.TenantId == n.TenantId && d.ClassroomId == n.ClassId);
if (targetDev != null)
{
var receipt = new NotificationReceipt
{
Id = $"rcpt_{Guid.NewGuid():N}",
NotificationId = n.Id,
DeviceId = targetDev.Id,
Status = string.IsNullOrWhiteSpace(n.Status) ? "Sent" : n.Status,
DeviceReceivedAt = n.CreatedAt,
DisplayedAt = n.CreatedAt,
AcknowledgedAt = n.ConfirmedAt,
UpdatedAt = n.ConfirmedAt ?? n.CreatedAt
};
dbContext.NotificationReceipts.Add(receipt);
}
}
}
await dbContext.SaveChangesAsync();
}
// Write Migration Marker
var markerRecord = new MigrationMarker
{
Id = "JsonMigration_v1",
MigratedAt = DateTimeOffset.UtcNow,
Details = $"Successfully migrated Tenants={result.TenantsCount}, Classrooms={result.ClassroomsCount}, Users={result.UsersCount}, Devices={result.DevicesCount}, Credentials={result.CredentialsCount}, Codes={result.ActivationCodesCount}, Notifications={result.NotificationsCount}."
};
dbContext.MigrationMarkers.Add(markerRecord);
await dbContext.SaveChangesAsync();
await tx.CommitAsync();
result.Migrated = true;
logger.LogInformation("JSON to PostgreSQL transaction committed successfully: {Details}", markerRecord.Details);
// Move legacy JSON files to data/json-backup-YYYYMMDD-HHmmss/
var backupDir = Path.Combine(dataDir, $"json-backup-{DateTime.UtcNow:yyyyMMdd-HHmmss}");
Directory.CreateDirectory(backupDir);
result.BackupPath = backupDir;
string[] jsonFiles = { tenantsFile, classroomsFile, usersFile, devicesFile, credsFile, codesFile, notifsFile };
foreach (var file in jsonFiles)
{
if (File.Exists(file))
{
var dest = Path.Combine(backupDir, Path.GetFileName(file));
File.Move(file, dest, overwrite: true);
}
}
logger.LogInformation("Legacy JSON files safely moved to backup directory: {BackupDir}", backupDir);
return result;
}
catch (Exception ex)
{
await tx.RollbackAsync();
logger.LogError(ex, "FATAL: JSON to PostgreSQL migration failed. Transaction rolled back, legacy JSON files preserved.");
throw;
}
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/Migrations/20260920225928_InitialPostgreSql.cs
SIZE: 16966 chars
SHA256: 6B86292AF4D316E6FD6E66D06E07D52AA1845A48759D81E47A69DDA3602CF4A6
===================================================================== */
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ClassNotify.Server.Data.Migrations
{
///
public partial class InitialPostgreSql : Migration
{
///
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DeviceCredentials",
columns: table => new
{
DeviceId = table.Column(type: "text", nullable: false),
InstallationId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
DeviceTokenHash = table.Column(type: "text", nullable: false),
EncryptedRecoverableToken = table.Column(type: "text", nullable: false),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false),
RotatedAt = table.Column(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DeviceCredentials", x => x.DeviceId);
});
migrationBuilder.CreateTable(
name: "MigrationMarkers",
columns: table => new
{
Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
MigratedAt = table.Column(type: "timestamp with time zone", nullable: false),
Details = table.Column(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_MigrationMarkers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Tenants",
columns: table => new
{
Id = table.Column(type: "text", nullable: false),
Name = table.Column(type: "character varying(200)", maxLength: 200, nullable: false),
IsActive = table.Column(type: "boolean", nullable: false),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Tenants", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ActivationCodes",
columns: table => new
{
Code = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
TenantId = table.Column(type: "text", nullable: false),
ClassroomId = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
ExpiresAt = table.Column(type: "timestamp with time zone", nullable: false),
IsUsed = table.Column(type: "boolean", nullable: false),
UsedAt = table.Column(type: "timestamp with time zone", nullable: true),
UsedByDeviceId = table.Column(type: "text", nullable: true),
InstallationId = table.Column(type: "character varying(100)", maxLength: 100, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ActivationCodes", x => x.Code);
table.ForeignKey(
name: "FK_ActivationCodes_Tenants_TenantId",
column: x => x.TenantId,
principalTable: "Tenants",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Classrooms",
columns: table => new
{
Id = table.Column(type: "text", nullable: false),
TenantId = table.Column(type: "text", nullable: false),
DisplayName = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
Grade = table.Column(type: "character varying(50)", maxLength: 50, nullable: true),
RoomNumber = table.Column(type: "character varying(50)", maxLength: 50, nullable: true),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Classrooms", x => new { x.TenantId, x.Id });
table.ForeignKey(
name: "FK_Classrooms_Tenants_TenantId",
column: x => x.TenantId,
principalTable: "Tenants",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Notifications",
columns: table => new
{
Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
TenantId = table.Column(type: "text", nullable: false),
ClassroomId = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
SenderUserId = table.Column(type: "text", nullable: true),
SenderName = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
Message = table.Column(type: "text", nullable: false),
Title = table.Column(type: "character varying(200)", maxLength: 200, nullable: false),
Priority = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Notifications", x => x.Id);
table.ForeignKey(
name: "FK_Notifications_Tenants_TenantId",
column: x => x.TenantId,
principalTable: "Tenants",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column(type: "text", nullable: false),
TenantId = table.Column(type: "text", nullable: false),
Username = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
PasswordHash = table.Column(type: "text", nullable: false),
FullName = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
Role = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
table.ForeignKey(
name: "FK_Users_Tenants_TenantId",
column: x => x.TenantId,
principalTable: "Tenants",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Devices",
columns: table => new
{
Id = table.Column(type: "text", nullable: false),
TenantId = table.Column(type: "text", nullable: false),
ClassroomId = table.Column(type: "text", nullable: false),
DeviceTokenHash = table.Column(type: "text", nullable: false),
RawDeviceToken = table.Column(type: "text", nullable: true),
InstallationId = table.Column(type: "character varying(100)", maxLength: 100, nullable: true),
Hostname = table.Column(type: "character varying(200)", maxLength: 200, nullable: true),
IsActive = table.Column(type: "boolean", nullable: false),
CreatedAt = table.Column(type: "timestamp with time zone", nullable: false),
LastHeartbeatAt = table.Column(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Devices", x => x.Id);
table.ForeignKey(
name: "FK_Devices_Classrooms_TenantId_ClassroomId",
columns: x => new { x.TenantId, x.ClassroomId },
principalTable: "Classrooms",
principalColumns: new[] { "TenantId", "Id" },
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Devices_Tenants_TenantId",
column: x => x.TenantId,
principalTable: "Tenants",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "NotificationReceipts",
columns: table => new
{
Id = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
NotificationId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
DeviceId = table.Column(type: "character varying(100)", maxLength: 100, nullable: false),
Status = table.Column(type: "character varying(50)", maxLength: 50, nullable: false),
DeviceReceivedAt = table.Column(type: "timestamp with time zone", nullable: true),
DisplayedAt = table.Column(type: "timestamp with time zone", nullable: true),
AcknowledgedAt = table.Column(type: "timestamp with time zone", nullable: true),
FailedAt = table.Column(type: "timestamp with time zone", nullable: true),
FailureReason = table.Column(type: "character varying(500)", maxLength: 500, nullable: true),
UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NotificationReceipts", x => x.Id);
table.ForeignKey(
name: "FK_NotificationReceipts_Devices_DeviceId",
column: x => x.DeviceId,
principalTable: "Devices",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_NotificationReceipts_Notifications_NotificationId",
column: x => x.NotificationId,
principalTable: "Notifications",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ActivationCodes_ClassroomId",
table: "ActivationCodes",
column: "ClassroomId");
migrationBuilder.CreateIndex(
name: "IX_ActivationCodes_Code",
table: "ActivationCodes",
column: "Code",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ActivationCodes_InstallationId",
table: "ActivationCodes",
column: "InstallationId");
migrationBuilder.CreateIndex(
name: "IX_ActivationCodes_TenantId",
table: "ActivationCodes",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "IX_Classrooms_TenantId_Id",
table: "Classrooms",
columns: new[] { "TenantId", "Id" });
migrationBuilder.CreateIndex(
name: "IX_DeviceCredentials_DeviceId",
table: "DeviceCredentials",
column: "DeviceId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_DeviceCredentials_InstallationId",
table: "DeviceCredentials",
column: "InstallationId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Devices_Id",
table: "Devices",
column: "Id",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Devices_InstallationId",
table: "Devices",
column: "InstallationId",
unique: true,
filter: "\"InstallationId\" IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Devices_TenantId",
table: "Devices",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "IX_Devices_TenantId_ClassroomId",
table: "Devices",
columns: new[] { "TenantId", "ClassroomId" });
migrationBuilder.CreateIndex(
name: "IX_NotificationReceipts_DeviceId_UpdatedAt",
table: "NotificationReceipts",
columns: new[] { "DeviceId", "UpdatedAt" },
descending: new[] { false, true });
migrationBuilder.CreateIndex(
name: "IX_NotificationReceipts_NotificationId_DeviceId",
table: "NotificationReceipts",
columns: new[] { "NotificationId", "DeviceId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Notifications_ClassroomId_CreatedAt",
table: "Notifications",
columns: new[] { "ClassroomId", "CreatedAt" },
descending: new[] { false, true });
migrationBuilder.CreateIndex(
name: "IX_Notifications_TenantId_CreatedAt",
table: "Notifications",
columns: new[] { "TenantId", "CreatedAt" },
descending: new[] { false, true });
migrationBuilder.CreateIndex(
name: "IX_Users_TenantId",
table: "Users",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "IX_Users_Username",
table: "Users",
column: "Username",
unique: true);
}
///
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ActivationCodes");
migrationBuilder.DropTable(
name: "DeviceCredentials");
migrationBuilder.DropTable(
name: "MigrationMarkers");
migrationBuilder.DropTable(
name: "NotificationReceipts");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "Devices");
migrationBuilder.DropTable(
name: "Notifications");
migrationBuilder.DropTable(
name: "Classrooms");
migrationBuilder.DropTable(
name: "Tenants");
}
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/Migrations/20260920225928_InitialPostgreSql.Designer.cs
SIZE: 18154 chars
SHA256: 5F471E0B59753E2DC1EA0658AA66928AEDB93E00C29B5534DDF13219B261A9AD
===================================================================== */
//
using System;
using ClassNotify.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ClassNotify.Server.Data.Migrations
{
[DbContext(typeof(ClassNotifyDbContext))]
[Migration("20260920225928_InitialPostgreSql")]
partial class InitialPostgreSql
{
///
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b =>
{
b.Property("Code")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("ClassroomId")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property("InstallationId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("IsUsed")
.HasColumnType("boolean");
b.Property("TenantId")
.IsRequired()
.HasColumnType("text");
b.Property("UsedAt")
.HasColumnType("timestamp with time zone");
b.Property("UsedByDeviceId")
.HasColumnType("text");
b.HasKey("Code");
b.HasIndex("ClassroomId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("InstallationId");
b.HasIndex("TenantId");
b.ToTable("ActivationCodes");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b =>
{
b.Property("TenantId")
.HasColumnType("text");
b.Property("Id")
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("Grade")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("RoomNumber")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.HasKey("TenantId", "Id");
b.HasIndex("TenantId", "Id");
b.ToTable("Classrooms");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b =>
{
b.Property("Id")
.HasColumnType("text");
b.Property("ClassroomId")
.IsRequired()
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("DeviceTokenHash")
.IsRequired()
.HasColumnType("text");
b.Property("Hostname")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property("InstallationId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("IsActive")
.HasColumnType("boolean");
b.Property("LastHeartbeatAt")
.HasColumnType("timestamp with time zone");
b.Property("RawDeviceToken")
.HasColumnType("text");
b.Property("TenantId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Id")
.IsUnique();
b.HasIndex("InstallationId")
.IsUnique()
.HasFilter("\"InstallationId\" IS NOT NULL");
b.HasIndex("TenantId");
b.HasIndex("TenantId", "ClassroomId");
b.ToTable("Devices");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.DeviceCredentialRecord", b =>
{
b.Property("DeviceId")
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("DeviceTokenHash")
.IsRequired()
.HasColumnType("text");
b.Property("EncryptedRecoverableToken")
.IsRequired()
.HasColumnType("text");
b.Property("InstallationId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("RotatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("DeviceId");
b.HasIndex("DeviceId")
.IsUnique();
b.HasIndex("InstallationId")
.IsUnique();
b.ToTable("DeviceCredentials");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.MigrationMarker", b =>
{
b.Property("Id")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("Details")
.HasColumnType("text");
b.Property("MigratedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.ToTable("MigrationMarkers");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b =>
{
b.Property("Id")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("ClassroomId")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("Message")
.IsRequired()
.HasColumnType("text");
b.Property("Priority")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("SenderName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("SenderUserId")
.HasColumnType("text");
b.Property("TenantId")
.IsRequired()
.HasColumnType("text");
b.Property("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.HasKey("Id");
b.HasIndex("ClassroomId", "CreatedAt")
.IsDescending(false, true);
b.HasIndex("TenantId", "CreatedAt")
.IsDescending(false, true);
b.ToTable("Notifications");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b =>
{
b.Property("Id")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("AcknowledgedAt")
.HasColumnType("timestamp with time zone");
b.Property("DeviceId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("DeviceReceivedAt")
.HasColumnType("timestamp with time zone");
b.Property("DisplayedAt")
.HasColumnType("timestamp with time zone");
b.Property("FailedAt")
.HasColumnType("timestamp with time zone");
b.Property("FailureReason")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property("NotificationId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("Status")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("DeviceId", "UpdatedAt")
.IsDescending(false, true);
b.HasIndex("NotificationId", "DeviceId")
.IsUnique();
b.ToTable("NotificationReceipts");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b =>
{
b.Property("Id")
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("IsActive")
.HasColumnType("boolean");
b.Property("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.HasKey("Id");
b.ToTable("Tenants");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b =>
{
b.Property("Id")
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property("FullName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property("Role")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("TenantId")
.IsRequired()
.HasColumnType("text");
b.Property("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.HasIndex("TenantId");
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant")
.WithMany("ActivationCodes")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Tenant");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant")
.WithMany("Classrooms")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Tenant");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant")
.WithMany("Devices")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("ClassNotify.Server.Domain.Entities.Classroom", "Classroom")
.WithMany("Devices")
.HasForeignKey("TenantId", "ClassroomId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Classroom");
b.Navigation("Tenant");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant")
.WithMany("Notifications")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Tenant");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.NotificationReceipt", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Device", "Device")
.WithMany("Receipts")
.HasForeignKey("DeviceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ClassNotify.Server.Domain.Entities.Notification", "Notification")
.WithMany("Receipts")
.HasForeignKey("NotificationId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Device");
b.Navigation("Notification");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.User", b =>
{
b.HasOne("ClassNotify.Server.Domain.Entities.Tenant", "Tenant")
.WithMany("Users")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Tenant");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b =>
{
b.Navigation("Devices");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Device", b =>
{
b.Navigation("Receipts");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Notification", b =>
{
b.Navigation("Receipts");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Tenant", b =>
{
b.Navigation("ActivationCodes");
b.Navigation("Classrooms");
b.Navigation("Devices");
b.Navigation("Notifications");
b.Navigation("Users");
});
#pragma warning restore 612, 618
}
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/Migrations/20260922000000_AddNotificationExpiresAtAndPendingIndex.cs
SIZE: 2830 chars
SHA256: 6E8631EC9A2EB772CA38EF8729A30337BB2E6D4DB64E1E4C7AE241796FA13AA2
===================================================================== */
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ClassNotify.Server.Data.Migrations
{
///
public partial class AddNotificationExpiresAtAndPendingIndex : Migration
{
///
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn(
name: "ExpiresAt",
table: "Notifications",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn(
name: "Voice",
table: "Notifications",
type: "boolean",
nullable: false,
defaultValue: true);
migrationBuilder.AddColumn(
name: "Shake",
table: "Notifications",
type: "boolean",
nullable: false,
defaultValue: true);
migrationBuilder.AddColumn(
name: "DurationSeconds",
table: "Notifications",
type: "integer",
nullable: false,
defaultValue: 15);
migrationBuilder.CreateIndex(
name: "IX_Notifications_TenantId_ClassroomId_ExpiresAt",
table: "Notifications",
columns: new[] { "TenantId", "ClassroomId", "ExpiresAt" });
migrationBuilder.CreateIndex(
name: "IX_NotificationReceipts_DeviceId_Status",
table: "NotificationReceipts",
columns: new[] { "DeviceId", "Status" });
// P1 Batch 9: Backfill legacy notifications where ExpiresAt IS NULL to CreatedAt (marking them expired)
migrationBuilder.Sql("UPDATE \"Notifications\" SET \"ExpiresAt\" = \"CreatedAt\" WHERE \"ExpiresAt\" IS NULL;");
}
///
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_NotificationReceipts_DeviceId_Status",
table: "NotificationReceipts");
migrationBuilder.DropIndex(
name: "IX_Notifications_TenantId_ClassroomId_ExpiresAt",
table: "Notifications");
migrationBuilder.DropColumn(
name: "DurationSeconds",
table: "Notifications");
migrationBuilder.DropColumn(
name: "Shake",
table: "Notifications");
migrationBuilder.DropColumn(
name: "Voice",
table: "Notifications");
migrationBuilder.DropColumn(
name: "ExpiresAt",
table: "Notifications");
}
}
}
/* =====================================================================
FILE: src/Server/ClassNotify.Server/Data/Migrations/20260922000000_AddNotificationExpiresAtAndPendingIndex.Designer.cs
SIZE: 18273 chars
SHA256: 5E983634C9ABC1D5BBBD8573EC78B2DD2735AE942CFA641CCF5CC4E3D3C0BAB4
===================================================================== */
//
using System;
using ClassNotify.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ClassNotify.Server.Data.Migrations
{
[DbContext(typeof(ClassNotifyDbContext))]
[Migration("20260922000000_AddNotificationExpiresAtAndPendingIndex")]
partial class AddNotificationExpiresAtAndPendingIndex
{
///
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.ActivationCode", b =>
{
b.Property("Code")
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("ClassroomId")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property("InstallationId")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property("IsUsed")
.HasColumnType("boolean");
b.Property("TenantId")
.IsRequired()
.HasColumnType("text");
b.Property("UsedAt")
.HasColumnType("timestamp with time zone");
b.Property("UsedByDeviceId")
.HasColumnType("text");
b.HasKey("Code");
b.HasIndex("ClassroomId");
b.HasIndex("Code")
.IsUnique();
b.HasIndex("InstallationId");
b.HasIndex("TenantId");
b.ToTable("ActivationCodes");
});
modelBuilder.Entity("ClassNotify.Server.Domain.Entities.Classroom", b =>
{
b.Property("TenantId")
.HasColumnType("text");
b.Property("Id")
.HasColumnType("text");
b.Property("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property