完善用户管理与凭据事务处理
This commit is contained in:
1 parent
7f0af703ed
commit
0e2222bcfe
33 files changed
+2135
-68
No files matched your search
@@ -29,6 +29,7 @@ type App struct {
|
|||||||
Database *database.Database
|
Database *database.Database
|
||||||
Repository *repository.SQLDomainRepository
|
Repository *repository.SQLDomainRepository
|
||||||
Servers *repository.SQLServerRepository
|
Servers *repository.SQLServerRepository
|
||||||
|
Users *repository.SQLUserRepository
|
||||||
Tasks *repository.SQLTaskRepository
|
Tasks *repository.SQLTaskRepository
|
||||||
Deployment *deployment.Service
|
Deployment *deployment.Service
|
||||||
SecretStore *secretstore.Store
|
SecretStore *secretstore.Store
|
||||||
@@ -77,6 +78,14 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
|||||||
dnsVerification := setup.NewDNSVerificationManager(dnsTester, secretStore)
|
dnsVerification := setup.NewDNSVerificationManager(dnsTester, secretStore)
|
||||||
repo := repository.NewSQLDomainRepository(db.DB)
|
repo := repository.NewSQLDomainRepository(db.DB)
|
||||||
serverRepo := repository.NewSQLServerRepository(db.DB)
|
serverRepo := repository.NewSQLServerRepository(db.DB)
|
||||||
|
userRepo := repository.NewSQLUserRepository(db.DB, cfg.Database.Driver)
|
||||||
|
if cfg.SetupReady && cfg.Admin.Username != "" && cfg.Admin.PasswordHash != "" {
|
||||||
|
if err := userRepo.EnsureSuperAdmin(ctx, repository.User{ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email, PasswordHash: cfg.Admin.PasswordHash}); err != nil {
|
||||||
|
_ = db.Close()
|
||||||
|
_ = logger.Close()
|
||||||
|
return nil, fmt.Errorf("初始化超级管理员用户失败:%w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
taskRepo := repository.NewSQLTaskRepository(db.DB)
|
taskRepo := repository.NewSQLTaskRepository(db.DB)
|
||||||
auditRepo := repository.NewSQLAuditRepository(db.DB)
|
auditRepo := repository.NewSQLAuditRepository(db.DB)
|
||||||
sshKeys := sshkey.NewService(secretStore)
|
sshKeys := sshkey.NewService(secretStore)
|
||||||
@@ -99,7 +108,7 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
|||||||
}
|
}
|
||||||
renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
|
renewal := certificate.NewRenewalScheduler(repo, workflow, cfg.ACME.RenewalThresholdDays)
|
||||||
server := httpapi.New(httpapi.Dependencies{
|
server := httpapi.New(httpapi.Dependencies{
|
||||||
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, SSHKeys: sshKeys,
|
Config: cfg, ConfigPath: configPath, Logger: logger, Repository: repo, Servers: serverRepo, Users: userRepo, SSHKeys: sshKeys,
|
||||||
SetupDNS: dnsVerification, Secrets: secretStore, Firewall: firewall.NewManager(),
|
SetupDNS: dnsVerification, Secrets: secretStore, Firewall: firewall.NewManager(),
|
||||||
IssueCertificate: workflow.IssueForHTTP,
|
IssueCertificate: workflow.IssueForHTTP,
|
||||||
IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
|
IssueSetupCertificate: func(ctx context.Context, request certificate.SetupCertificateRequest) (certificate.SavedResource, error) {
|
||||||
@@ -130,6 +139,7 @@ func NewWithConfigPath(ctx context.Context, cfg config.Config, configPath string
|
|||||||
return &App{
|
return &App{
|
||||||
Config: cfg, Logger: logger, Database: db, Repository: repo,
|
Config: cfg, Logger: logger, Database: db, Repository: repo,
|
||||||
Servers: serverRepo,
|
Servers: serverRepo,
|
||||||
|
Users: userRepo,
|
||||||
Tasks: taskRepo,
|
Tasks: taskRepo,
|
||||||
Deployment: deploymentService,
|
Deployment: deploymentService,
|
||||||
SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server,
|
SecretStore: secretStore, SSHKeys: sshKeys, DNSVerification: dnsVerification, HTTP: server,
|
||||||
|
|||||||
@@ -17,6 +17,11 @@ type AdminAccount struct {
|
|||||||
|
|
||||||
// AuthenticateAdmin 统一执行用户名或邮箱登录,并只返回后端确认的真实权限。
|
// AuthenticateAdmin 统一执行用户名或邮箱登录,并只返回后端确认的真实权限。
|
||||||
func AuthenticateAdmin(identifier, password, username, email, passwordHash string) (AdminAccount, error) {
|
func AuthenticateAdmin(identifier, password, username, email, passwordHash string) (AdminAccount, error) {
|
||||||
|
return AuthenticateAccount(identifier, password, username, email, passwordHash, "super_admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthenticateAccount 校验任意已启用账户的登录凭据,并返回其实际角色。
|
||||||
|
func AuthenticateAccount(identifier, password, username, email, passwordHash, role string) (AdminAccount, error) {
|
||||||
matched := IsMatch(identifier, username, email)
|
matched := IsMatch(identifier, username, email)
|
||||||
if !matched || strings.TrimSpace(password) == "" || len([]byte(password)) > 256 {
|
if !matched || strings.TrimSpace(password) == "" || len([]byte(password)) > 256 {
|
||||||
_ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
|
_ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
|
||||||
@@ -28,7 +33,7 @@ func AuthenticateAdmin(identifier, password, username, email, passwordHash strin
|
|||||||
return AdminAccount{
|
return AdminAccount{
|
||||||
Username: strings.TrimSpace(username),
|
Username: strings.TrimSpace(username),
|
||||||
Email: strings.TrimSpace(email),
|
Email: strings.TrimSpace(email),
|
||||||
Role: "super_admin",
|
Role: role,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func TestOpenAndMigrateSQLite(t *testing.T) {
|
|||||||
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&count); err != nil {
|
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&count); err != nil {
|
||||||
t.Fatalf("读取迁移版本失败:%v", err)
|
t.Fatalf("读取迁移版本失败:%v", err)
|
||||||
}
|
}
|
||||||
if count != 4 {
|
if count != latestMigrationVersion {
|
||||||
t.Fatalf("迁移版本数量错误:%d", count)
|
t.Fatalf("迁移版本数量错误:%d", count)
|
||||||
}
|
}
|
||||||
var autoRenew bool
|
var autoRenew bool
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed migrations/sqlite/0001_initial.sql migrations/sqlite/0002_domain_options.sql migrations/sqlite/0003_deployment.sql migrations/sqlite/0004_task_attempts.sql migrations/mysql/0001_initial.sql migrations/mysql/0002_domain_options.sql migrations/mysql/0003_deployment.sql migrations/mysql/0004_task_attempts.sql
|
//go:embed migrations/sqlite/0001_initial.sql migrations/sqlite/0002_domain_options.sql migrations/sqlite/0003_deployment.sql migrations/sqlite/0004_task_attempts.sql migrations/sqlite/0005_users.sql migrations/mysql/0001_initial.sql migrations/mysql/0002_domain_options.sql migrations/mysql/0003_deployment.sql migrations/mysql/0004_task_attempts.sql migrations/mysql/0005_users.sql
|
||||||
var migrationFiles embed.FS
|
var migrationFiles embed.FS
|
||||||
|
|
||||||
func Migrate(ctx context.Context, db *sql.DB, driver string) error {
|
func Migrate(ctx context.Context, db *sql.DB, driver string) error {
|
||||||
@@ -38,7 +38,7 @@ func Migrate(ctx context.Context, db *sql.DB, driver string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const latestMigrationVersion = 4
|
const latestMigrationVersion = 5
|
||||||
|
|
||||||
func applyMigration(ctx context.Context, db *sql.DB, driver string, version int) error {
|
func applyMigration(ctx context.Context, db *sql.DB, driver string, version int) error {
|
||||||
path := fmt.Sprintf("migrations/%s/%04d_%s.sql", driver, version, migrationName(version))
|
path := fmt.Sprintf("migrations/%s/%04d_%s.sql", driver, version, migrationName(version))
|
||||||
@@ -123,6 +123,8 @@ func migrationName(version int) string {
|
|||||||
return "deployment"
|
return "deployment"
|
||||||
case 4:
|
case 4:
|
||||||
return "task_attempts"
|
return "task_attempts"
|
||||||
|
case 5:
|
||||||
|
return "users"
|
||||||
default:
|
default:
|
||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id VARCHAR(36) NOT NULL PRIMARY KEY,
|
||||||
|
username VARCHAR(128) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(253) NULL,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
role VARCHAR(32) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE KEY uq_users_email (email),
|
||||||
|
INDEX idx_users_role_status (role, status)
|
||||||
|
);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id TEXT NOT NULL PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
email TEXT NOT NULL DEFAULT '',
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email
|
||||||
|
ON users(email)
|
||||||
|
WHERE email <> '';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_role_status ON users(role, status);
|
||||||
@@ -52,14 +52,14 @@ func TestSQLiteMigrationIsIdempotentAndCreatesBaseTables(t *testing.T) {
|
|||||||
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&versions); err != nil {
|
if err := db.DB.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&versions); err != nil {
|
||||||
t.Fatalf("读取迁移版本失败:%v", err)
|
t.Fatalf("读取迁移版本失败:%v", err)
|
||||||
}
|
}
|
||||||
if versions != 4 {
|
if versions != latestMigrationVersion {
|
||||||
t.Fatalf("重复迁移写入了多条版本记录:%d", versions)
|
t.Fatalf("重复迁移写入了多条版本记录:%d", versions)
|
||||||
}
|
}
|
||||||
var tables int
|
var tables int
|
||||||
if err := db.DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('settings', 'domains', 'tasks', 'audit_logs', 'servers', 'domain_servers')`).Scan(&tables); err != nil {
|
if err := db.DB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('settings', 'domains', 'tasks', 'audit_logs', 'servers', 'domain_servers', 'users')`).Scan(&tables); err != nil {
|
||||||
t.Fatalf("检查基础数据表失败:%v", err)
|
t.Fatalf("检查基础数据表失败:%v", err)
|
||||||
}
|
}
|
||||||
if tables != 6 {
|
if tables != 7 {
|
||||||
t.Fatalf("基础数据表数量不正确:%d", tables)
|
t.Fatalf("基础数据表数量不正确:%d", tables)
|
||||||
}
|
}
|
||||||
if err := Migrate(context.Background(), db.DB, "postgres"); err == nil {
|
if err := Migrate(context.Background(), db.DB, "postgres"); err == nil {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"net"
|
"net"
|
||||||
@@ -11,6 +12,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/auth"
|
"git.pcux.cn/xuans/Scert/backend/internal/auth"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,10 +27,13 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type authSession struct {
|
type authSession struct {
|
||||||
Username string
|
UserID string
|
||||||
Email string
|
Username string
|
||||||
Role string
|
Email string
|
||||||
ExpiresAt time.Time
|
Role string
|
||||||
|
PasswordHash string
|
||||||
|
ExpiresAt time.Time
|
||||||
|
AbsoluteExpiresAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type loginAttempt struct {
|
type loginAttempt struct {
|
||||||
@@ -64,13 +69,8 @@ func (s *Server) authLogin(c *gin.Context) {
|
|||||||
s.writeError(c, http.StatusTooManyRequests, "登录失败次数过多,请稍后再试", nil)
|
s.writeError(c, http.StatusTooManyRequests, "登录失败次数过多,请稍后再试", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
account, err := auth.AuthenticateAdmin(
|
|
||||||
request.Identifier,
|
account, userID, passwordHash, err := s.authenticateAccount(c.Request.Context(), request, cfg)
|
||||||
request.Password,
|
|
||||||
cfg.Admin.Username,
|
|
||||||
cfg.Admin.Email,
|
|
||||||
cfg.Admin.PasswordHash,
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.recordLoginFailure(key)
|
s.recordLoginFailure(key)
|
||||||
s.recordAuthAudit(c, "登录失败", "failed", "登录凭据校验失败")
|
s.recordAuthAudit(c, "登录失败", "failed", "登录凭据校验失败")
|
||||||
@@ -84,33 +84,56 @@ func (s *Server) authLogin(c *gin.Context) {
|
|||||||
s.writeError(c, http.StatusInternalServerError, "无法创建登录会话,请稍后重试", err)
|
s.writeError(c, http.StatusInternalServerError, "无法创建登录会话,请稍后重试", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
lifetime := authSessionLifetime
|
now := s.now()
|
||||||
|
absoluteExpiresAt := now.Add(authSessionLifetime)
|
||||||
if request.Remember {
|
if request.Remember {
|
||||||
lifetime = rememberSessionLife
|
absoluteExpiresAt = now.Add(rememberSessionLife)
|
||||||
}
|
}
|
||||||
expiresAt := s.now().Add(lifetime)
|
expiresAt := minTime(now.Add(authSessionLifetime), absoluteExpiresAt)
|
||||||
s.authMu.Lock()
|
s.authMu.Lock()
|
||||||
s.authSessions[token] = authSession{
|
s.authSessions[token] = authSession{
|
||||||
Username: account.Username,
|
UserID: userID,
|
||||||
Email: account.Email,
|
Username: account.Username,
|
||||||
Role: account.Role,
|
Email: account.Email,
|
||||||
ExpiresAt: expiresAt,
|
Role: account.Role,
|
||||||
|
PasswordHash: passwordHash,
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
AbsoluteExpiresAt: absoluteExpiresAt,
|
||||||
}
|
}
|
||||||
s.authMu.Unlock()
|
s.authMu.Unlock()
|
||||||
s.setAuthCookie(c, token, expiresAt)
|
s.setAuthCookie(c, token, expiresAt)
|
||||||
s.recordAuthAudit(c, "登录成功", "success", "超级管理员登录成功")
|
s.recordAuthAudit(c, "登录成功", "success", "用户登录成功")
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"authenticated": true,
|
"authenticated": true,
|
||||||
"account": account.Username,
|
"account": account.Username,
|
||||||
"email": account.Email,
|
"email": account.Email,
|
||||||
"role": account.Role,
|
"role": account.Role,
|
||||||
"is_admin": true,
|
"is_admin": account.Role == repository.UserRoleSuperAdmin || account.Role == repository.UserRoleAdmin,
|
||||||
"next_step": "complete",
|
"next_step": "complete",
|
||||||
"required_steps": []string{},
|
"required_steps": []string{},
|
||||||
"expires_at": expiresAt,
|
"expires_at": expiresAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) authenticateAccount(ctx context.Context, request authLoginRequest, cfg config.Config) (auth.AdminAccount, string, string, error) {
|
||||||
|
account, err := auth.AuthenticateAdmin(request.Identifier, request.Password, cfg.Admin.Username, cfg.Admin.Email, cfg.Admin.PasswordHash)
|
||||||
|
if err == nil {
|
||||||
|
return account, "primary-super-admin", cfg.Admin.PasswordHash, nil
|
||||||
|
}
|
||||||
|
if s.users == nil {
|
||||||
|
return auth.AdminAccount{}, "", "", auth.ErrInvalidCredentials
|
||||||
|
}
|
||||||
|
user, lookupErr := s.users.FindByIdentifier(ctx, request.Identifier)
|
||||||
|
if lookupErr != nil || user.Status != repository.UserStatusActive {
|
||||||
|
return auth.AdminAccount{}, "", "", auth.ErrInvalidCredentials
|
||||||
|
}
|
||||||
|
account, err = auth.AuthenticateAccount(request.Identifier, request.Password, user.Username, user.Email, user.PasswordHash, user.Role)
|
||||||
|
if err != nil {
|
||||||
|
return auth.AdminAccount{}, "", "", auth.ErrInvalidCredentials
|
||||||
|
}
|
||||||
|
return account, user.ID, user.PasswordHash, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) authSession(c *gin.Context) {
|
func (s *Server) authSession(c *gin.Context) {
|
||||||
session, ok := s.currentAuthSession(c)
|
session, ok := s.currentAuthSession(c)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -122,7 +145,7 @@ func (s *Server) authSession(c *gin.Context) {
|
|||||||
"account": session.Username,
|
"account": session.Username,
|
||||||
"email": session.Email,
|
"email": session.Email,
|
||||||
"role": session.Role,
|
"role": session.Role,
|
||||||
"is_admin": session.Role == "super_admin" || session.Role == "admin",
|
"is_admin": session.Role == repository.UserRoleSuperAdmin || session.Role == repository.UserRoleAdmin,
|
||||||
"next_step": "complete",
|
"next_step": "complete",
|
||||||
"required_steps": []string{},
|
"required_steps": []string{},
|
||||||
"expires_at": session.ExpiresAt,
|
"expires_at": session.ExpiresAt,
|
||||||
@@ -151,26 +174,99 @@ func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
|
|||||||
s.authMu.RLock()
|
s.authMu.RLock()
|
||||||
session, ok := s.authSessions[token]
|
session, ok := s.authSessions[token]
|
||||||
s.authMu.RUnlock()
|
s.authMu.RUnlock()
|
||||||
if !ok {
|
if !ok || !session.ExpiresAt.After(now) || (!session.AbsoluteExpiresAt.IsZero() && !session.AbsoluteExpiresAt.After(now)) {
|
||||||
|
if ok {
|
||||||
|
s.authMu.Lock()
|
||||||
|
delete(s.authSessions, token)
|
||||||
|
s.authMu.Unlock()
|
||||||
|
}
|
||||||
return authSession{}, false
|
return authSession{}, false
|
||||||
}
|
}
|
||||||
if !session.ExpiresAt.After(now) {
|
if !s.authSessionAccountIsValid(c.Request.Context(), session) {
|
||||||
s.authMu.Lock()
|
s.authMu.Lock()
|
||||||
delete(s.authSessions, token)
|
delete(s.authSessions, token)
|
||||||
s.authMu.Unlock()
|
s.authMu.Unlock()
|
||||||
|
s.clearAuthCookie(c)
|
||||||
return authSession{}, false
|
return authSession{}, false
|
||||||
}
|
}
|
||||||
|
newExpiresAt := minTime(now.Add(authSessionLifetime), session.AbsoluteExpiresAt)
|
||||||
|
if newExpiresAt.After(session.ExpiresAt) {
|
||||||
|
session.ExpiresAt = newExpiresAt
|
||||||
|
s.authMu.Lock()
|
||||||
|
if current, exists := s.authSessions[token]; exists {
|
||||||
|
current.ExpiresAt = newExpiresAt
|
||||||
|
s.authSessions[token] = current
|
||||||
|
session = current
|
||||||
|
}
|
||||||
|
s.authMu.Unlock()
|
||||||
|
s.setAuthCookie(c, token, session.ExpiresAt)
|
||||||
|
}
|
||||||
return session, true
|
return session, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) authSessionAccountIsValid(ctx context.Context, session authSession) bool {
|
||||||
|
if session.UserID == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if session.PasswordHash == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if session.UserID == "primary-super-admin" {
|
||||||
|
s.configMu.RLock()
|
||||||
|
cfg := s.config
|
||||||
|
s.configMu.RUnlock()
|
||||||
|
if !cfg.SetupReady || session.Role != repository.UserRoleSuperAdmin {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(strings.TrimSpace(session.Username), strings.TrimSpace(cfg.Admin.Username)) ||
|
||||||
|
!strings.EqualFold(strings.TrimSpace(session.Email), strings.TrimSpace(cfg.Admin.Email)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return session.PasswordHash == cfg.Admin.PasswordHash
|
||||||
|
}
|
||||||
|
if s.users == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
user, err := s.users.GetUserByID(ctx, session.UserID)
|
||||||
|
if err != nil || user.Status != repository.UserStatusActive {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if user.Role != session.Role || !strings.EqualFold(user.Username, session.Username) || !strings.EqualFold(user.Email, session.Email) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return session.PasswordHash == user.PasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) setAuthCookie(c *gin.Context, token string, expiresAt time.Time) {
|
func (s *Server) setAuthCookie(c *gin.Context, token string, expiresAt time.Time) {
|
||||||
|
maxAge := int(expiresAt.Sub(s.now()).Seconds())
|
||||||
http.SetCookie(c.Writer, &http.Cookie{
|
http.SetCookie(c.Writer, &http.Cookie{
|
||||||
Name: authCookieName, Value: token, Path: "/",
|
Name: authCookieName, Value: token, Path: "/",
|
||||||
Expires: expiresAt, MaxAge: max(1, int(time.Until(expiresAt).Seconds())),
|
Expires: expiresAt, MaxAge: max(1, maxAge),
|
||||||
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.requestIsHTTPS(c.Request),
|
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.requestIsHTTPS(c.Request),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) clearAuthCookie(c *gin.Context) {
|
||||||
|
http.SetCookie(c.Writer, &http.Cookie{
|
||||||
|
Name: authCookieName, Value: "", Path: "/", MaxAge: -1,
|
||||||
|
HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.requestIsHTTPS(c.Request),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) invalidateUserSessions(userID string) {
|
||||||
|
userID = strings.TrimSpace(userID)
|
||||||
|
if userID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.authMu.Lock()
|
||||||
|
defer s.authMu.Unlock()
|
||||||
|
for token, session := range s.authSessions {
|
||||||
|
if session.UserID == userID {
|
||||||
|
delete(s.authSessions, token)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) allowLogin(key string) bool {
|
func (s *Server) allowLogin(key string) bool {
|
||||||
now := s.now()
|
now := s.now()
|
||||||
s.loginMu.Lock()
|
s.loginMu.Lock()
|
||||||
@@ -256,6 +352,13 @@ func (s *Server) requestIsHTTPS(request *http.Request) bool {
|
|||||||
return strings.EqualFold(forwardedProto, "https")
|
return strings.EqualFold(forwardedProto, "https")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func minTime(left, right time.Time) time.Time {
|
||||||
|
if right.IsZero() || left.Before(right) {
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
return right
|
||||||
|
}
|
||||||
|
|
||||||
func max(left, right int) int {
|
func max(left, right int) int {
|
||||||
if left > right {
|
if left > right {
|
||||||
return left
|
return left
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAuthLoginSupportsUserNameEmailAndDisabledAccounts(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
cfg.Database.DSN = filepath.Join(directory, "data", "auth-api.db")
|
||||||
|
db, err := database.Open(t.Context(), cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开认证测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
t.Fatalf("迁移认证测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
users := repository.NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
if err := users.EnsureSuperAdmin(t.Context(), repository.User{
|
||||||
|
ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email, PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存测试超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := users.CreateUser(t.Context(), repository.User{
|
||||||
|
ID: "operator-1", Username: "operator", Email: "operator@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Operator123"), Role: repository.UserRoleAdmin, Status: repository.UserStatusActive,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存测试管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := users.CreateUser(t.Context(), repository.User{
|
||||||
|
ID: "disabled-1", Username: "disabled", Email: "disabled@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Disabled123"), Role: repository.UserRoleUser, Status: repository.UserStatusDisabled,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存测试禁用用户失败:%v", err)
|
||||||
|
}
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}, Users: users})
|
||||||
|
|
||||||
|
for _, identifier := range []string{"operator", "OPERATOR@EXAMPLE.TEST"} {
|
||||||
|
response := loginAuthTest(t, server, identifier, "Operator123", false)
|
||||||
|
var payload struct {
|
||||||
|
Account string `json:"account"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
IsAdmin bool `json:"is_admin"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||||
|
t.Fatalf("解析用户登录响应失败:%v", err)
|
||||||
|
}
|
||||||
|
if payload.Account != "operator" || payload.Email != "operator@example.test" || payload.Role != repository.UserRoleAdmin || !payload.IsAdmin {
|
||||||
|
t.Fatalf("用户登录响应内容错误:%+v", payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
disabled := loginAuthTest(t, server, "disabled", "Disabled123", false)
|
||||||
|
if disabled.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("禁用用户登录应返回 401,实际为 %d:%s", disabled.Code, disabled.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthSessionSlidesAndHonorsAbsoluteRememberExpiration(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}})
|
||||||
|
current := time.Date(2026, 8, 30, 10, 0, 0, 0, time.UTC)
|
||||||
|
server.now = func() time.Time { return current }
|
||||||
|
|
||||||
|
login := loginAuthTest(t, server, "admin", "AdminPass123", true)
|
||||||
|
cookies := login.Result().Cookies()
|
||||||
|
if len(cookies) == 0 {
|
||||||
|
t.Fatal("记住登录响应未返回会话 Cookie")
|
||||||
|
}
|
||||||
|
token := cookies[0].Value
|
||||||
|
server.authMu.RLock()
|
||||||
|
initial := server.authSessions[token]
|
||||||
|
server.authMu.RUnlock()
|
||||||
|
if !initial.AbsoluteExpiresAt.Equal(current.Add(rememberSessionLife)) || !initial.ExpiresAt.Equal(current.Add(authSessionLifetime)) {
|
||||||
|
t.Fatalf("记住登录会话期限错误:%+v", initial)
|
||||||
|
}
|
||||||
|
|
||||||
|
current = current.Add(20 * time.Minute)
|
||||||
|
sessionResponse := httptest.NewRecorder()
|
||||||
|
sessionRequest := httptest.NewRequest(http.MethodGet, "/api/v1/auth/session", nil)
|
||||||
|
sessionRequest.AddCookie(cookies[0])
|
||||||
|
server.Handler().ServeHTTP(sessionResponse, sessionRequest)
|
||||||
|
if sessionResponse.Code != http.StatusOK {
|
||||||
|
t.Fatalf("有效会话检查失败:%d %s", sessionResponse.Code, sessionResponse.Body.String())
|
||||||
|
}
|
||||||
|
server.authMu.RLock()
|
||||||
|
sliding := server.authSessions[token]
|
||||||
|
server.authMu.RUnlock()
|
||||||
|
if !sliding.ExpiresAt.Equal(current.Add(authSessionLifetime)) {
|
||||||
|
t.Fatalf("会话未按访问时间滑动续期:%+v", sliding)
|
||||||
|
}
|
||||||
|
|
||||||
|
current = current.Add(rememberSessionLife)
|
||||||
|
expired := httptest.NewRecorder()
|
||||||
|
expiredRequest := httptest.NewRequest(http.MethodGet, "/api/v1/auth/session", nil)
|
||||||
|
expiredRequest.AddCookie(cookies[0])
|
||||||
|
server.Handler().ServeHTTP(expired, expiredRequest)
|
||||||
|
if expired.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("超过绝对期限的会话应返回 401,实际为 %d:%s", expired.Code, expired.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthSessionIsInvalidatedWhenUserChanges(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
cfg.Database.DSN = filepath.Join(directory, "data", "auth-invalidation.db")
|
||||||
|
db, err := database.Open(t.Context(), cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开会话失效测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
t.Fatalf("迁移会话失效测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
users := repository.NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
if err := users.EnsureSuperAdmin(t.Context(), repository.User{
|
||||||
|
ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email, PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存会话失效测试超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := users.CreateUser(t.Context(), repository.User{
|
||||||
|
ID: "operator-1", Username: "operator", Email: "operator@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Operator123"), Role: repository.UserRoleAdmin, Status: repository.UserStatusActive,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存会话失效测试用户失败:%v", err)
|
||||||
|
}
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}, Users: users})
|
||||||
|
|
||||||
|
login := loginAuthTest(t, server, "operator", "Operator123", false)
|
||||||
|
cookies := login.Result().Cookies()
|
||||||
|
if len(cookies) == 0 {
|
||||||
|
t.Fatal("会话失效测试未返回 Cookie")
|
||||||
|
}
|
||||||
|
if err := users.UpdateUser(t.Context(), repository.User{
|
||||||
|
ID: "operator-1", Username: "operator", Email: "operator@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Operator123"), Role: repository.UserRoleAdmin, Status: repository.UserStatusDisabled,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("禁用会话失效测试用户失败:%v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/auth/session", nil)
|
||||||
|
request.AddCookie(cookies[0])
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("禁用用户的旧会话应返回 401,实际为 %d:%s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
server.authMu.RLock()
|
||||||
|
_, exists := server.authSessions[cookies[0].Value]
|
||||||
|
server.authMu.RUnlock()
|
||||||
|
if exists {
|
||||||
|
t.Fatal("禁用用户的旧会话未从内存中清理")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func loginAuthTest(t *testing.T, server *Server, identifier, password string, remember bool) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
body := `{"identifier":"` + identifier + `","password":"` + password + `","remember":` + boolString(remember) + `}`
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(body))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if remember && response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("记住登录失败:%d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if !remember && identifier != "disabled" && response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("登录失败:%s,状态码=%d,响应=%s", identifier, response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolString(value bool) string {
|
||||||
|
if value {
|
||||||
|
return "true"
|
||||||
|
}
|
||||||
|
return "false"
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthSessionIsInvalidatedWhenUserPasswordChangesOrIsDeleted(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
cfg.Database.DSN = filepath.Join(directory, "data", "auth-invalidation-actions.db")
|
||||||
|
db, err := database.Open(t.Context(), cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开用户会话操作测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
t.Fatalf("迁移用户会话操作测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
users := repository.NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
if err := users.EnsureSuperAdmin(t.Context(), repository.User{
|
||||||
|
ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email, PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存用户会话操作测试超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := users.CreateUser(t.Context(), repository.User{
|
||||||
|
ID: "operator-1", Username: "operator", Email: "operator@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Operator123"), Role: repository.UserRoleAdmin, Status: repository.UserStatusActive,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存用户会话操作测试用户失败:%v", err)
|
||||||
|
}
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}, Users: users})
|
||||||
|
|
||||||
|
passwordLogin := loginAuthTest(t, server, "operator", "Operator123", false)
|
||||||
|
passwordCookie := passwordLogin.Result().Cookies()[0]
|
||||||
|
if err := users.UpdateUser(t.Context(), repository.User{
|
||||||
|
ID: "operator-1", Username: "operator", Email: "operator@example.test",
|
||||||
|
PasswordHash: httpUserPasswordHash(t, "Changed123"), Role: repository.UserRoleAdmin, Status: repository.UserStatusActive,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("修改用户密码失败:%v", err)
|
||||||
|
}
|
||||||
|
passwordResponse := authSessionRequest(server, passwordCookie)
|
||||||
|
if passwordResponse.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("用户改密后旧会话应返回 401,实际为 %d:%s", passwordResponse.Code, passwordResponse.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteLogin := loginAuthTest(t, server, "operator", "Changed123", false)
|
||||||
|
deleteCookie := deleteLogin.Result().Cookies()[0]
|
||||||
|
if err := users.DeleteUser(t.Context(), "operator-1"); err != nil {
|
||||||
|
t.Fatalf("删除用户失败:%v", err)
|
||||||
|
}
|
||||||
|
deleteResponse := authSessionRequest(server, deleteCookie)
|
||||||
|
if deleteResponse.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("删除用户后旧会话应返回 401,实际为 %d:%s", deleteResponse.Code, deleteResponse.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrimarySuperAdminSessionIsInvalidatedWhenConfigurationPasswordChanges(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}})
|
||||||
|
|
||||||
|
login := loginAuthTest(t, server, "admin", "AdminPass123", false)
|
||||||
|
cookie := login.Result().Cookies()[0]
|
||||||
|
server.configMu.Lock()
|
||||||
|
server.config.Admin.PasswordHash = httpUserPasswordHash(t, "Changed123")
|
||||||
|
server.configMu.Unlock()
|
||||||
|
|
||||||
|
response := authSessionRequest(server, cookie)
|
||||||
|
if response.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("主超级管理员改密后旧会话应返回 401,实际为 %d:%s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func authSessionRequest(server *Server, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/auth/session", nil)
|
||||||
|
request.AddCookie(cookie)
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
return response
|
||||||
|
}
|
||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
const requestIDHeader = "X-Scert-Request-ID"
|
const requestIDHeader = "X-Scert-Request-ID"
|
||||||
@@ -43,13 +45,21 @@ func (s *Server) requireAdmin(c *gin.Context) {
|
|||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, ok := s.currentAuthSession(c); !ok {
|
session, ok := s.currentAuthSession(c)
|
||||||
|
if !ok {
|
||||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||||
"error": "请先登录管理后台",
|
"error": "请先登录管理后台",
|
||||||
"request_id": requestIDFromContext(c),
|
"request_id": requestIDFromContext(c),
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if session.Role != repository.UserRoleSuperAdmin && session.Role != repository.UserRoleAdmin {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||||
|
"error": "当前账号没有管理权限",
|
||||||
|
"request_id": requestIDFromContext(c),
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
if !s.sameOriginForAPI(c.Request) {
|
if !s.sameOriginForAPI(c.Request) {
|
||||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||||
"error": "请求来源校验失败",
|
"error": "请求来源校验失败",
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestRequestMiddlewareAddsAndPreservesRequestID(t *testing.T) {
|
func TestRequestMiddlewareAddsAndPreservesRequestID(t *testing.T) {
|
||||||
@@ -94,3 +95,24 @@ func TestAdminAPIAcceptsAuthenticatedSessionAndRejectsCrossOrigin(t *testing.T)
|
|||||||
t.Fatalf("跨来源管理请求应返回 403,实际为 %d:%s", crossOriginResponse.Code, crossOriginResponse.Body.String())
|
t.Fatalf("跨来源管理请求应返回 403,实际为 %d:%s", crossOriginResponse.Code, crossOriginResponse.Body.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdminAPIRejectsAuthenticatedRegularUser(t *testing.T) {
|
||||||
|
cfg := config.Default(t.TempDir())
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.com"
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte("Password123"), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||||
|
}
|
||||||
|
cfg.Admin.PasswordHash = string(hash)
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}})
|
||||||
|
cookie := httpUserSessionCookie(server, "user-1", repository.UserRoleUser)
|
||||||
|
response := serveUserRequest(server, cookie, http.MethodGet, "/api/v1/domains", "")
|
||||||
|
if response.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("普通用户访问管理接口应返回 403,实际为 %d:%s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if !strings.Contains(response.Body.String(), "没有管理权限") {
|
||||||
|
t.Fatalf("普通用户权限错误提示不明确:%s", response.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
@@ -16,6 +17,7 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
"git.pcux.cn/xuans/Scert/backend/internal/admin"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/passwordpolicy"
|
"git.pcux.cn/xuans/Scert/backend/internal/passwordpolicy"
|
||||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
)
|
)
|
||||||
@@ -134,6 +136,7 @@ func (s *Server) resetSubmit(c *gin.Context) {
|
|||||||
s.renderResetPage(c, http.StatusBadRequest, token, err.Error())
|
s.renderResetPage(c, http.StatusBadRequest, token, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
previousConfig := cfg
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.recordResetAudit(c, "error", "生成新密码摘要失败")
|
s.recordResetAudit(c, "error", "生成新密码摘要失败")
|
||||||
@@ -141,16 +144,26 @@ func (s *Server) resetSubmit(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
cfg.Admin.PasswordHash = string(hash)
|
cfg.Admin.PasswordHash = string(hash)
|
||||||
|
if err := s.syncPrimarySuperAdmin(c.Request.Context(), cfg); err != nil {
|
||||||
|
s.recordResetAudit(c, "error", "同步超级管理员用户失败")
|
||||||
|
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法同步管理员账户,请稍后重试")
|
||||||
|
return
|
||||||
|
}
|
||||||
if strings.TrimSpace(s.configPath) == "" {
|
if strings.TrimSpace(s.configPath) == "" {
|
||||||
|
_ = s.syncPrimarySuperAdmin(c.Request.Context(), previousConfig)
|
||||||
s.recordResetAudit(c, "error", "密码重置配置路径未配置")
|
s.recordResetAudit(c, "error", "密码重置配置路径未配置")
|
||||||
s.writeResetFailure(c, http.StatusInternalServerError, "服务配置路径未就绪,请联系管理员")
|
s.writeResetFailure(c, http.StatusInternalServerError, "服务配置路径未就绪,请联系管理员")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := cfg.Save(s.configPath); err != nil {
|
if err := cfg.Save(s.configPath); err != nil {
|
||||||
|
if restoreErr := s.syncPrimarySuperAdmin(c.Request.Context(), previousConfig); restoreErr != nil && s.logger != nil {
|
||||||
|
s.logger.Error("配置保存失败后恢复超级管理员用户摘要失败", "error", restoreErr)
|
||||||
|
}
|
||||||
s.recordResetAudit(c, "error", "保存密码重置配置失败")
|
s.recordResetAudit(c, "error", "保存密码重置配置失败")
|
||||||
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法保存新密码,请稍后重试")
|
s.writeResetFailure(c, http.StatusInternalServerError, "暂时无法保存新密码,请稍后重试")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
s.invalidateUserSessions("primary-super-admin")
|
||||||
if err := admin.Consume(s.resetStatePath, verified, now); err != nil {
|
if err := admin.Consume(s.resetStatePath, verified, now); err != nil {
|
||||||
s.resetClosedHash = session.CodeHash
|
s.resetClosedHash = session.CodeHash
|
||||||
s.configMu.Lock()
|
s.configMu.Lock()
|
||||||
@@ -171,6 +184,18 @@ func (s *Server) resetSubmit(c *gin.Context) {
|
|||||||
s.renderResetSuccess(c, "密码重置成功,请停止 Scert-admin 以结束本次维护窗口")
|
s.renderResetSuccess(c, "密码重置成功,请停止 Scert-admin 以结束本次维护窗口")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) syncPrimarySuperAdmin(ctx context.Context, cfg config.Config) error {
|
||||||
|
if s.users == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.users.EnsureSuperAdmin(ctx, repository.User{
|
||||||
|
ID: "primary-super-admin",
|
||||||
|
Username: cfg.Admin.Username,
|
||||||
|
Email: cfg.Admin.Email,
|
||||||
|
PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) sameOrigin(request *http.Request) bool {
|
func (s *Server) sameOrigin(request *http.Request) bool {
|
||||||
if request == nil || strings.TrimSpace(request.Host) == "" {
|
if request == nil || strings.TrimSpace(request.Host) == "" {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ type Dependencies struct {
|
|||||||
Logger *logging.Logger
|
Logger *logging.Logger
|
||||||
Repository repository.DomainRepository
|
Repository repository.DomainRepository
|
||||||
Servers repository.ServerRepository
|
Servers repository.ServerRepository
|
||||||
|
Users repository.UserRepository
|
||||||
SSHKeys *sshkey.Service
|
SSHKeys *sshkey.Service
|
||||||
SetupDNS setupDNSVerifier
|
SetupDNS setupDNSVerifier
|
||||||
Secrets setupSecretWriter
|
Secrets setupSecretWriter
|
||||||
@@ -65,6 +66,7 @@ type Server struct {
|
|||||||
logger *logging.Logger
|
logger *logging.Logger
|
||||||
repository repository.DomainRepository
|
repository repository.DomainRepository
|
||||||
servers repository.ServerRepository
|
servers repository.ServerRepository
|
||||||
|
users repository.UserRepository
|
||||||
sshKeys *sshkey.Service
|
sshKeys *sshkey.Service
|
||||||
setupDNS setupDNSVerifier
|
setupDNS setupDNSVerifier
|
||||||
secrets setupSecretWriter
|
secrets setupSecretWriter
|
||||||
@@ -105,6 +107,7 @@ func New(deps Dependencies) *Server {
|
|||||||
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
|
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
|
||||||
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
|
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
|
||||||
servers: deps.Servers,
|
servers: deps.Servers,
|
||||||
|
users: deps.Users,
|
||||||
sshKeys: deps.SSHKeys,
|
sshKeys: deps.SSHKeys,
|
||||||
issueCertificate: deps.IssueCertificate,
|
issueCertificate: deps.IssueCertificate,
|
||||||
issueSetupCertificate: deps.IssueSetupCertificate,
|
issueSetupCertificate: deps.IssueSetupCertificate,
|
||||||
@@ -139,6 +142,12 @@ func (s *Server) registerRoutes() {
|
|||||||
s.router.POST("/api/v1/auth/logout", s.authLogout)
|
s.router.POST("/api/v1/auth/logout", s.authLogout)
|
||||||
s.router.POST("/api/v1/password-reset/resolve", s.resolvePasswordResetAccount)
|
s.router.POST("/api/v1/password-reset/resolve", s.resolvePasswordResetAccount)
|
||||||
adminAPI := s.router.Group("/api/v1", s.requireAdmin)
|
adminAPI := s.router.Group("/api/v1", s.requireAdmin)
|
||||||
|
userAPI := s.router.Group("/api/v1/users", s.requireSuperAdmin)
|
||||||
|
userAPI.GET("", s.listUsers)
|
||||||
|
userAPI.POST("", s.createUser)
|
||||||
|
userAPI.GET("/:id", s.getUser)
|
||||||
|
userAPI.PUT("/:id", s.updateUser)
|
||||||
|
userAPI.DELETE("/:id", s.deleteUser)
|
||||||
adminAPI.GET("/domains", s.listDomains)
|
adminAPI.GET("/domains", s.listDomains)
|
||||||
adminAPI.POST("/domains", s.createDomain)
|
adminAPI.POST("/domains", s.createDomain)
|
||||||
adminAPI.PUT("/domains/:id", s.updateDomain)
|
adminAPI.PUT("/domains/:id", s.updateDomain)
|
||||||
|
|||||||
@@ -173,6 +173,75 @@ func TestResetPasswordUpdatesConfigAndConsumesSession(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResetPasswordSynchronizesPrimarySuperAdminUser(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
cfg := config.Default(dir)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Web.Hostname = "scert.example.test"
|
||||||
|
cfg.DNS.VerificationState = "verified"
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
oldHash, err := bcrypt.GenerateFromPassword([]byte("OldPassword123"), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("生成旧密码摘要失败:%v", err)
|
||||||
|
}
|
||||||
|
cfg.Admin.PasswordHash = string(oldHash)
|
||||||
|
cfg.Database.DSN = filepath.Join(dir, "data", "reset-users.db")
|
||||||
|
configPath := filepath.Join(dir, "config", "scert.json")
|
||||||
|
if err := cfg.Save(configPath); err != nil {
|
||||||
|
t.Fatalf("保存测试配置失败:%v", err)
|
||||||
|
}
|
||||||
|
db, err := database.Open(t.Context(), cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开测试用户数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
t.Fatalf("迁移测试用户数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
users := repository.NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
if err := users.EnsureSuperAdmin(t.Context(), repository.User{
|
||||||
|
ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email, PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("创建测试超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
controller := admin.New(cfg)
|
||||||
|
session, err := controller.Start()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("启动测试重置会话失败:%v", err)
|
||||||
|
}
|
||||||
|
server := New(Dependencies{
|
||||||
|
Config: cfg, ConfigPath: configPath, Repository: &stubDomainRepository{}, Users: users,
|
||||||
|
ResetStatePath: admin.StatePath(cfg.Paths.Data),
|
||||||
|
})
|
||||||
|
get := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(get, httptest.NewRequest(http.MethodGet, "https://scert.example.test/reset", nil))
|
||||||
|
if get.Code != http.StatusOK {
|
||||||
|
t.Fatalf("获取密码重置页面失败:%d", get.Code)
|
||||||
|
}
|
||||||
|
cookies := get.Result().Cookies()
|
||||||
|
if len(cookies) != 1 {
|
||||||
|
t.Fatalf("密码重置页面 Cookie 数量错误:%d", len(cookies))
|
||||||
|
}
|
||||||
|
form := resetForm(session.Code, cookies[0].Value, "NewPass1234")
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "https://scert.example.test/reset", strings.NewReader(form.Encode()))
|
||||||
|
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
request.Header.Set("Origin", "https://scert.example.test")
|
||||||
|
request.AddCookie(cookies[0])
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("密码重置失败:%d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
item, err := users.GetUserByID(t.Context(), "primary-super-admin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("读取同步后的超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(item.PasswordHash), []byte("NewPass1234")) != nil {
|
||||||
|
t.Fatal("用户表中的超级管理员摘要未同步新密码")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) {
|
func TestResetRejectsCrossSiteAndLimitsFailures(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
cfg := config.Default(dir)
|
cfg := config.Default(dir)
|
||||||
|
|||||||
@@ -165,17 +165,21 @@ func (s *Server) updateSettings(c *gin.Context) {
|
|||||||
updated := s.config
|
updated := s.config
|
||||||
applySettingsRequest(&updated, request)
|
applySettingsRequest(&updated, request)
|
||||||
updated.Normalize()
|
updated.Normalize()
|
||||||
if err := s.saveSettingsNotificationCredentials(c.Request.Context(), &updated, request); err != nil {
|
createdCredentialRefs, err := s.saveSettingsNotificationCredentials(c.Request.Context(), &updated, request)
|
||||||
|
if err != nil {
|
||||||
|
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||||
s.configMu.Unlock()
|
s.configMu.Unlock()
|
||||||
s.writeError(c, http.StatusBadRequest, "保存通知凭据失败", err)
|
s.writeError(c, http.StatusBadRequest, "保存通知凭据失败", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := updated.Validate(); err != nil {
|
if err := updated.Validate(); err != nil {
|
||||||
|
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||||
s.configMu.Unlock()
|
s.configMu.Unlock()
|
||||||
s.writeError(c, http.StatusBadRequest, "设置内容校验失败", err)
|
s.writeError(c, http.StatusBadRequest, "设置内容校验失败", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := updated.Save(s.configPath); err != nil {
|
if err := updated.Save(s.configPath); err != nil {
|
||||||
|
s.rollbackSetupCredentialsWithLog(createdCredentialRefs)
|
||||||
s.configMu.Unlock()
|
s.configMu.Unlock()
|
||||||
s.writeError(c, http.StatusInternalServerError, "保存设置失败", err)
|
s.writeError(c, http.StatusInternalServerError, "保存设置失败", err)
|
||||||
return
|
return
|
||||||
@@ -193,6 +197,29 @@ func (s *Server) updateSettings(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
s.config = updated
|
s.config = updated
|
||||||
s.configMu.Unlock()
|
s.configMu.Unlock()
|
||||||
|
oldCredentialRefs := []string{
|
||||||
|
previous.Notification.HTTPCredentialRef,
|
||||||
|
previous.Notification.SMTPCredentialRef,
|
||||||
|
}
|
||||||
|
newCredentialRefs := map[string]struct{}{
|
||||||
|
updated.Notification.HTTPCredentialRef: {},
|
||||||
|
updated.Notification.SMTPCredentialRef: {},
|
||||||
|
}
|
||||||
|
var obsoleteCredentialRefs []string
|
||||||
|
for _, reference := range oldCredentialRefs {
|
||||||
|
reference = strings.TrimSpace(reference)
|
||||||
|
if reference == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, stillUsed := newCredentialRefs[reference]; !stillUsed {
|
||||||
|
obsoleteCredentialRefs = append(obsoleteCredentialRefs, reference)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(obsoleteCredentialRefs) > 0 {
|
||||||
|
if err := s.rollbackSetupCredentials(obsoleteCredentialRefs); err != nil && s.logger != nil {
|
||||||
|
s.logger.Warn("\u6e05\u7406\u5df2\u66ff\u6362\u7684\u901a\u77e5\u654f\u611f\u51ed\u636e\u5931\u8d25", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"settings": settingsViewFromConfig(updated),
|
"settings": settingsViewFromConfig(updated),
|
||||||
|
|||||||
@@ -209,3 +209,123 @@ func mustTestPasswordHash(t *testing.T, password string) string {
|
|||||||
}
|
}
|
||||||
return string(hash)
|
return string(hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSettingsAPIRollsBackCredentialsWhenValidationFails(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
cfg := config.Default(dir)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.DNS.VerificationState = "verified"
|
||||||
|
cfg.Web.Hostname = "scert.example.test"
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||||
|
configPath := dir + "\\config\\scert.json"
|
||||||
|
if err := cfg.Save(configPath); err != nil {
|
||||||
|
t.Fatalf("save test config: %v", err)
|
||||||
|
}
|
||||||
|
secrets := &fakeSetupSecretWriter{}
|
||||||
|
server := New(Dependencies{Config: cfg, ConfigPath: configPath, Secrets: secrets})
|
||||||
|
cookie := loginForSettingsTest(t, server)
|
||||||
|
|
||||||
|
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||||
|
"notification": {
|
||||||
|
"http_auth_mode": "bearer",
|
||||||
|
"http_credentials": {"token": "new-token"},
|
||||||
|
"http_path": "email/send"
|
||||||
|
}
|
||||||
|
}`))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.AddCookie(cookie)
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("invalid notification settings should fail: %d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if len(secrets.values) != 0 || len(secrets.deleted) != 1 {
|
||||||
|
t.Fatalf("new credentials should be rolled back after validation failure: values=%v deleted=%v", secrets.values, secrets.deleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSettingsAPICleansReplacedNotificationCredential(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
cfg := config.Default(dir)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.DNS.VerificationState = "verified"
|
||||||
|
cfg.Web.Hostname = "scert.example.test"
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||||
|
cfg.Notification.HTTPAuthMode = "bearer"
|
||||||
|
cfg.Notification.HTTPCredentialRef = "secret://notification/old"
|
||||||
|
configPath := dir + "\\config\\scert.json"
|
||||||
|
if err := cfg.Save(configPath); err != nil {
|
||||||
|
t.Fatalf("save test config: %v", err)
|
||||||
|
}
|
||||||
|
secrets := &fakeSetupSecretWriter{values: map[string]map[string]string{
|
||||||
|
"secret://notification/old": {"token": "old-token"},
|
||||||
|
}}
|
||||||
|
server := New(Dependencies{Config: cfg, ConfigPath: configPath, Secrets: secrets})
|
||||||
|
cookie := loginForSettingsTest(t, server)
|
||||||
|
|
||||||
|
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||||
|
"notification": {
|
||||||
|
"http_auth_mode": "bearer",
|
||||||
|
"http_credentials": {"token": "new-token"}
|
||||||
|
}
|
||||||
|
}`))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.AddCookie(cookie)
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusOK {
|
||||||
|
t.Fatalf("notification credential replacement should succeed: %d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if _, ok := secrets.values["secret://notification/old"]; ok {
|
||||||
|
t.Fatal("replaced notification credential should be deleted")
|
||||||
|
}
|
||||||
|
if len(secrets.values) != 1 {
|
||||||
|
t.Fatalf("new notification credential should remain: %v", secrets.values)
|
||||||
|
}
|
||||||
|
if strings.Contains(response.Body.String(), "new-token") {
|
||||||
|
t.Fatal("notification credential must not be returned in the response")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSettingsAPIRollsBackEarlierCredentialWhenLaterCredentialFails(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
cfg := config.Default(dir)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.DNS.VerificationState = "verified"
|
||||||
|
cfg.Web.Hostname = "scert.example.test"
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
|
||||||
|
cfg.Notification.SMTPUsername = "smtp-user"
|
||||||
|
configPath := dir + "\\config\\scert.json"
|
||||||
|
if err := cfg.Save(configPath); err != nil {
|
||||||
|
t.Fatalf("save test config: %v", err)
|
||||||
|
}
|
||||||
|
secrets := &fakeSetupSecretWriter{}
|
||||||
|
server := New(Dependencies{Config: cfg, ConfigPath: configPath, Secrets: secrets})
|
||||||
|
cookie := loginForSettingsTest(t, server)
|
||||||
|
|
||||||
|
request := httptest.NewRequest(http.MethodPut, "/api/v1/settings", strings.NewReader(`{
|
||||||
|
"notification": {
|
||||||
|
"http_auth_mode": "bearer",
|
||||||
|
"http_credentials": {"token": "new-token"},
|
||||||
|
"smtp_enabled": true,
|
||||||
|
"smtp_username": "",
|
||||||
|
"smtp_password": "smtp-password"
|
||||||
|
}
|
||||||
|
}`))
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
request.AddCookie(cookie)
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("later SMTP validation should fail: %d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if len(secrets.values) != 0 || len(secrets.deleted) != 1 {
|
||||||
|
t.Fatalf("earlier HTTP credentials should be rolled back: values=%v deleted=%v", secrets.values, secrets.deleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,46 +9,49 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// saveSettingsNotificationCredentials 将页面提交的通知密码写入加密存储,配置文件只保存引用。
|
// saveSettingsNotificationCredentials 将页面提交的通知密码写入加密存储,配置文件只保存引用。
|
||||||
func (s *Server) saveSettingsNotificationCredentials(ctx context.Context, cfg *config.Config, request settingsRequest) error {
|
func (s *Server) saveSettingsNotificationCredentials(ctx context.Context, cfg *config.Config, request settingsRequest) ([]string, error) {
|
||||||
|
createdCredentialRefs := make([]string, 0, 2)
|
||||||
if cfg == nil || request.Notification == nil {
|
if cfg == nil || request.Notification == nil {
|
||||||
return nil
|
return createdCredentialRefs, nil
|
||||||
}
|
}
|
||||||
item := request.Notification
|
item := request.Notification
|
||||||
if len(item.HTTPCredentials) > 0 {
|
if len(item.HTTPCredentials) > 0 {
|
||||||
if s.secrets == nil {
|
if s.secrets == nil {
|
||||||
return errors.New("HTTP 通知敏感凭据存储尚未初始化")
|
return createdCredentialRefs, errors.New("HTTP 通知敏感凭据存储尚未初始化")
|
||||||
}
|
}
|
||||||
values, err := normalizeNotificationCredentials(cfg.Notification.HTTPAuthMode, item.HTTPCredentials)
|
values, err := normalizeNotificationCredentials(cfg.Notification.HTTPAuthMode, item.HTTPCredentials)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return createdCredentialRefs, err
|
||||||
}
|
}
|
||||||
ref, err := newNotificationCredentialReference()
|
ref, err := newNotificationCredentialReference()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return createdCredentialRefs, err
|
||||||
}
|
}
|
||||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||||
return err
|
return createdCredentialRefs, err
|
||||||
}
|
}
|
||||||
|
createdCredentialRefs = append(createdCredentialRefs, ref)
|
||||||
cfg.Notification.HTTPCredentialRef = ref
|
cfg.Notification.HTTPCredentialRef = ref
|
||||||
}
|
}
|
||||||
if item.SMTPPassword == nil || *item.SMTPPassword == "" {
|
if item.SMTPPassword == nil || *item.SMTPPassword == "" {
|
||||||
return nil
|
return createdCredentialRefs, nil
|
||||||
}
|
}
|
||||||
if s.secrets == nil {
|
if s.secrets == nil {
|
||||||
return errors.New("SMTP 通知敏感凭据存储尚未初始化")
|
return createdCredentialRefs, errors.New("SMTP 通知敏感凭据存储尚未初始化")
|
||||||
}
|
}
|
||||||
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
username := strings.TrimSpace(cfg.Notification.SMTPUsername)
|
||||||
if username == "" {
|
if username == "" {
|
||||||
return errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
return createdCredentialRefs, errors.New("填写 SMTP 密码前必须配置 SMTP 用户名")
|
||||||
}
|
}
|
||||||
ref, err := newNotificationCredentialReference()
|
ref, err := newNotificationCredentialReference()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return createdCredentialRefs, err
|
||||||
}
|
}
|
||||||
values := map[string]string{"username": username, "password": *item.SMTPPassword}
|
values := map[string]string{"username": username, "password": *item.SMTPPassword}
|
||||||
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
if err := s.secrets.Put(ctx, ref, values); err != nil {
|
||||||
return err
|
return createdCredentialRefs, err
|
||||||
}
|
}
|
||||||
|
createdCredentialRefs = append(createdCredentialRefs, ref)
|
||||||
cfg.Notification.SMTPCredentialRef = ref
|
cfg.Notification.SMTPCredentialRef = ref
|
||||||
return nil
|
return createdCredentialRefs, nil
|
||||||
}
|
}
|
||||||
@@ -202,6 +202,17 @@ func (s *Server) applySetup(c *gin.Context) {
|
|||||||
s.writeError(c, http.StatusBadRequest, err.Error(), nil)
|
s.writeError(c, http.StatusBadRequest, err.Error(), nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
dnsCredentialRetained := false
|
||||||
|
defer func() {
|
||||||
|
if dnsCredentialRetained || s.secrets == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cleanupContext, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.secrets.Delete(cleanupContext, strings.TrimSpace(request.DNSCredentialRef)); err != nil && s.logger != nil {
|
||||||
|
s.logger.Warn("\u521d\u59cb\u5316\u5931\u8d25\u540e\u6e05\u7406 DNS \u51ed\u6362\u5931\u8d25", "error", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
webEnabled := true
|
webEnabled := true
|
||||||
if request.WebEnabled != nil {
|
if request.WebEnabled != nil {
|
||||||
webEnabled = *request.WebEnabled
|
webEnabled = *request.WebEnabled
|
||||||
@@ -430,6 +441,7 @@ func (s *Server) applySetup(c *gin.Context) {
|
|||||||
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败", err)
|
s.writeError(c, http.StatusInternalServerError, "保存初始化配置失败", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
dnsCredentialRetained = true
|
||||||
if err := s.setupDNS.Consume(request.DNSVerificationToken, request.DNSProvider, request.DNSCredentialRef, testDomain); err != nil && s.logger != nil {
|
if err := s.setupDNS.Consume(request.DNSVerificationToken, request.DNSProvider, request.DNSCredentialRef, testDomain); err != nil && s.logger != nil {
|
||||||
s.logger.Warn("初始化配置已保存,但清理 DNS 验证令牌失败", "error", err)
|
s.logger.Warn("初始化配置已保存,但清理 DNS 验证令牌失败", "error", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -747,3 +747,31 @@ func TestSetupFirewallFailureRollsBackIssuedCertificate(t *testing.T) {
|
|||||||
t.Fatal("防火墙配置失败时应回滚已保存的初始化证书")
|
t.Fatal("防火墙配置失败时应回滚已保存的初始化证书")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetupFailureDeletesTemporaryDNSCredential(t *testing.T) {
|
||||||
|
baseDir := t.TempDir()
|
||||||
|
configPath := filepath.Join(baseDir, "config", "scert.json")
|
||||||
|
verifier := &fakeSetupDNSVerifier{}
|
||||||
|
secrets := &fakeSetupSecretWriter{values: map[string]map[string]string{
|
||||||
|
"secret://dns/cloudflare/test": {"api_token": "temporary-token"},
|
||||||
|
}}
|
||||||
|
server := New(Dependencies{
|
||||||
|
Config: config.Default(baseDir), ConfigPath: configPath,
|
||||||
|
Repository: &stubDomainRepository{}, SetupDNS: verifier, Secrets: secrets,
|
||||||
|
IssueSetupCertificate: newSetupCertificateIssuer(t, baseDir, errors.New("simulated certificate failure")),
|
||||||
|
})
|
||||||
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/setup", strings.NewReader(setupPayload(baseDir, "secure1234")))
|
||||||
|
request.RemoteAddr = "127.0.0.1:53000"
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
if response.Code != http.StatusBadGateway {
|
||||||
|
t.Fatalf("setup certificate failure should return 502: %d %s", response.Code, response.Body.String())
|
||||||
|
}
|
||||||
|
if _, ok := secrets.values["secret://dns/cloudflare/test"]; ok {
|
||||||
|
t.Fatal("temporary DNS credential should be deleted after setup failure")
|
||||||
|
}
|
||||||
|
if len(secrets.deleted) != 1 || secrets.deleted[0] != "secret://dns/cloudflare/test" {
|
||||||
|
t.Fatalf("unexpected deleted DNS credentials: %v", secrets.deleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/passwordpolicy"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
type userRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireSuperAdmin(c *gin.Context) {
|
||||||
|
s.configMu.RLock()
|
||||||
|
setupReady := s.config.SetupReady
|
||||||
|
s.configMu.RUnlock()
|
||||||
|
if !setupReady {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
session, ok := s.currentAuthSession(c)
|
||||||
|
if !ok {
|
||||||
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "请先登录管理后台", "request_id": requestIDFromContext(c)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if session.Role != repository.UserRoleSuperAdmin {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "只有超级管理员可以管理用户", "request_id": requestIDFromContext(c)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.sameOriginForAPI(c.Request) {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "请求来源校验失败", "request_id": requestIDFromContext(c)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) listUsers(c *gin.Context) {
|
||||||
|
if s.users == nil {
|
||||||
|
s.writeError(c, http.StatusNotImplemented, "用户管理接口尚未配置", errors.New("用户仓储未配置"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items, err := s.users.ListUsers(c.Request.Context())
|
||||||
|
if err != nil {
|
||||||
|
s.writeError(c, http.StatusInternalServerError, "查询用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"items": items})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) getUser(c *gin.Context) {
|
||||||
|
if s.users == nil {
|
||||||
|
s.writeError(c, http.StatusNotImplemented, "用户管理接口尚未配置", errors.New("用户仓储未配置"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := s.users.GetUserByID(c.Request.Context(), c.Param("id"))
|
||||||
|
if err != nil {
|
||||||
|
if repository.IsNotFound(err) {
|
||||||
|
s.writeError(c, http.StatusNotFound, "用户不存在", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeError(c, http.StatusInternalServerError, "读取用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) createUser(c *gin.Context) {
|
||||||
|
if s.users == nil {
|
||||||
|
s.writeError(c, http.StatusNotImplemented, "用户管理接口尚未配置", errors.New("用户仓储未配置"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request userRequest
|
||||||
|
if err := c.ShouldBindJSON(&request); err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "用户参数无效", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := userFromRequest(request, "")
|
||||||
|
if err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "用户参数无效", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.users.CreateUser(c.Request.Context(), item); err != nil {
|
||||||
|
s.writeError(c, userErrorStatus(err), "创建用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.recordUserAudit(c, "创建用户", "success", item.ID)
|
||||||
|
c.JSON(http.StatusCreated, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) updateUser(c *gin.Context) {
|
||||||
|
if s.users == nil {
|
||||||
|
s.writeError(c, http.StatusNotImplemented, "用户管理接口尚未配置", errors.New("用户仓储未配置"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(c.Param("id"))
|
||||||
|
existing, err := s.users.GetUserByID(c.Request.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
if repository.IsNotFound(err) {
|
||||||
|
s.writeError(c, http.StatusNotFound, "用户不存在", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeError(c, http.StatusInternalServerError, "读取用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var request userRequest
|
||||||
|
if err := c.ShouldBindJSON(&request); err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "用户参数无效", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item, err := userFromRequest(request, id)
|
||||||
|
if err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "用户参数无效", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if request.Password == "" {
|
||||||
|
item.PasswordHash = existing.PasswordHash
|
||||||
|
}
|
||||||
|
if request.Role == "" {
|
||||||
|
item.Role = existing.Role
|
||||||
|
}
|
||||||
|
if request.Status == "" {
|
||||||
|
item.Status = existing.Status
|
||||||
|
}
|
||||||
|
if existing.Role == repository.UserRoleSuperAdmin && item.Role != repository.UserRoleSuperAdmin {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "不能降低超级管理员权限", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if existing.Role == repository.UserRoleSuperAdmin && item.Status == repository.UserStatusDisabled {
|
||||||
|
if err := s.ensureAnotherSuperAdmin(c, id); err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := s.users.UpdateUser(c.Request.Context(), item); err != nil {
|
||||||
|
s.writeError(c, userErrorStatus(err), "更新用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.invalidateUserSessions(id)
|
||||||
|
s.recordUserAudit(c, "更新用户", "success", id)
|
||||||
|
c.JSON(http.StatusOK, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) deleteUser(c *gin.Context) {
|
||||||
|
if s.users == nil {
|
||||||
|
s.writeError(c, http.StatusNotImplemented, "用户管理接口尚未配置", errors.New("用户仓储未配置"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(c.Param("id"))
|
||||||
|
session, _ := s.currentAuthSession(c)
|
||||||
|
if session.UserID != "" && session.UserID == id {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "不能删除当前登录用户", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
existing, err := s.users.GetUserByID(c.Request.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
if repository.IsNotFound(err) {
|
||||||
|
s.writeError(c, http.StatusNotFound, "用户不存在", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeError(c, http.StatusInternalServerError, "读取用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if existing.Role == repository.UserRoleSuperAdmin {
|
||||||
|
if existing.ID == "primary-super-admin" {
|
||||||
|
s.writeError(c, http.StatusBadRequest, "不能删除配置中的主超级管理员", repository.ErrSuperAdminProtected)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.ensureAnotherSuperAdmin(c, id); err != nil {
|
||||||
|
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := s.users.DeleteUser(c.Request.Context(), id); err != nil {
|
||||||
|
if errors.Is(err, repository.ErrSuperAdminProtected) {
|
||||||
|
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if repository.IsNotFound(err) {
|
||||||
|
s.writeError(c, http.StatusNotFound, "用户不存在", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.writeError(c, userErrorStatus(err), "删除用户失败", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.invalidateUserSessions(id)
|
||||||
|
s.recordUserAudit(c, "删除用户", "success", id)
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) ensureAnotherSuperAdmin(c *gin.Context, currentID string) error {
|
||||||
|
items, err := s.users.ListUsers(c.Request.Context())
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("无法确认超级管理员数量")
|
||||||
|
}
|
||||||
|
for _, item := range items {
|
||||||
|
if item.Role == repository.UserRoleSuperAdmin && item.Status == repository.UserStatusActive && item.ID != currentID {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.New("不能禁用最后一个超级管理员")
|
||||||
|
}
|
||||||
|
|
||||||
|
func userFromRequest(request userRequest, id string) (repository.User, error) {
|
||||||
|
username := strings.TrimSpace(strings.ToLower(request.Username))
|
||||||
|
if username == "" {
|
||||||
|
return repository.User{}, errors.New("用户名不能为空")
|
||||||
|
}
|
||||||
|
if request.Password == "" && id == "" {
|
||||||
|
return repository.User{}, errors.New("密码不能为空")
|
||||||
|
}
|
||||||
|
item := repository.User{
|
||||||
|
ID: id, Username: username, Email: request.Email,
|
||||||
|
Role: strings.TrimSpace(strings.ToLower(request.Role)), Status: strings.TrimSpace(strings.ToLower(request.Status)),
|
||||||
|
}
|
||||||
|
if item.Role == "" {
|
||||||
|
item.Role = repository.UserRoleUser
|
||||||
|
}
|
||||||
|
if item.Status == "" {
|
||||||
|
item.Status = repository.UserStatusActive
|
||||||
|
}
|
||||||
|
if request.Password != "" {
|
||||||
|
if err := passwordpolicy.ValidateAccountPassword(request.Password, username); err != nil {
|
||||||
|
return repository.User{}, err
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return repository.User{}, errors.New("生成密码摘要失败")
|
||||||
|
}
|
||||||
|
item.PasswordHash = string(hash)
|
||||||
|
}
|
||||||
|
if item.ID == "" {
|
||||||
|
item.ID = domain.NewID()
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) recordUserAudit(c *gin.Context, action, status, id string) {
|
||||||
|
if s.audit == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||||
|
Action: action, ResourceType: "user", ResourceID: id, Status: status, Message: action,
|
||||||
|
}); err != nil && s.logger != nil {
|
||||||
|
s.logger.Warn("保存用户审计日志失败", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func userErrorStatus(err error) int {
|
||||||
|
if repository.IsConflict(err) {
|
||||||
|
return http.StatusConflict
|
||||||
|
}
|
||||||
|
if repository.IsNotFound(err) {
|
||||||
|
return http.StatusNotFound
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), "不能为空") || strings.Contains(err.Error(), "无效") || strings.Contains(err.Error(), "长度") || strings.Contains(err.Error(), "不能") {
|
||||||
|
return http.StatusBadRequest
|
||||||
|
}
|
||||||
|
return http.StatusInternalServerError
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUserManagementAuthorizationAndCRUD(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory)
|
||||||
|
cfg.SetupReady = true
|
||||||
|
cfg.Admin.Username = "admin"
|
||||||
|
cfg.Admin.Email = "admin@example.test"
|
||||||
|
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
|
||||||
|
cfg.Database.DSN = filepath.Join(directory, "data", "users-api.db")
|
||||||
|
db, err := database.Open(t.Context(), cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开用户 API 测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
t.Fatalf("迁移用户 API 测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
users := repository.NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
if err := users.EnsureSuperAdmin(t.Context(), repository.User{
|
||||||
|
ID: "primary-super-admin", Username: cfg.Admin.Username, Email: cfg.Admin.Email,
|
||||||
|
PasswordHash: cfg.Admin.PasswordHash,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("保存用户 API 测试超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{}, Users: users})
|
||||||
|
|
||||||
|
unauthorized := serveUserRequest(server, nil, http.MethodGet, "/api/v1/users", "")
|
||||||
|
if unauthorized.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("未登录请求应返回 401:%d %s", unauthorized.Code, unauthorized.Body.String())
|
||||||
|
}
|
||||||
|
regularCookie := httpUserSessionCookie(server, "user-1", repository.UserRoleUser)
|
||||||
|
forbidden := serveUserRequest(server, regularCookie, http.MethodGet, "/api/v1/users", "")
|
||||||
|
if forbidden.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("普通用户请求应返回 403:%d %s", forbidden.Code, forbidden.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
adminCookie := httpUserSessionCookie(server, "primary-super-admin", repository.UserRoleSuperAdmin)
|
||||||
|
created := serveUserRequest(server, adminCookie, http.MethodPost, "/api/v1/users", `{"username":"operator","email":"operator@example.test","password":"UserPass123","role":"user","status":"active"}`)
|
||||||
|
if created.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("创建用户失败:%d %s", created.Code, created.Body.String())
|
||||||
|
}
|
||||||
|
if strings.Contains(created.Body.String(), "password_hash") || strings.Contains(created.Body.String(), "UserPass123") {
|
||||||
|
t.Fatalf("创建用户响应泄露敏感字段:%s", created.Body.String())
|
||||||
|
}
|
||||||
|
var createdUser repository.User
|
||||||
|
if err := json.Unmarshal(created.Body.Bytes(), &createdUser); err != nil || createdUser.ID == "" {
|
||||||
|
t.Fatalf("解析创建用户响应失败:%v %s", err, created.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
listed := serveUserRequest(server, adminCookie, http.MethodGet, "/api/v1/users", "")
|
||||||
|
if listed.Code != http.StatusOK || !strings.Contains(listed.Body.String(), "operator") {
|
||||||
|
t.Fatalf("查询用户失败:%d %s", listed.Code, listed.Body.String())
|
||||||
|
}
|
||||||
|
updated := serveUserRequest(server, adminCookie, http.MethodPut, "/api/v1/users/"+createdUser.ID, `{"username":"operator","email":"operator@example.test","role":"admin","status":"disabled"}`)
|
||||||
|
if updated.Code != http.StatusOK || !strings.Contains(updated.Body.String(), "admin") {
|
||||||
|
t.Fatalf("更新用户失败:%d %s", updated.Code, updated.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
loginDisabled := httptest.NewRecorder()
|
||||||
|
loginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"operator","password":"UserPass123"}`))
|
||||||
|
loginRequest.Header.Set("Content-Type", "application/json")
|
||||||
|
server.Handler().ServeHTTP(loginDisabled, loginRequest)
|
||||||
|
if loginDisabled.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("禁用用户登录应被拒绝:%d %s", loginDisabled.Code, loginDisabled.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
secondSuperAdmin := serveUserRequest(server, adminCookie, http.MethodPost, "/api/v1/users", `{"username":"owner","password":"OwnerPass123","role":"super_admin","status":"active"}`)
|
||||||
|
if secondSuperAdmin.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("创建第二个超级管理员失败:%d %s", secondSuperAdmin.Code, secondSuperAdmin.Body.String())
|
||||||
|
}
|
||||||
|
var second repository.User
|
||||||
|
if err := json.Unmarshal(secondSuperAdmin.Body.Bytes(), &second); err != nil || second.ID == "" {
|
||||||
|
t.Fatalf("解析第二个超级管理员响应失败:%v %s", err, secondSuperAdmin.Body.String())
|
||||||
|
}
|
||||||
|
deleted := serveUserRequest(server, adminCookie, http.MethodDelete, "/api/v1/users/"+second.ID, "")
|
||||||
|
if deleted.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("删除第二个超级管理员失败:%d %s", deleted.Code, deleted.Body.String())
|
||||||
|
}
|
||||||
|
protected := serveUserRequest(server, adminCookie, http.MethodDelete, "/api/v1/users/primary-super-admin", "")
|
||||||
|
if protected.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("删除主超级管理员应被拒绝:%d %s", protected.Code, protected.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveUserRequest(server *Server, cookie *http.Cookie, method, path, body string) *httptest.ResponseRecorder {
|
||||||
|
request := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||||
|
if body != "" {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if cookie != nil {
|
||||||
|
request.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
response := httptest.NewRecorder()
|
||||||
|
server.Handler().ServeHTTP(response, request)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpUserSessionCookie(server *Server, userID, role string) *http.Cookie {
|
||||||
|
token := userID + "-session"
|
||||||
|
now := time.Now()
|
||||||
|
server.authMu.Lock()
|
||||||
|
server.authSessions[token] = authSession{
|
||||||
|
UserID: userID, Username: userID, Role: role,
|
||||||
|
ExpiresAt: now.Add(time.Hour), AbsoluteExpiresAt: now.Add(2 * time.Hour),
|
||||||
|
}
|
||||||
|
server.authMu.Unlock()
|
||||||
|
return &http.Cookie{Name: authCookieName, Value: token, Path: "/"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpUserPasswordHash(t *testing.T, password string) string {
|
||||||
|
t.Helper()
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("生成用户测试密码摘要失败:%v", err)
|
||||||
|
}
|
||||||
|
return string(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = context.Background
|
||||||
@@ -12,28 +12,38 @@ const (
|
|||||||
MaxLength = 12
|
MaxLength = 12
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Validate 校验管理员密码是否符合策略。
|
||||||
func Validate(password, username string) error {
|
func Validate(password, username string) error {
|
||||||
|
return validate(password, username, "管理员密码")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateAccountPassword 校验普通账户密码是否符合策略。
|
||||||
|
func ValidateAccountPassword(password, username string) error {
|
||||||
|
return validate(password, username, "账户密码")
|
||||||
|
}
|
||||||
|
|
||||||
|
func validate(password, username, label string) error {
|
||||||
length := utf8.RuneCountInString(password)
|
length := utf8.RuneCountInString(password)
|
||||||
if length < MinLength {
|
if length < MinLength {
|
||||||
return fmt.Errorf("超级管理员密码至少需要 %d 个字符", MinLength)
|
return fmt.Errorf("%s长度不能少于 %d 个字符", label, MinLength)
|
||||||
}
|
}
|
||||||
if length > MaxLength {
|
if length > MaxLength {
|
||||||
return fmt.Errorf("超级管理员密码最多允许 %d 个字符", MaxLength)
|
return fmt.Errorf("%s长度不能超过 %d 个字符", label, MaxLength)
|
||||||
}
|
}
|
||||||
if strings.EqualFold(password, strings.TrimSpace(username)) {
|
if strings.EqualFold(password, strings.TrimSpace(username)) {
|
||||||
return fmt.Errorf("超级管理员密码不能与用户名相同")
|
return fmt.Errorf("%s不能与用户名相同", label)
|
||||||
}
|
}
|
||||||
hasLetter := false
|
hasLetter := false
|
||||||
hasDigit := false
|
hasDigit := false
|
||||||
for _, value := range password {
|
for _, value := range password {
|
||||||
if unicode.IsControl(value) {
|
if unicode.IsControl(value) {
|
||||||
return fmt.Errorf("超级管理员密码不能包含控制字符")
|
return fmt.Errorf("%s不能包含控制字符", label)
|
||||||
}
|
}
|
||||||
hasLetter = hasLetter || unicode.IsLetter(value)
|
hasLetter = hasLetter || unicode.IsLetter(value)
|
||||||
hasDigit = hasDigit || unicode.IsDigit(value)
|
hasDigit = hasDigit || unicode.IsDigit(value)
|
||||||
}
|
}
|
||||||
if !hasLetter || !hasDigit {
|
if !hasLetter || !hasDigit {
|
||||||
return fmt.Errorf("超级管理员密码必须同时包含字母和数字")
|
return fmt.Errorf("%s必须同时包含字母和数字", label)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/auth"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserRoleSuperAdmin = "super_admin"
|
||||||
|
UserRoleAdmin = "admin"
|
||||||
|
UserRoleUser = "user"
|
||||||
|
UserStatusActive = "active"
|
||||||
|
UserStatusDisabled = "disabled"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrSuperAdminProtected = errors.New("超级管理员不能删除")
|
||||||
|
|
||||||
|
// User 表示一个可登录的管理后台用户。密码摘要不会被 JSON 输出。
|
||||||
|
type User struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
PasswordHash string `json:"-"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRepository interface {
|
||||||
|
EnsureSuperAdmin(context.Context, User) error
|
||||||
|
FindByIdentifier(context.Context, string) (User, error)
|
||||||
|
ListUsers(context.Context) ([]User, error)
|
||||||
|
GetUserByID(context.Context, string) (User, error)
|
||||||
|
CreateUser(context.Context, User) error
|
||||||
|
UpdateUser(context.Context, User) error
|
||||||
|
DeleteUser(context.Context, string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type SQLUserRepository struct {
|
||||||
|
db *sql.DB
|
||||||
|
driver string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSQLUserRepository(db *sql.DB, driver ...string) *SQLUserRepository {
|
||||||
|
selectedDriver := "sqlite"
|
||||||
|
if len(driver) > 0 && strings.TrimSpace(driver[0]) != "" {
|
||||||
|
selectedDriver = strings.ToLower(strings.TrimSpace(driver[0]))
|
||||||
|
}
|
||||||
|
return &SQLUserRepository{db: db, driver: selectedDriver}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) EnsureSuperAdmin(ctx context.Context, item User) error {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
item.Role = UserRoleSuperAdmin
|
||||||
|
item.Status = UserStatusActive
|
||||||
|
item = normalizeUser(item)
|
||||||
|
if item.ID == "" {
|
||||||
|
item.ID = "primary-super-admin"
|
||||||
|
}
|
||||||
|
if err := validateUser(item, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := r.upsert(ctx, item); err != nil {
|
||||||
|
return fmt.Errorf("同步超级管理员失败:%w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) FindByIdentifier(ctx context.Context, identifier string) (User, error) {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return User{}, err
|
||||||
|
}
|
||||||
|
normalized, err := auth.NormalizeIdentifier(identifier)
|
||||||
|
if err != nil {
|
||||||
|
return User{}, err
|
||||||
|
}
|
||||||
|
row := r.db.QueryRowContext(ctx, userSelect+` WHERE LOWER(username) = ? OR (email IS NOT NULL AND LOWER(email) = ?) LIMIT 1`, normalized, normalized)
|
||||||
|
return scanUser(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) ListUsers(ctx context.Context) ([]User, error) {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, userSelect+` ORDER BY role, username, id`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("查询用户失败:%w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := make([]User, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
item, err := scanUser(rows)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("读取用户失败:%w", err)
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) GetUserByID(ctx context.Context, id string) (User, error) {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return User{}, err
|
||||||
|
}
|
||||||
|
id = strings.TrimSpace(id)
|
||||||
|
if id == "" {
|
||||||
|
return User{}, errors.New("用户 ID 不能为空")
|
||||||
|
}
|
||||||
|
return scanUser(r.db.QueryRowContext(ctx, userSelect+` WHERE id = ?`, id))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) CreateUser(ctx context.Context, item User) error {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
item = normalizeUser(item)
|
||||||
|
if err := validateUser(item, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if item.CreatedAt.IsZero() {
|
||||||
|
item.CreatedAt = time.Now().UTC()
|
||||||
|
}
|
||||||
|
if item.UpdatedAt.IsZero() {
|
||||||
|
item.UpdatedAt = item.CreatedAt
|
||||||
|
}
|
||||||
|
_, err := r.db.ExecContext(ctx, `INSERT INTO users
|
||||||
|
(id, username, email, password_hash, role, status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||||
|
item.Role, item.Status, item.CreatedAt, item.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("保存用户失败:%w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) UpdateUser(ctx context.Context, item User) error {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
item = normalizeUser(item)
|
||||||
|
if err := validateUser(item, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
result, err := r.db.ExecContext(ctx, `UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||||
|
item.Username, r.emailValue(item.Email), item.PasswordHash, item.Role, item.Status, time.Now().UTC(), item.ID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("更新用户失败:%w", err)
|
||||||
|
}
|
||||||
|
count, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("读取用户更新结果失败:%w", err)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) DeleteUser(ctx context.Context, id string) error {
|
||||||
|
if err := r.ensureDB(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id = strings.TrimSpace(id)
|
||||||
|
if id == "" {
|
||||||
|
return errors.New("用户 ID 不能为空")
|
||||||
|
}
|
||||||
|
if id == "primary-super-admin" {
|
||||||
|
return ErrSuperAdminProtected
|
||||||
|
}
|
||||||
|
result, err := r.db.ExecContext(ctx, `DELETE FROM users WHERE id = ?`, id)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("删除用户失败:%w", err)
|
||||||
|
}
|
||||||
|
count, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("读取用户删除结果失败:%w", err)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) ensureDB() error {
|
||||||
|
if r == nil || r.db == nil {
|
||||||
|
return errors.New("数据库连接不能为空")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) upsert(ctx context.Context, item User) error {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
if item.CreatedAt.IsZero() {
|
||||||
|
item.CreatedAt = now
|
||||||
|
}
|
||||||
|
item.UpdatedAt = now
|
||||||
|
result, err := r.db.ExecContext(ctx, `UPDATE users SET username = ?, email = ?, password_hash = ?, role = ?, status = ?, updated_at = ? WHERE id = ?`,
|
||||||
|
item.Username, r.emailValue(item.Email), item.PasswordHash, item.Role, item.Status, item.UpdatedAt, item.ID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
count, err := result.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if count > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, err = r.db.ExecContext(ctx, `INSERT INTO users
|
||||||
|
(id, username, email, password_hash, role, status, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, item.ID, item.Username, r.emailValue(item.Email), item.PasswordHash,
|
||||||
|
item.Role, item.Status, item.CreatedAt, item.UpdatedAt)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SQLUserRepository) emailValue(email string) any {
|
||||||
|
if email == "" && r.driver == "mysql" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return email
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeUser(item User) User {
|
||||||
|
item.ID = strings.TrimSpace(item.ID)
|
||||||
|
item.Username = strings.TrimSpace(strings.ToLower(item.Username))
|
||||||
|
item.Email = strings.TrimSpace(strings.ToLower(item.Email))
|
||||||
|
item.Role = strings.TrimSpace(strings.ToLower(item.Role))
|
||||||
|
item.Status = strings.TrimSpace(strings.ToLower(item.Status))
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateUser(item User, allowEmptyID bool) error {
|
||||||
|
item = normalizeUser(item)
|
||||||
|
if item.ID == "" && !allowEmptyID {
|
||||||
|
return errors.New("用户 ID 不能为空")
|
||||||
|
}
|
||||||
|
if len([]byte(item.Username)) < 3 || len([]byte(item.Username)) > 64 {
|
||||||
|
return errors.New("用户名长度必须为 3 到 64 个字符")
|
||||||
|
}
|
||||||
|
if strings.Contains(item.Username, "@") {
|
||||||
|
return errors.New("用户名格式无效")
|
||||||
|
}
|
||||||
|
for _, char := range item.Username {
|
||||||
|
if unicode.IsSpace(char) || unicode.IsControl(char) {
|
||||||
|
return errors.New("用户名不能包含空格或控制字符")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch item.Username {
|
||||||
|
case "admin", "administrator", "root", "system", "scert":
|
||||||
|
if item.Role != UserRoleSuperAdmin || item.Username != "admin" {
|
||||||
|
return errors.New("用户名为系统保留名称")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if item.Email != "" {
|
||||||
|
if _, err := auth.NormalizeIdentifier(item.Email); err != nil || !strings.Contains(item.Email, "@") {
|
||||||
|
return errors.New("邮箱格式无效")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := bcrypt.Cost([]byte(item.PasswordHash)); err != nil {
|
||||||
|
return errors.New("密码摘要无效")
|
||||||
|
}
|
||||||
|
if item.Role != UserRoleSuperAdmin && item.Role != UserRoleAdmin && item.Role != UserRoleUser {
|
||||||
|
return fmt.Errorf("用户角色无效:%s", item.Role)
|
||||||
|
}
|
||||||
|
if item.Status != UserStatusActive && item.Status != UserStatusDisabled {
|
||||||
|
return fmt.Errorf("用户状态无效:%s", item.Status)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const userSelect = `SELECT id, username, email, password_hash, role, status, created_at, updated_at FROM users`
|
||||||
|
|
||||||
|
func scanUser(row interface{ Scan(...any) error }) (User, error) {
|
||||||
|
var item User
|
||||||
|
var email sql.NullString
|
||||||
|
if err := row.Scan(&item.ID, &item.Username, &email, &item.PasswordHash, &item.Role, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
|
||||||
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
return User{}, sql.ErrNoRows
|
||||||
|
}
|
||||||
|
return User{}, fmt.Errorf("读取用户失败:%w", err)
|
||||||
|
}
|
||||||
|
if email.Valid {
|
||||||
|
item.Email = email.String
|
||||||
|
}
|
||||||
|
return normalizeUser(item), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
package repository
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||||
|
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSQLUserRepositoryCRUDAndLookup(t *testing.T) {
|
||||||
|
db := openUserTestDatabase(t)
|
||||||
|
defer db.Close()
|
||||||
|
repo := NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
hash := userTestPasswordHash(t, "UserPass123")
|
||||||
|
item := User{ID: "user-1", Username: "Operator", Email: "Operator@Example.Test", PasswordHash: hash, Role: UserRoleUser, Status: UserStatusActive}
|
||||||
|
if err := repo.CreateUser(t.Context(), item); err != nil {
|
||||||
|
t.Fatalf("创建用户失败:%v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
byName, err := repo.FindByIdentifier(t.Context(), " operator ")
|
||||||
|
if err != nil || byName.ID != item.ID || byName.Username != "operator" {
|
||||||
|
t.Fatalf("按用户名查询用户失败:%v %+v", err, byName)
|
||||||
|
}
|
||||||
|
byEmail, err := repo.FindByIdentifier(t.Context(), "OPERATOR@EXAMPLE.TEST")
|
||||||
|
if err != nil || byEmail.ID != item.ID || byEmail.Email != "operator@example.test" {
|
||||||
|
t.Fatalf("按邮箱查询用户失败:%v %+v", err, byEmail)
|
||||||
|
}
|
||||||
|
|
||||||
|
encoded, err := json.Marshal(byName)
|
||||||
|
if err != nil || strings.Contains(string(encoded), hash) || strings.Contains(string(encoded), "password_hash") {
|
||||||
|
t.Fatalf("用户 JSON 不应包含密码摘要:%s", encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
updated := byName
|
||||||
|
updated.Role = UserRoleAdmin
|
||||||
|
updated.Status = UserStatusDisabled
|
||||||
|
if err := repo.UpdateUser(t.Context(), updated); err != nil {
|
||||||
|
t.Fatalf("更新用户失败:%v", err)
|
||||||
|
}
|
||||||
|
loaded, err := repo.GetUserByID(t.Context(), item.ID)
|
||||||
|
if err != nil || loaded.Role != UserRoleAdmin || loaded.Status != UserStatusDisabled {
|
||||||
|
t.Fatalf("读取更新后的用户失败:%v %+v", err, loaded)
|
||||||
|
}
|
||||||
|
if bcrypt.CompareHashAndPassword([]byte(loaded.PasswordHash), []byte("UserPass123")) != nil {
|
||||||
|
t.Fatal("更新用户不应改变原密码")
|
||||||
|
}
|
||||||
|
|
||||||
|
items, err := repo.ListUsers(t.Context())
|
||||||
|
if err != nil || len(items) != 1 {
|
||||||
|
t.Fatalf("列出用户失败:%v %+v", err, items)
|
||||||
|
}
|
||||||
|
if err := repo.DeleteUser(t.Context(), item.ID); err != nil {
|
||||||
|
t.Fatalf("删除用户失败:%v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.GetUserByID(t.Context(), item.ID); !errors.Is(err, context.Canceled) && !IsNotFound(err) {
|
||||||
|
t.Fatalf("删除用户后查询结果错误:%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSQLUserRepositoryEnforcesIdentityAndSuperAdminRules(t *testing.T) {
|
||||||
|
db := openUserTestDatabase(t)
|
||||||
|
defer db.Close()
|
||||||
|
repo := NewSQLUserRepository(db.DB, "sqlite")
|
||||||
|
first := User{ID: "user-1", Username: "operator", Email: "operator@example.test", PasswordHash: userTestPasswordHash(t, "UserPass123"), Role: UserRoleUser, Status: UserStatusActive}
|
||||||
|
if err := repo.CreateUser(t.Context(), first); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
duplicateName := first
|
||||||
|
duplicateName.ID = "user-2"
|
||||||
|
duplicateName.Email = "second@example.test"
|
||||||
|
if err := repo.CreateUser(t.Context(), duplicateName); !IsConflict(err) {
|
||||||
|
t.Fatalf("重复用户名未被拒绝:%v", err)
|
||||||
|
}
|
||||||
|
duplicateEmail := first
|
||||||
|
duplicateEmail.ID = "user-3"
|
||||||
|
duplicateEmail.Username = "second"
|
||||||
|
if err := repo.CreateUser(t.Context(), duplicateEmail); !IsConflict(err) {
|
||||||
|
t.Fatalf("重复邮箱未被拒绝:%v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := repo.EnsureSuperAdmin(t.Context(), User{ID: "primary-super-admin", Username: "admin", Email: "admin@example.test", PasswordHash: userTestPasswordHash(t, "AdminPass123")}); err != nil {
|
||||||
|
t.Fatalf("保存超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := repo.DeleteUser(t.Context(), "primary-super-admin"); !errors.Is(err, ErrSuperAdminProtected) {
|
||||||
|
t.Fatalf("主超级管理员不应被删除:%v", err)
|
||||||
|
}
|
||||||
|
secondAdmin := User{ID: "super-2", Username: "owner", PasswordHash: userTestPasswordHash(t, "OwnerPass123"), Role: UserRoleSuperAdmin, Status: UserStatusActive}
|
||||||
|
if err := repo.CreateUser(t.Context(), secondAdmin); err != nil {
|
||||||
|
t.Fatalf("创建第二个超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := repo.DeleteUser(t.Context(), secondAdmin.ID); err != nil {
|
||||||
|
t.Fatalf("删除第二个超级管理员失败:%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSQLUserRepositoryNilDatabase(t *testing.T) {
|
||||||
|
var repo *SQLUserRepository
|
||||||
|
if err := repo.CreateUser(context.Background(), User{}); err == nil {
|
||||||
|
t.Fatal("空数据库连接应返回错误")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func openUserTestDatabase(t *testing.T) *database.Database {
|
||||||
|
t.Helper()
|
||||||
|
directory := t.TempDir()
|
||||||
|
cfg := config.Default(directory).Database
|
||||||
|
cfg.DSN = filepath.Join(directory, "data", "users.db")
|
||||||
|
db, err := database.Open(t.Context(), cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("打开用户测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||||
|
_ = db.Close()
|
||||||
|
t.Fatalf("迁移用户测试数据库失败:%v", err)
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
func userTestPasswordHash(t *testing.T, password string) string {
|
||||||
|
t.Helper()
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("生成测试密码摘要失败:%v", err)
|
||||||
|
}
|
||||||
|
return string(hash)
|
||||||
|
}
|
||||||
@@ -108,6 +108,10 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
|||||||
Err: err,
|
Err: err,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
verificationToken, err := secureToken(32)
|
||||||
|
if err != nil {
|
||||||
|
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 验证令牌失败:%w", err)
|
||||||
|
}
|
||||||
credentialID, err := secureToken(18)
|
credentialID, err := secureToken(18)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 凭据引用失败:%w", err)
|
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 凭据引用失败:%w", err)
|
||||||
@@ -116,10 +120,6 @@ func (m *DNSVerificationManager) Verify(ctx context.Context, input DNSVerificati
|
|||||||
if err := m.store.Put(ctx, credentialRef, normalizedCredentials); err != nil {
|
if err := m.store.Put(ctx, credentialRef, normalizedCredentials); err != nil {
|
||||||
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err)
|
return DNSVerificationResult{}, fmt.Errorf("加密保存 DNS 凭据失败:%w", err)
|
||||||
}
|
}
|
||||||
verificationToken, err := secureToken(32)
|
|
||||||
if err != nil {
|
|
||||||
return DNSVerificationResult{}, fmt.Errorf("生成 DNS 验证令牌失败:%w", err)
|
|
||||||
}
|
|
||||||
expiresAt := m.now().UTC().Add(dnsVerificationLifetime)
|
expiresAt := m.now().UTC().Add(dnsVerificationLifetime)
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
m.clearExpiredLocked(m.now().UTC())
|
m.clearExpiredLocked(m.now().UTC())
|
||||||
|
|||||||
Binary file not shown.
+9
-2
@@ -1,6 +1,6 @@
|
|||||||
# SSH 密钥配置指南
|
# SSH 密钥配置指南
|
||||||
|
|
||||||
本文用于帮助不熟悉 SSH 的用户完成 Scert 远程服务器部署配置。Scert 只使用 SSH 密钥认证,不保存或使用远程服务器登录密码。
|
本文用于帮助不熟悉 SSH 的用户完成 Scert 远程服务器部署配置。Scert 只使用 SSH 密钥认证,不保存或使用远程服务器登录密码。本机为每台主机、每次配置生成随机密钥文件名,最终公钥路径为 `/ssl/ssh/<用户名>+scert-<随机标识>`,不保留 `.pub` 后缀。
|
||||||
|
|
||||||
## 一、配置流程
|
## 一、配置流程
|
||||||
|
|
||||||
@@ -116,6 +116,13 @@ Windows 服务器需要先确认 OpenSSH Server 已安装并运行。对于普
|
|||||||
6. 确认内容无误后点击“加密保存”。
|
6. 确认内容无误后点击“加密保存”。
|
||||||
7. 返回服务器配置,选择刚刚保存的 SSH 私钥。
|
7. 返回服务器配置,选择刚刚保存的 SSH 私钥。
|
||||||
|
|
||||||
|
Scert 页面显示的本机密钥路径遵循以下规则:
|
||||||
|
|
||||||
|
- 私钥:`/ssl/ssh/<用户名>+scert-<随机标识>.key`
|
||||||
|
- 公钥:`/ssl/ssh/<用户名>+scert-<随机标识>`
|
||||||
|
|
||||||
|
生成命令会先由 `ssh-keygen` 临时产生 `.pub` 文件,然后将该文件移动为不带 `.pub` 后缀的公钥目标文件。每台主机、每次新建配置都会生成新的随机标识;远程服务器仍只需要把公钥内容追加到授权文件。
|
||||||
|
|
||||||
读取本机私钥文件只会把内容放入当前页面内存,仍需点击“加密保存”才会提交。关闭窗口或刷新页面前,请确认已经完成保存。
|
读取本机私钥文件只会把内容放入当前页面内存,仍需点击“加密保存”才会提交。关闭窗口或刷新页面前,请确认已经完成保存。
|
||||||
|
|
||||||
## 七、测试连接前检查
|
## 七、测试连接前检查
|
||||||
@@ -168,4 +175,4 @@ Windows 服务器需要先确认 OpenSSH Server 已安装并运行。对于普
|
|||||||
- 不要把私钥粘贴到远程服务器;远程服务器只需要公钥。
|
- 不要把私钥粘贴到远程服务器;远程服务器只需要公钥。
|
||||||
- 不要覆盖远程服务器已有的 `authorized_keys` 文件。
|
- 不要覆盖远程服务器已有的 `authorized_keys` 文件。
|
||||||
- 服务器地址、端口、用户和主机指纹应按环境分别配置。
|
- 服务器地址、端口、用户和主机指纹应按环境分别配置。
|
||||||
- 测试机的配置不能直接复制到生产环境。
|
- 测试机的配置不能直接复制到生产环境。
|
||||||
+4
-4
@@ -2885,9 +2885,9 @@ Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无
|
|||||||
### 69.1 本轮需求与实现状态
|
### 69.1 本轮需求与实现状态
|
||||||
|
|
||||||
- [✓] 本机 SSH 密钥统一使用 `/ssl/ssh/` 目录生成。
|
- [✓] 本机 SSH 密钥统一使用 `/ssl/ssh/` 目录生成。
|
||||||
- [✓] 密钥文件名使用 `用户名+scert-随机标识` 格式,公钥文件追加 `.pub`。
|
- [✓] 密钥文件名使用 `用户名+scert-随机标识` 格式,公钥最终保存为不带 `.pub` 后缀的文件。
|
||||||
- [✓] 每次打开 SSH 密钥配置弹窗都会重新生成随机标识,避免不同主机或不同配置复用固定文件名。
|
- [✓] 每次打开 SSH 密钥配置弹窗都会重新生成随机标识,避免不同主机或不同配置复用固定文件名。
|
||||||
- [✓] Windows、Linux/macOS 密钥生成命令和公钥安装命令统一使用当前随机路径。
|
- [✓] Windows、Linux/macOS 密钥生成命令会临时产生 `.pub` 文件,随后移动为当前随机路径对应的不带 `.pub` 后缀的公钥文件,安装命令统一使用该最终路径。
|
||||||
- [✓] 页面显示本次密钥文件名、本地私钥路径、本地公钥路径和远程登录目标。
|
- [✓] 页面显示本次密钥文件名、本地私钥路径、本地公钥路径和远程登录目标。
|
||||||
- [✓] Scert 后端仍仅保存加密敏感信息引用,不将本地明文私钥路径或私钥内容写入普通配置。
|
- [✓] Scert 后端仍仅保存加密敏感信息引用,不将本地明文私钥路径或私钥内容写入普通配置。
|
||||||
|
|
||||||
@@ -2896,7 +2896,7 @@ Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无
|
|||||||
- [✓] `npm.cmd run build` 通过。
|
- [✓] `npm.cmd run build` 通过。
|
||||||
- [✓] 浏览器复核首次打开和再次打开弹窗时随机文件名发生变化。
|
- [✓] 浏览器复核首次打开和再次打开弹窗时随机文件名发生变化。
|
||||||
- [✓] 浏览器复核服务器配置填写 `deploy` 和 `192.0.2.50` 后,路径和 SSH 目标同步更新。
|
- [✓] 浏览器复核服务器配置填写 `deploy` 和 `192.0.2.50` 后,路径和 SSH 目标同步更新。
|
||||||
- [✓] 浏览器复核 Windows 与 Linux/macOS 命令均包含当前随机路径和公钥 `.pub` 路径。
|
- [✓] 浏览器复核 Windows 与 Linux/macOS 命令均包含当前随机路径和最终公钥路径;生成命令包含临时 `.pub` 文件移动步骤。
|
||||||
- [✓] 桌面端 1440×901 视口下弹窗宽度为 1080px,页面背景滚动已锁定,弹窗内部无垂直溢出。
|
- [✓] 桌面端 1440×901 视口下弹窗宽度为 1080px,页面背景滚动已锁定,弹窗内部无垂直溢出。
|
||||||
- [!] 真实 SSH 主机、公钥安装、私钥登录和证书部署仍需用户提供并授权实机环境后验收。
|
- [!] 真实 SSH 主机、公钥安装、私钥登录和证书部署仍需用户提供并授权实机环境后验收。
|
||||||
|
|
||||||
@@ -2940,4 +2940,4 @@ Linux Ubuntu 22.04 上的 `Scert-admin` 手动启停、无开机自启动、无
|
|||||||
### 71.2 验证状态
|
### 71.2 验证状态
|
||||||
|
|
||||||
- [✓] 登录相关前端文件已完成修改,等待本轮构建复审。
|
- [✓] 登录相关前端文件已完成修改,等待本轮构建复审。
|
||||||
- [!] 后端仍根据服务端返回结果识别超级管理员、管理员和普通用户,未因页面文案调整而改变权限模型。
|
- [!] 后端仍根据服务端返回结果识别超级管理员、管理员和普通用户,未因页面文案调整而改变权限模型。
|
||||||
@@ -68,16 +68,17 @@ export function useDashboard() {
|
|||||||
`${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}+scert-${sshKeyRandomSuffix.value}`,
|
`${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}+scert-${sshKeyRandomSuffix.value}`,
|
||||||
);
|
);
|
||||||
const sshKeyPath = computed(() => `/ssl/ssh/${sshKeyFileName.value}`);
|
const sshKeyPath = computed(() => `/ssl/ssh/${sshKeyFileName.value}`);
|
||||||
const sshKeyPublicPath = computed(() => `${sshKeyPath.value}.pub`);
|
const sshKeyPrivatePath = computed(() => `${sshKeyPath.value}.key`);
|
||||||
|
const sshKeyPublicPath = computed(() => sshKeyPath.value);
|
||||||
const sshKeyRemoteTarget = computed(
|
const sshKeyRemoteTarget = computed(
|
||||||
() =>
|
() =>
|
||||||
`${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}@${sanitizeSSHHost(sshKeyCommandHost.value)}`,
|
`${sanitizeSSHKeySegment(sshKeyCommandUsername.value, "用户名")}@${sanitizeSSHHost(sshKeyCommandHost.value)}`,
|
||||||
);
|
);
|
||||||
const sshKeyCommands = computed(() => ({
|
const sshKeyCommands = computed(() => ({
|
||||||
windows:
|
windows:
|
||||||
`New-Item -ItemType Directory -Force -Path "/ssl/ssh" | Out-Null; ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPath.value}"`,
|
`New-Item -ItemType Directory -Force -Path "/ssl/ssh" | Out-Null; ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPrivatePath.value}"; Move-Item -Force "${sshKeyPrivatePath.value}.pub" "${sshKeyPublicPath.value}"`,
|
||||||
linux:
|
linux:
|
||||||
`sudo install -d -m 700 -o "$(id -un)" -g "$(id -gn)" /ssl/ssh && ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPath.value}"`,
|
`sudo install -d -m 700 -o "$(id -un)" -g "$(id -gn)" /ssl/ssh && ssh-keygen -t ed25519 -C "scert-deploy" -f "${sshKeyPrivatePath.value}" && mv -f "${sshKeyPrivatePath.value}.pub" "${sshKeyPublicPath.value}" && chmod 644 "${sshKeyPublicPath.value}"`,
|
||||||
}));
|
}));
|
||||||
const sshPublicKeyCommands = computed(() => ({
|
const sshPublicKeyCommands = computed(() => ({
|
||||||
windows:
|
windows:
|
||||||
@@ -815,6 +816,7 @@ export function useDashboard() {
|
|||||||
sshKeyCommandHost,
|
sshKeyCommandHost,
|
||||||
sshKeyFileName,
|
sshKeyFileName,
|
||||||
sshKeyPath,
|
sshKeyPath,
|
||||||
|
sshKeyPrivatePath,
|
||||||
sshKeyPublicPath,
|
sshKeyPublicPath,
|
||||||
showSettings,
|
showSettings,
|
||||||
settingsSaving,
|
settingsSaving,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
|
import UserManagement from "../UserManagement/UserManagement.vue";
|
||||||
import { useDashboard } from "./Dashboard.js";
|
import { useDashboard } from "./Dashboard.js";
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -43,6 +44,7 @@ const {
|
|||||||
sshKeyCommandHost,
|
sshKeyCommandHost,
|
||||||
sshKeyFileName,
|
sshKeyFileName,
|
||||||
sshKeyPath,
|
sshKeyPath,
|
||||||
|
sshKeyPrivatePath,
|
||||||
sshKeyPublicPath,
|
sshKeyPublicPath,
|
||||||
showSettings,
|
showSettings,
|
||||||
settingsSaving,
|
settingsSaving,
|
||||||
@@ -162,6 +164,8 @@ const {
|
|||||||
</article>
|
</article>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<UserManagement />
|
||||||
|
|
||||||
<section class="panel operations-panel">
|
<section class="panel operations-panel">
|
||||||
<div class="panel-heading">
|
<div class="panel-heading">
|
||||||
<div>
|
<div>
|
||||||
@@ -877,7 +881,7 @@ const {
|
|||||||
<div class="ssh-key-path-summary">
|
<div class="ssh-key-path-summary">
|
||||||
<div>
|
<div>
|
||||||
<span>本地私钥位置</span>
|
<span>本地私钥位置</span>
|
||||||
<code>{{ sshKeyPath }}</code>
|
<code>{{ sshKeyPrivatePath }}</code>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span>本地公钥位置</span>
|
<span>本地公钥位置</span>
|
||||||
@@ -924,13 +928,12 @@ const {
|
|||||||
</div>
|
</div>
|
||||||
<code>{{ sshPublicKeyCommands[sshKeyPlatform] }}</code>
|
<code>{{ sshPublicKeyCommands[sshKeyPlatform] }}</code>
|
||||||
<small>
|
<small>
|
||||||
本地公钥文件是上面显示的随机路径;安装后会追加到远程用户的
|
本地公钥文件就是上面显示的随机路径;安装后会追加到远程用户的
|
||||||
<code>~/.ssh/authorized_keys</code>。每台主机、每次新建配置都会生成新的文件名。
|
<code>~/.ssh/authorized_keys</code>。每台主机、每次新建配置都会生成新的文件名。
|
||||||
</small>
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<p class="ssh-key-guide-note">
|
<p class="ssh-key-guide-note">
|
||||||
懒人方式:如果你能登录服务器控制台,只需执行生成命令,再把生成的
|
懒人方式:如果你能登录服务器控制台,只需执行生成命令,再把随机路径中的公钥内容追加到授权文件,最后在下方选择私钥文件即可。
|
||||||
<code>.pub</code> 公钥内容追加到授权文件,最后在下方选择私钥文件即可。
|
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
<div class="ssh-key-form-fields">
|
<div class="ssh-key-form-fields">
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
.user-management {
|
||||||
|
margin-top: 18px;
|
||||||
|
}
|
||||||
|
.user-management-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 22px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.user-management-heading h2 {
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-size: 26px;
|
||||||
|
}
|
||||||
|
.user-management-description {
|
||||||
|
margin: 0;
|
||||||
|
color: #71809a;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.user-management-actions,
|
||||||
|
.user-row-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 9px;
|
||||||
|
}
|
||||||
|
.user-message {
|
||||||
|
margin: 12px 0;
|
||||||
|
padding: 11px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.error-message {
|
||||||
|
border: 1px solid #f0c4c4;
|
||||||
|
color: #9c3b3b;
|
||||||
|
background: #fff2f2;
|
||||||
|
}
|
||||||
|
.notice-message {
|
||||||
|
border: 1px solid #bfe7d1;
|
||||||
|
color: #24734b;
|
||||||
|
background: #effbf4;
|
||||||
|
}
|
||||||
|
.user-empty {
|
||||||
|
padding: 30px 12px;
|
||||||
|
border: 1px dashed #d5ddea;
|
||||||
|
border-radius: 12px;
|
||||||
|
color: #7a879d;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.user-table-wrap {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.user-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
color: #394963;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.user-table th,
|
||||||
|
.user-table td {
|
||||||
|
padding: 13px 10px;
|
||||||
|
border-bottom: 1px solid #edf0f5;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: middle;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.user-table th {
|
||||||
|
color: #7a879d;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.user-table td:first-child {
|
||||||
|
color: #263752;
|
||||||
|
}
|
||||||
|
.user-badge,
|
||||||
|
.user-status {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 4px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.user-badge {
|
||||||
|
color: #315aaa;
|
||||||
|
background: #edf3ff;
|
||||||
|
}
|
||||||
|
.user-status.active {
|
||||||
|
color: #24734b;
|
||||||
|
background: #effbf4;
|
||||||
|
}
|
||||||
|
.user-status.disabled {
|
||||||
|
color: #91672e;
|
||||||
|
background: #fff7e8;
|
||||||
|
}
|
||||||
|
.user-modal {
|
||||||
|
width: min(100%, 620px);
|
||||||
|
}
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.user-management-heading {
|
||||||
|
align-items: stretch;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.user-management-actions {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
.user-table th,
|
||||||
|
.user-table td {
|
||||||
|
padding: 11px 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
|
||||||
|
const roleLabels = {
|
||||||
|
super_admin: "超级管理员",
|
||||||
|
admin: "管理员",
|
||||||
|
user: "普通用户",
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusLabels = {
|
||||||
|
active: "正常",
|
||||||
|
disabled: "已禁用",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useUserManagement() {
|
||||||
|
const visible = ref(false);
|
||||||
|
const users = ref([]);
|
||||||
|
const loading = ref(false);
|
||||||
|
const saving = ref(false);
|
||||||
|
const error = ref("");
|
||||||
|
const notice = ref("");
|
||||||
|
const showForm = ref(false);
|
||||||
|
const editingId = ref("");
|
||||||
|
const formError = ref("");
|
||||||
|
const form = ref(createEmptyForm());
|
||||||
|
const isEditing = computed(() => Boolean(editingId.value));
|
||||||
|
const formTitle = computed(() => (isEditing.value ? "编辑用户" : "添加用户"));
|
||||||
|
|
||||||
|
async function request(path, options = {}) {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
...options,
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
...(options.body ? { "Content-Type": "application/json" } : {}),
|
||||||
|
...(options.headers || {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (response.status === 401) {
|
||||||
|
window.location.assign("/login");
|
||||||
|
throw new Error("登录会话已过期,请重新登录");
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUsers() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = "";
|
||||||
|
try {
|
||||||
|
const response = await request("/api/v1/users");
|
||||||
|
if (response.status === 403 || response.status === 404) {
|
||||||
|
visible.value = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw new Error(result.error || "读取用户列表失败");
|
||||||
|
users.value = result.items || [];
|
||||||
|
visible.value = true;
|
||||||
|
} catch (err) {
|
||||||
|
if (err.message !== "登录会话已过期,请重新登录") {
|
||||||
|
error.value = err.message || "读取用户列表失败";
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEmptyForm() {
|
||||||
|
return {
|
||||||
|
username: "",
|
||||||
|
email: "",
|
||||||
|
password: "",
|
||||||
|
role: "user",
|
||||||
|
status: "active",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
editingId.value = "";
|
||||||
|
form.value = createEmptyForm();
|
||||||
|
formError.value = "";
|
||||||
|
showForm.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(item) {
|
||||||
|
editingId.value = item.id;
|
||||||
|
form.value = {
|
||||||
|
username: item.username || "",
|
||||||
|
email: item.email || "",
|
||||||
|
password: "",
|
||||||
|
role: item.role || "user",
|
||||||
|
status: item.status || "active",
|
||||||
|
};
|
||||||
|
formError.value = "";
|
||||||
|
showForm.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeForm() {
|
||||||
|
if (!saving.value) showForm.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveUser() {
|
||||||
|
formError.value = "";
|
||||||
|
const payload = { ...form.value };
|
||||||
|
if (!payload.password) delete payload.password;
|
||||||
|
if (!payload.username.trim()) {
|
||||||
|
formError.value = "请输入用户名";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isEditing.value && !payload.password) {
|
||||||
|
formError.value = "请输入密码";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const path = isEditing.value
|
||||||
|
? `/api/v1/users/${editingId.value}`
|
||||||
|
: "/api/v1/users";
|
||||||
|
const response = await request(path, {
|
||||||
|
method: isEditing.value ? "PUT" : "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
const result = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw new Error(result.error || "保存用户失败");
|
||||||
|
showForm.value = false;
|
||||||
|
notice.value = isEditing.value ? "用户信息已更新" : "用户已创建";
|
||||||
|
await loadUsers();
|
||||||
|
} catch (err) {
|
||||||
|
formError.value = err.message || "保存用户失败";
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleStatus(item) {
|
||||||
|
const nextStatus = item.status === "active" ? "disabled" : "active";
|
||||||
|
if (item.role === "super_admin" && nextStatus === "disabled") {
|
||||||
|
notice.value = "最后一个超级管理员不能被禁用";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await request(`/api/v1/users/${item.id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify({
|
||||||
|
username: item.username,
|
||||||
|
email: item.email || "",
|
||||||
|
role: item.role,
|
||||||
|
status: nextStatus,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const result = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw new Error(result.error || "更新用户状态失败");
|
||||||
|
notice.value = nextStatus === "active" ? "用户已启用" : "用户已禁用";
|
||||||
|
await loadUsers();
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err.message || "更新用户状态失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteUser(item) {
|
||||||
|
if (!window.confirm(`确定删除用户“${item.username}”吗?`)) return;
|
||||||
|
try {
|
||||||
|
const response = await request(`/api/v1/users/${item.id}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
const result = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw new Error(result.error || "删除用户失败");
|
||||||
|
notice.value = "用户已删除";
|
||||||
|
await loadUsers();
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err.message || "删除用户失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadUsers);
|
||||||
|
|
||||||
|
return {
|
||||||
|
visible,
|
||||||
|
users,
|
||||||
|
loading,
|
||||||
|
saving,
|
||||||
|
error,
|
||||||
|
notice,
|
||||||
|
showForm,
|
||||||
|
form,
|
||||||
|
formError,
|
||||||
|
formTitle,
|
||||||
|
isEditing,
|
||||||
|
roleLabels,
|
||||||
|
statusLabels,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
closeForm,
|
||||||
|
saveUser,
|
||||||
|
toggleStatus,
|
||||||
|
deleteUser,
|
||||||
|
loadUsers,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
<script setup>
|
||||||
|
import { useUserManagement } from "./UserManagement.js";
|
||||||
|
|
||||||
|
const {
|
||||||
|
visible,
|
||||||
|
users,
|
||||||
|
loading,
|
||||||
|
saving,
|
||||||
|
error,
|
||||||
|
notice,
|
||||||
|
showForm,
|
||||||
|
form,
|
||||||
|
formError,
|
||||||
|
formTitle,
|
||||||
|
isEditing,
|
||||||
|
roleLabels,
|
||||||
|
statusLabels,
|
||||||
|
openCreate,
|
||||||
|
openEdit,
|
||||||
|
closeForm,
|
||||||
|
saveUser,
|
||||||
|
toggleStatus,
|
||||||
|
deleteUser,
|
||||||
|
loadUsers,
|
||||||
|
} = useUserManagement();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section v-if="visible" class="user-management panel">
|
||||||
|
<div class="user-management-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">权限与账号</p>
|
||||||
|
<h2>用户管理</h2>
|
||||||
|
<p class="user-management-description">
|
||||||
|
管理登录账号、角色和使用状态。密码只在服务端保存摘要。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="user-management-actions">
|
||||||
|
<button class="secondary-button" type="button" :disabled="loading" @click="loadUsers">
|
||||||
|
{{ loading ? "读取中……" : "刷新列表" }}
|
||||||
|
</button>
|
||||||
|
<button class="primary-button" type="button" @click="openCreate">添加用户</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="error" class="user-message error-message">{{ error }}</p>
|
||||||
|
<p v-if="notice" class="user-message notice-message">{{ notice }}</p>
|
||||||
|
|
||||||
|
<div v-if="loading && users.length === 0" class="user-empty">正在读取用户列表……</div>
|
||||||
|
<div v-else-if="users.length === 0" class="user-empty">暂无数据库用户,配置中的超级管理员仍可登录。</div>
|
||||||
|
<div v-else class="user-table-wrap">
|
||||||
|
<table class="user-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>账号</th>
|
||||||
|
<th>邮箱</th>
|
||||||
|
<th>角色</th>
|
||||||
|
<th>状态</th>
|
||||||
|
<th>创建时间</th>
|
||||||
|
<th>操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in users" :key="item.id">
|
||||||
|
<td><strong>{{ item.username }}</strong></td>
|
||||||
|
<td>{{ item.email || "未绑定" }}</td>
|
||||||
|
<td><span class="user-badge">{{ roleLabels[item.role] || item.role }}</span></td>
|
||||||
|
<td><span class="user-status" :class="item.status">{{ statusLabels[item.status] || item.status }}</span></td>
|
||||||
|
<td>{{ new Date(item.created_at).toLocaleString("zh-CN") }}</td>
|
||||||
|
<td>
|
||||||
|
<div class="user-row-actions">
|
||||||
|
<button class="text-button" type="button" @click="openEdit(item)">编辑</button>
|
||||||
|
<button class="text-button" type="button" @click="toggleStatus(item)">
|
||||||
|
{{ item.status === "active" ? "禁用" : "启用" }}
|
||||||
|
</button>
|
||||||
|
<button v-if="item.role !== 'super_admin'" class="text-button danger-text" type="button" @click="deleteUser(item)">删除</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="showForm" class="modal-backdrop" @click.self="closeForm">
|
||||||
|
<section class="modal-card user-modal" role="dialog" aria-modal="true" :aria-label="formTitle">
|
||||||
|
<div class="modal-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">账号配置</p>
|
||||||
|
<h2>{{ formTitle }}</h2>
|
||||||
|
</div>
|
||||||
|
<button class="close-button" type="button" aria-label="关闭" @click="closeForm">×</button>
|
||||||
|
</div>
|
||||||
|
<form @submit.prevent="saveUser">
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="field">
|
||||||
|
<span>用户名</span>
|
||||||
|
<input v-model="form.username" type="text" autocomplete="off" placeholder="3 到 64 个字符" />
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>绑定邮箱 <small>可选</small></span>
|
||||||
|
<input v-model="form.email" type="email" autocomplete="off" placeholder="用于邮箱登录" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label class="field">
|
||||||
|
<span>密码 <small>{{ isEditing ? "留空表示不修改,8 到 12 个字符" : "8 到 12 个字符" }}</small></span>
|
||||||
|
<input v-model="form.password" type="password" autocomplete="new-password" placeholder="请输入密码" />
|
||||||
|
</label>
|
||||||
|
<div class="form-grid">
|
||||||
|
<label class="field">
|
||||||
|
<span>角色</span>
|
||||||
|
<select v-model="form.role">
|
||||||
|
<option value="user">普通用户</option>
|
||||||
|
<option value="admin">管理员</option>
|
||||||
|
<option value="super_admin">超级管理员</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>状态</span>
|
||||||
|
<select v-model="form.status">
|
||||||
|
<option value="active">正常</option>
|
||||||
|
<option value="disabled">已禁用</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p v-if="formError" class="form-error">{{ formError }}</p>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="secondary-button" type="button" :disabled="saving" @click="closeForm">取消</button>
|
||||||
|
<button class="primary-button" type="submit" :disabled="saving">{{ saving ? "保存中……" : "保存用户" }}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
@import "./UserManagement.css";
|
||||||
|
</style>
|
||||||
Reference in new issue
Block a user