feat: 新增访客/管理员两级鉴权,访客仅见容器数量与列表
后端采用单管理员密码 + HMAC 签名会话 Cookie(HttpOnly/SameSite,HTTPS 自动 Secure,登录失败节流);/api/system/stats 需登录,/api/docker/stats 对访客脱敏(隐藏占用/端口/版本/ID)。前端增加全局登录态、登录弹窗,以及访客与管理员两套视图。compose 注入 ADMIN_PASSWORD / SESSION_SECRET,并补充 .env.example 与 README。
This commit is contained in:
1 parent
eaecdaf9f5
commit
c47391a5af
13 files changed
+740
-94
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
# JuiceWorkStation 部署环境变量示例
|
||||||
|
#
|
||||||
|
# 用法:复制为 .env(与 docker-compose.yml 同目录),按需填写。
|
||||||
|
# docker compose 会自动读取同目录下的 .env 文件。
|
||||||
|
|
||||||
|
# 管理员登录密码。不设置则禁止登录,访客只能看到容器数量与列表。
|
||||||
|
ADMIN_PASSWORD=
|
||||||
|
|
||||||
|
# 会话 Cookie 的签名密钥。不设置会随机生成,导致每次重启都需要重新登录。
|
||||||
|
# 建议填写一段足够长的随机字符串,例如:openssl rand -hex 32
|
||||||
|
SESSION_SECRET=
|
||||||
|
|
||||||
|
# 宿主机 docker 组 GID。一般不用手填:Jenkinsfile 会自动读取 /var/run/docker.sock 的组 GID。
|
||||||
|
# 手动部署时可用:stat -c '%g' /var/run/docker.sock
|
||||||
|
DOCKER_GID=999
|
||||||
@@ -1 +1,67 @@
|
|||||||
# JuiceWorkStation
|
# JuiceWorkStation
|
||||||
|
|
||||||
|
个人服务器 / 工作站控制面板。Go 后端 + React 前端,通过 Docker Compose + Jenkins 部署。
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/ Go 后端(系统状态 + Docker 监控 + 鉴权)
|
||||||
|
dashboard/ React + Vite 前端
|
||||||
|
docker-compose.yml
|
||||||
|
Jenkinsfile
|
||||||
|
```
|
||||||
|
|
||||||
|
## 访问权限模型
|
||||||
|
|
||||||
|
采用「公开只读 + 管理员登录」两级模型,未登录访客与管理员看到的内容不同:
|
||||||
|
|
||||||
|
| 内容 | 访客 | 管理员 |
|
||||||
|
| --- | :-: | :-: |
|
||||||
|
| 容器数量统计(总数 / 运行中 / 停止) | ✅ | ✅ |
|
||||||
|
| 容器列表(名称 / 镜像 / 状态) | ✅ | ✅ |
|
||||||
|
| 容器资源占用(CPU / 内存 / 网络 / 磁盘) | ❌ | ✅ |
|
||||||
|
| 端口分配、容器 ID | ❌ | ✅ |
|
||||||
|
| Docker 版本 | ❌ | ✅ |
|
||||||
|
| 系统状态(CPU / 内存 / 开机时间) | ❌ | ✅ |
|
||||||
|
|
||||||
|
脱敏在后端完成:访客拿到的 JSON 里敏感字段已被抹掉,而不是靠前端隐藏。
|
||||||
|
|
||||||
|
## 后端接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/api/system/stats` | 系统状态(仅管理员,未登录返回 401) |
|
||||||
|
| GET | `/api/docker/stats` | Docker 容器监控(访客自动脱敏) |
|
||||||
|
| POST | `/api/auth/login` | 管理员登录,成功后下发 HttpOnly 会话 Cookie |
|
||||||
|
| POST | `/api/auth/logout` | 退出登录 |
|
||||||
|
| GET | `/api/auth/status` | 查询登录状态 |
|
||||||
|
| GET | `/healthz` | 健康检查 |
|
||||||
|
|
||||||
|
## 环境变量
|
||||||
|
|
||||||
|
见 [`.env.example`](.env.example),复制为 `.env` 后填写:
|
||||||
|
|
||||||
|
- `ADMIN_PASSWORD`:管理员密码。**不设置则禁止登录**,访客仍可看公开数据。
|
||||||
|
- `SESSION_SECRET`:会话 Cookie 签名密钥。不设置会随机生成,重启后需重新登录。
|
||||||
|
- `DOCKER_GID`:宿主机 docker 组 GID,一般由 Jenkinsfile 自动注入。
|
||||||
|
|
||||||
|
## 本地开发
|
||||||
|
|
||||||
|
后端:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
ADMIN_PASSWORD=dev go run . # Linux/macOS
|
||||||
|
```
|
||||||
|
|
||||||
|
前端(Vite 已把 `/api` 代理到 `localhost:9018`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd dashboard
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## 部署
|
||||||
|
|
||||||
|
Jenkins 流水线会构建镜像并 `docker compose up -d`。生产环境通过 nginx 同源反代 `/api/`,会话 Cookie 无需额外跨域配置。
|
||||||
+232
@@ -0,0 +1,232 @@
|
|||||||
|
// 鉴权
|
||||||
|
//
|
||||||
|
// 采用「单管理员密码 + HMAC 签名会话 Cookie」的轻量方案:
|
||||||
|
// - ADMIN_PASSWORD 通过环境变量配置;未设置时禁止登录(访客仍可看公开数据)。
|
||||||
|
// - 登录成功签发无状态 Cookie,值为 <过期时间戳>.<HMAC-SHA256 签名>。
|
||||||
|
// - SESSION_SECRET 用作签名密钥;未设置时随机生成(重启后已有登录失效)。
|
||||||
|
//
|
||||||
|
// 权限模型:
|
||||||
|
// - 访客(未登录):只能看到容器数量与容器列表(名称/镜像/状态)。
|
||||||
|
// - 管理员(已登录):可看到系统状态、容器资源占用、端口等全部信息。
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
sessionCookieName = "jws_session"
|
||||||
|
sessionTTL = 7 * 24 * time.Hour
|
||||||
|
|
||||||
|
// 登录失败超过 maxLoginFailures 次后锁定 loginLockDuration。
|
||||||
|
maxLoginFailures = 5
|
||||||
|
loginLockDuration = time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
var sessionSecret = loadSessionSecret()
|
||||||
|
|
||||||
|
func loadSessionSecret() []byte {
|
||||||
|
if s := strings.TrimSpace(os.Getenv("SESSION_SECRET")); s != "" {
|
||||||
|
sum := sha256.Sum256([]byte(s))
|
||||||
|
return sum[:]
|
||||||
|
}
|
||||||
|
// 没有配置就随机生成:重启后现有登录失效,但至少不是可预测的默认密钥。
|
||||||
|
b := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
log.Fatalf("生成会话密钥失败: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf("警告:未设置 SESSION_SECRET,已生成临时密钥,重启后所有登录会失效")
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminPassword() string {
|
||||||
|
return os.Getenv("ADMIN_PASSWORD")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 会话令牌
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func makeSessionToken(exp time.Time) string {
|
||||||
|
payload := strconv.FormatInt(exp.Unix(), 10)
|
||||||
|
mac := hmac.New(sha256.New, sessionSecret)
|
||||||
|
mac.Write([]byte(payload))
|
||||||
|
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||||
|
return payload + "." + sig
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifySessionToken(token string) bool {
|
||||||
|
parts := strings.SplitN(token, ".", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
expUnix, err := strconv.ParseInt(parts[0], 10, 64)
|
||||||
|
if err != nil || time.Now().Unix() > expUnix {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, sessionSecret)
|
||||||
|
mac.Write([]byte(parts[0]))
|
||||||
|
got, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return hmac.Equal(mac.Sum(nil), got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// isAuthenticated 判断当前请求是否携带有效的管理员会话。
|
||||||
|
func isAuthenticated(r *http.Request) bool {
|
||||||
|
c, err := r.Cookie(sessionCookieName)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return verifySessionToken(c.Value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireAuth 用于只允许管理员访问的接口。
|
||||||
|
func requireAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !isAuthenticated(r) {
|
||||||
|
writeJSON(w, http.StatusUnauthorized, map[string]any{
|
||||||
|
"error": "unauthorized",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 登录失败节流(简单的内存计数,防暴力破解)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
var (
|
||||||
|
loginMu sync.Mutex
|
||||||
|
loginFailures int
|
||||||
|
loginLockedUntil time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
func loginLocked() bool {
|
||||||
|
loginMu.Lock()
|
||||||
|
defer loginMu.Unlock()
|
||||||
|
return time.Now().Before(loginLockedUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func recordLoginFailure() {
|
||||||
|
loginMu.Lock()
|
||||||
|
defer loginMu.Unlock()
|
||||||
|
loginFailures++
|
||||||
|
if loginFailures >= maxLoginFailures {
|
||||||
|
loginLockedUntil = time.Now().Add(loginLockDuration)
|
||||||
|
loginFailures = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetLoginFailures() {
|
||||||
|
loginMu.Lock()
|
||||||
|
loginFailures = 0
|
||||||
|
loginLockedUntil = time.Time{}
|
||||||
|
loginMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// HTTP 处理
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
func handleAuthStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"authenticated": isAuthenticated(r),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if adminPassword() == "" {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||||
|
"error": "服务端未配置 ADMIN_PASSWORD",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if loginLocked() {
|
||||||
|
writeJSON(w, http.StatusTooManyRequests, map[string]any{
|
||||||
|
"error": "尝试过于频繁,请稍后再试",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
|
||||||
|
writeJSON(w, http.StatusBadRequest, map[string]any{"error": "请求格式错误"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if subtle.ConstantTimeCompare([]byte(body.Password), []byte(adminPassword())) != 1 {
|
||||||
|
recordLoginFailure()
|
||||||
|
// 让暴力破解变慢。
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "密码错误"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resetLoginFailures()
|
||||||
|
exp := time.Now().Add(sessionTTL)
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: sessionCookieName,
|
||||||
|
Value: makeSessionToken(exp),
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
Secure: isTLS(r),
|
||||||
|
Expires: exp,
|
||||||
|
MaxAge: int(sessionTTL.Seconds()),
|
||||||
|
})
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"authenticated": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: sessionCookieName,
|
||||||
|
Value: "",
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
Secure: isTLS(r),
|
||||||
|
MaxAge: -1,
|
||||||
|
})
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"authenticated": false})
|
||||||
|
}
|
||||||
|
|
||||||
|
// isTLS 判断原始请求是否为 HTTPS(生产环境由 nginx 反代,需要看 X-Forwarded-Proto)。
|
||||||
|
func isTLS(r *http.Request) bool {
|
||||||
|
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||||
|
log.Printf("序列化响应失败: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,9 @@ type DockerStats struct {
|
|||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
|
|
||||||
|
// Authenticated 表示当前请求是否来自已登录管理员。访客只会拿到脱敏后的数据。
|
||||||
|
Authenticated bool `json:"authenticated"`
|
||||||
|
|
||||||
ContainersTotal int `json:"containersTotal"`
|
ContainersTotal int `json:"containersTotal"`
|
||||||
ContainersRunning int `json:"containersRunning"`
|
ContainersRunning int `json:"containersRunning"`
|
||||||
ContainersStopped int `json:"containersStopped"`
|
ContainersStopped int `json:"containersStopped"`
|
||||||
@@ -249,13 +252,45 @@ func pruneDockerSamples(live map[string]struct{}) {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
func handleDockerStats(w http.ResponseWriter, r *http.Request) {
|
func handleDockerStats(w http.ResponseWriter, r *http.Request) {
|
||||||
|
authed := isAuthenticated(r)
|
||||||
stats := collectDockerStats(r.Context())
|
stats := collectDockerStats(r.Context())
|
||||||
|
stats.Authenticated = authed
|
||||||
|
if !authed {
|
||||||
|
redactDockerStats(&stats)
|
||||||
|
}
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
if err := json.NewEncoder(w).Encode(stats); err != nil {
|
if err := json.NewEncoder(w).Encode(stats); err != nil {
|
||||||
log.Printf("序列化 Docker 响应失败: %v", err)
|
log.Printf("序列化 Docker 响应失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// redactDockerStats 把访客不该看到的信息抹掉,只保留容器数量与列表(名称/镜像/状态)。
|
||||||
|
// 注意:这里不改变 available 与各类计数,访客仍能看出"服务在不在跑"。
|
||||||
|
func redactDockerStats(s *DockerStats) {
|
||||||
|
// 版本号与底层错误信息(可能含 socket 路径)不对访客暴露。
|
||||||
|
s.Version = ""
|
||||||
|
if s.Available {
|
||||||
|
s.Message = ""
|
||||||
|
} else {
|
||||||
|
s.Message = "监控服务暂不可用"
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range s.Containers {
|
||||||
|
c := &s.Containers[i]
|
||||||
|
c.ID = ""
|
||||||
|
c.Created = 0
|
||||||
|
c.CPUPercent = 0
|
||||||
|
c.MemUsage = 0
|
||||||
|
c.MemLimit = 0
|
||||||
|
c.MemPercent = 0
|
||||||
|
c.NetRx = 0
|
||||||
|
c.NetTx = 0
|
||||||
|
c.BlockRead = 0
|
||||||
|
c.BlockWrite = 0
|
||||||
|
c.Ports = []string{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func collectDockerStats(parent context.Context) DockerStats {
|
func collectDockerStats(parent context.Context) DockerStats {
|
||||||
out := DockerStats{Containers: []ContainerStats{}}
|
out := DockerStats{Containers: []ContainerStats{}}
|
||||||
|
|
||||||
|
|||||||
+13
-4
@@ -2,9 +2,12 @@
|
|||||||
//
|
//
|
||||||
// 这是原 Spring Boot 版本的 Go 重写,对外接口与 JSON 结构保持一致:
|
// 这是原 Spring Boot 版本的 Go 重写,对外接口与 JSON 结构保持一致:
|
||||||
//
|
//
|
||||||
// GET /api/system/stats 返回系统状态 JSON
|
// GET /api/system/stats 返回系统状态 JSON(仅管理员)
|
||||||
// GET /api/docker/stats 返回 Docker 容器监控 JSON(见 docker.go)
|
// GET /api/docker/stats 返回 Docker 容器监控 JSON(见 docker.go,访客只读脱敏)
|
||||||
// GET /healthz 健康检查(给容器编排/探活用)
|
// POST /api/auth/login 管理员登录
|
||||||
|
// POST /api/auth/logout 退出登录
|
||||||
|
// GET /api/auth/status 查询当前登录状态
|
||||||
|
// GET /healthz 健康检查(给容器编排/探活用)
|
||||||
//
|
//
|
||||||
// 相比 Java 版,运行时只占十几 MB 内存,且不依赖 JVM。
|
// 相比 Java 版,运行时只占十几 MB 内存,且不依赖 JVM。
|
||||||
package main
|
package main
|
||||||
@@ -349,8 +352,11 @@ func main() {
|
|||||||
startCPUSampler()
|
startCPUSampler()
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/api/system/stats", handleSystemStats)
|
mux.HandleFunc("/api/system/stats", requireAuth(handleSystemStats))
|
||||||
mux.HandleFunc("/api/docker/stats", handleDockerStats)
|
mux.HandleFunc("/api/docker/stats", handleDockerStats)
|
||||||
|
mux.HandleFunc("/api/auth/login", handleLogin)
|
||||||
|
mux.HandleFunc("/api/auth/logout", handleLogout)
|
||||||
|
mux.HandleFunc("/api/auth/status", handleAuthStatus)
|
||||||
mux.HandleFunc("/healthz", handleHealthz)
|
mux.HandleFunc("/healthz", handleHealthz)
|
||||||
|
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
@@ -360,6 +366,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("workstation-server (Go %s) 启动,监听 %s", runtime.Version(), listenAddr)
|
log.Printf("workstation-server (Go %s) 启动,监听 %s", runtime.Version(), listenAddr)
|
||||||
|
if adminPassword() == "" {
|
||||||
|
log.Printf("警告:未设置 ADMIN_PASSWORD,管理员登录已禁用,仅对外公开只读监控")
|
||||||
|
}
|
||||||
if err := server.ListenAndServe(); err != nil {
|
if err := server.ListenAndServe(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-7
@@ -1,15 +1,27 @@
|
|||||||
import { Outlet } from 'react-router-dom'
|
import { Outlet } from 'react-router-dom'
|
||||||
import NavBar from './components/NavBar'
|
import NavBar from './components/NavBar'
|
||||||
import Footer from './components/Footer'
|
import Footer from './components/Footer'
|
||||||
|
import LoginModal from './components/LoginModal'
|
||||||
|
import { AuthProvider, useAuth } from './lib/auth'
|
||||||
|
|
||||||
|
// 独立的登录弹窗容器,放在 Provider 内部以便读取全局开关。
|
||||||
|
function GlobalLoginModal() {
|
||||||
|
const { loginOpen, closeLogin } = useAuth()
|
||||||
|
// key 让弹窗在每次打开时重新挂载,天然清空上次的输入与错误。
|
||||||
|
return <LoginModal key={String(loginOpen)} open={loginOpen} onClose={closeLogin} />
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 text-slate-900">
|
<AuthProvider>
|
||||||
<NavBar />
|
<div className="min-h-screen bg-slate-50 text-slate-900">
|
||||||
<main>
|
<NavBar />
|
||||||
<Outlet />
|
<main>
|
||||||
</main>
|
<Outlet />
|
||||||
<Footer />
|
</main>
|
||||||
</div>
|
<Footer />
|
||||||
|
</div>
|
||||||
|
<GlobalLoginModal />
|
||||||
|
</AuthProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
|
||||||
|
export default function LoginModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||||
|
const { login } = useAuth()
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [submitting, setSubmitting] = useState(false)
|
||||||
|
|
||||||
|
if (!open) return null
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (submitting) return
|
||||||
|
setSubmitting(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const ok = await login(password)
|
||||||
|
if (ok) {
|
||||||
|
onClose()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setError('密码错误')
|
||||||
|
} catch {
|
||||||
|
setError('网络错误,请稍后再试')
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/50 px-6"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-sm rounded-xl border border-slate-200 bg-white p-6 shadow-xl"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<h2 className="text-lg font-semibold text-slate-900">管理员登录</h2>
|
||||||
|
<p className="mt-1 text-sm text-slate-500">登录后可查看资源占用与端口等完整信息</p>
|
||||||
|
|
||||||
|
<form className="mt-5" onSubmit={handleSubmit}>
|
||||||
|
<label htmlFor="admin-password" className="block text-sm font-medium text-slate-700">
|
||||||
|
密码
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="admin-password"
|
||||||
|
type="password"
|
||||||
|
autoFocus
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="mt-2 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none transition-colors focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100"
|
||||||
|
placeholder="请输入管理员密码"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && <p className="mt-2 text-sm text-red-600">{error}</p>}
|
||||||
|
|
||||||
|
<div className="mt-5 flex justify-end gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-lg px-4 py-2 text-sm text-slate-600 transition-colors hover:bg-slate-100"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting || !password}
|
||||||
|
className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{submitting ? '登录中…' : '登录'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { NavLink } from 'react-router-dom'
|
import { NavLink } from 'react-router-dom'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
|
||||||
const links = [
|
const links = [
|
||||||
{ to: '/', label: '首页' },
|
{ to: '/', label: '首页' },
|
||||||
@@ -17,6 +18,26 @@ function linkClassName({ isActive }: { isActive: boolean }) {
|
|||||||
|
|
||||||
export default function NavBar() {
|
export default function NavBar() {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
|
const { authenticated, loading, logout, openLogin } = useAuth()
|
||||||
|
|
||||||
|
const authAction = authenticated ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void logout()}
|
||||||
|
className="rounded-md px-3 py-2 text-sm text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900"
|
||||||
|
>
|
||||||
|
退出
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={openLogin}
|
||||||
|
disabled={loading}
|
||||||
|
className="rounded-md bg-indigo-600 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
登录
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-50 border-b border-slate-200 bg-white/80 backdrop-blur">
|
<header className="sticky top-0 z-50 border-b border-slate-200 bg-white/80 backdrop-blur">
|
||||||
@@ -28,42 +49,51 @@ export default function NavBar() {
|
|||||||
JuiceWorkStation
|
JuiceWorkStation
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|
||||||
<ul className="hidden items-center gap-1 md:flex">
|
<div className="flex items-center gap-1">
|
||||||
{links.map((link) => (
|
<ul className="hidden items-center gap-1 md:flex">
|
||||||
<li key={link.to}>
|
{links.map((link) => (
|
||||||
<NavLink to={link.to} end={link.to === '/'} className={linkClassName}>
|
<li key={link.to}>
|
||||||
{link.label}
|
<NavLink to={link.to} end={link.to === '/'} className={linkClassName}>
|
||||||
</NavLink>
|
{link.label}
|
||||||
</li>
|
</NavLink>
|
||||||
))}
|
</li>
|
||||||
</ul>
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
<button
|
<span className="mx-1 hidden h-5 w-px bg-slate-200 md:block" />
|
||||||
type="button"
|
|
||||||
className="grid size-10 place-items-center rounded-md text-slate-600 transition-colors hover:bg-slate-100 md:hidden"
|
<div className="hidden md:block">
|
||||||
aria-label={open ? '关闭菜单' : '打开菜单'}
|
{authenticated && <span className="mr-1 text-xs text-slate-400">管理员</span>}
|
||||||
aria-expanded={open}
|
{authAction}
|
||||||
onClick={() => setOpen((v) => !v)}
|
</div>
|
||||||
>
|
|
||||||
<svg
|
<button
|
||||||
className="size-6"
|
type="button"
|
||||||
fill="none"
|
className="grid size-10 place-items-center rounded-md text-slate-600 transition-colors hover:bg-slate-100 md:hidden"
|
||||||
viewBox="0 0 24 24"
|
aria-label={open ? '关闭菜单' : '打开菜单'}
|
||||||
strokeWidth={1.8}
|
aria-expanded={open}
|
||||||
stroke="currentColor"
|
onClick={() => setOpen((v) => !v)}
|
||||||
aria-hidden="true"
|
|
||||||
>
|
>
|
||||||
{open ? (
|
<svg
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
className="size-6"
|
||||||
) : (
|
fill="none"
|
||||||
<path
|
viewBox="0 0 24 24"
|
||||||
strokeLinecap="round"
|
strokeWidth={1.8}
|
||||||
strokeLinejoin="round"
|
stroke="currentColor"
|
||||||
d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5"
|
aria-hidden="true"
|
||||||
/>
|
>
|
||||||
)}
|
{open ? (
|
||||||
</svg>
|
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
|
||||||
</button>
|
) : (
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{open && (
|
{open && (
|
||||||
@@ -81,6 +111,31 @@ export default function NavBar() {
|
|||||||
</NavLink>
|
</NavLink>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
<li className="pt-1">
|
||||||
|
{authenticated ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
void logout()
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className="w-full rounded-md px-3 py-2 text-left text-sm text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900"
|
||||||
|
>
|
||||||
|
退出登录
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
openLogin()
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
className="w-full rounded-md bg-indigo-600 px-3 py-2 text-left text-sm font-medium text-white transition-colors hover:bg-indigo-500"
|
||||||
|
>
|
||||||
|
管理员登录
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -12,5 +12,6 @@ export function resolveApiUrl(path: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function apiFetch(path: string, init?: RequestInit): Promise<Response> {
|
export function apiFetch(path: string, init?: RequestInit): Promise<Response> {
|
||||||
return fetch(resolveApiUrl(path), init)
|
// credentials: 'include' 让浏览器带上会话 Cookie(同源反代下必需)。
|
||||||
|
return fetch(resolveApiUrl(path), { credentials: 'include', ...init })
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
|
||||||
|
import { apiFetch } from './api'
|
||||||
|
|
||||||
|
interface AuthContextValue {
|
||||||
|
authenticated: boolean
|
||||||
|
/** 首次向服务端确认登录状态期间为 true */
|
||||||
|
loading: boolean
|
||||||
|
login: (password: string) => Promise<boolean>
|
||||||
|
logout: () => Promise<void>
|
||||||
|
/** 全局登录弹窗开关,避免各页面各自维护一份 */
|
||||||
|
loginOpen: boolean
|
||||||
|
openLogin: () => void
|
||||||
|
closeLogin: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const [authenticated, setAuthenticated] = useState(false)
|
||||||
|
const [loading, setLoading] = useState(true)
|
||||||
|
const [loginOpen, setLoginOpen] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
|
apiFetch('/api/auth/status')
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data: { authenticated?: boolean }) => {
|
||||||
|
if (!cancelled) setAuthenticated(!!data.authenticated)
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setAuthenticated(false)
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setLoading(false)
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const login = useCallback(async (password: string) => {
|
||||||
|
const res = await apiFetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ password }),
|
||||||
|
})
|
||||||
|
const data = (await res.json().catch(() => ({}))) as { authenticated?: boolean }
|
||||||
|
const ok = res.ok && !!data.authenticated
|
||||||
|
setAuthenticated(ok)
|
||||||
|
return ok
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const logout = useCallback(async () => {
|
||||||
|
await apiFetch('/api/auth/logout', { method: 'POST' }).catch(() => undefined)
|
||||||
|
setAuthenticated(false)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const openLogin = useCallback(() => setLoginOpen(true), [])
|
||||||
|
const closeLogin = useCallback(() => setLoginOpen(false), [])
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({ authenticated, loading, login, logout, loginOpen, openLogin, closeLogin }),
|
||||||
|
[authenticated, loading, login, logout, loginOpen, openLogin, closeLogin],
|
||||||
|
)
|
||||||
|
|
||||||
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
// useAuth 是 hook 而非组件,和 Provider 放在同一文件更方便使用;
|
||||||
|
// 这里显式豁免 react-refresh 的“只导出组件”规则。
|
||||||
|
// eslint-disable-next-line react-refresh/only-export-components
|
||||||
|
export function useAuth(): AuthContextValue {
|
||||||
|
const ctx = useContext(AuthContext)
|
||||||
|
if (!ctx) throw new Error('useAuth 必须在 AuthProvider 内使用')
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { apiFetch } from '../lib/api'
|
import { apiFetch } from '../lib/api'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ key: 'overview', label: '概览' },
|
{ key: 'overview', label: '概览' },
|
||||||
@@ -32,6 +33,7 @@ interface DockerStats {
|
|||||||
available: boolean
|
available: boolean
|
||||||
message: string
|
message: string
|
||||||
version: string
|
version: string
|
||||||
|
authenticated: boolean
|
||||||
containersTotal: number
|
containersTotal: number
|
||||||
containersRunning: number
|
containersRunning: number
|
||||||
containersStopped: number
|
containersStopped: number
|
||||||
@@ -101,7 +103,7 @@ function SummaryCard({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function ContainerCard({ container }: { container: ContainerStats }) {
|
function ContainerCard({ container, detailed }: { container: ContainerStats; detailed: boolean }) {
|
||||||
const info = stateInfo(container.state)
|
const info = stateInfo(container.state)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -122,48 +124,56 @@ function ContainerCard({ container }: { container: ContainerStats }) {
|
|||||||
<p className="shrink-0 text-xs text-slate-400">{container.status}</p>
|
<p className="shrink-0 text-xs text-slate-400">{container.status}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-4 grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-4">
|
{detailed && (
|
||||||
<Metric label="CPU">
|
<>
|
||||||
<span>{container.cpuPercent.toFixed(1)}%</span>
|
<div className="mt-4 grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-4">
|
||||||
<MiniBar percent={container.cpuPercent} />
|
<Metric label="CPU">
|
||||||
</Metric>
|
<span>{container.cpuPercent.toFixed(1)}%</span>
|
||||||
<Metric label="内存">
|
<MiniBar percent={container.cpuPercent} />
|
||||||
<span>{formatBytes(container.memUsage)}</span>
|
</Metric>
|
||||||
<span className="text-xs font-normal text-slate-400">
|
<Metric label="内存">
|
||||||
{' '}
|
<span>{formatBytes(container.memUsage)}</span>
|
||||||
/ {container.memLimit ? formatBytes(container.memLimit) : '—'}
|
<span className="text-xs font-normal text-slate-400">
|
||||||
</span>
|
{' '}
|
||||||
<MiniBar percent={container.memPercent} />
|
/ {container.memLimit ? formatBytes(container.memLimit) : '—'}
|
||||||
</Metric>
|
|
||||||
<Metric label="网络">
|
|
||||||
<span className="text-emerald-600">↓ {formatBytes(container.netRx)}</span>
|
|
||||||
<br />
|
|
||||||
<span className="text-sky-600">↑ {formatBytes(container.netTx)}</span>
|
|
||||||
</Metric>
|
|
||||||
<Metric label="磁盘读写">
|
|
||||||
<span>R {formatBytes(container.blockRead)}</span>
|
|
||||||
<br />
|
|
||||||
<span>W {formatBytes(container.blockWrite)}</span>
|
|
||||||
</Metric>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-slate-100 pt-3 text-xs text-slate-400">
|
|
||||||
<span>ID {container.id}</span>
|
|
||||||
{container.ports.length > 0 && (
|
|
||||||
<span className="flex flex-wrap gap-1">
|
|
||||||
{container.ports.map((port) => (
|
|
||||||
<span key={port} className="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[11px] text-slate-600">
|
|
||||||
{port}
|
|
||||||
</span>
|
</span>
|
||||||
))}
|
<MiniBar percent={container.memPercent} />
|
||||||
</span>
|
</Metric>
|
||||||
)}
|
<Metric label="网络">
|
||||||
</div>
|
<span className="text-emerald-600">↓ {formatBytes(container.netRx)}</span>
|
||||||
|
<br />
|
||||||
|
<span className="text-sky-600">↑ {formatBytes(container.netTx)}</span>
|
||||||
|
</Metric>
|
||||||
|
<Metric label="磁盘读写">
|
||||||
|
<span>R {formatBytes(container.blockRead)}</span>
|
||||||
|
<br />
|
||||||
|
<span>W {formatBytes(container.blockWrite)}</span>
|
||||||
|
</Metric>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-slate-100 pt-3 text-xs text-slate-400">
|
||||||
|
<span>ID {container.id}</span>
|
||||||
|
{container.ports.length > 0 && (
|
||||||
|
<span className="flex flex-wrap gap-1">
|
||||||
|
{container.ports.map((port) => (
|
||||||
|
<span
|
||||||
|
key={port}
|
||||||
|
className="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[11px] text-slate-600"
|
||||||
|
>
|
||||||
|
{port}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function DockerOverview() {
|
function DockerOverview() {
|
||||||
|
const { authenticated, openLogin } = useAuth()
|
||||||
const [stats, setStats] = useState<DockerStats | null>(null)
|
const [stats, setStats] = useState<DockerStats | null>(null)
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
|
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
|
||||||
@@ -191,7 +201,8 @@ function DockerOverview() {
|
|||||||
cancelled = true
|
cancelled = true
|
||||||
clearInterval(timer)
|
clearInterval(timer)
|
||||||
}
|
}
|
||||||
}, [])
|
// 登录/退出后重新拉取,切换脱敏与完整视图。
|
||||||
|
}, [authenticated])
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
@@ -232,10 +243,29 @@ function DockerOverview() {
|
|||||||
value={`${stats.containersStopped} / ${stats.containersPaused}`}
|
value={`${stats.containersStopped} / ${stats.containersPaused}`}
|
||||||
accent="text-slate-500"
|
accent="text-slate-500"
|
||||||
/>
|
/>
|
||||||
<SummaryCard label="Docker 版本" value={stats.version || '—'} accent="text-indigo-600" />
|
<SummaryCard
|
||||||
|
label="Docker 版本"
|
||||||
|
value={stats.authenticated ? stats.version || '—' : '登录可见'}
|
||||||
|
accent={stats.authenticated ? 'text-indigo-600' : 'text-slate-300'}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!stats.authenticated && (
|
||||||
|
<div className="mt-4 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-5 py-4">
|
||||||
|
<p className="text-sm text-slate-500">
|
||||||
|
当前为访客视图,仅展示容器数量与列表。登录后可查看资源占用、端口等信息。
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={openLogin}
|
||||||
|
className="shrink-0 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-indigo-500"
|
||||||
|
>
|
||||||
|
管理员登录
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{lastUpdated && (
|
{lastUpdated && (
|
||||||
<p className="mt-3 text-right text-xs text-slate-400">
|
<p className="mt-3 text-right text-xs text-slate-400">
|
||||||
最后更新于 {lastUpdated.toLocaleTimeString()} · 每 {REFRESH_INTERVAL / 1000} 秒自动刷新
|
最后更新于 {lastUpdated.toLocaleTimeString()} · 每 {REFRESH_INTERVAL / 1000} 秒自动刷新
|
||||||
@@ -249,7 +279,11 @@ function DockerOverview() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="mt-4 space-y-4">
|
<div className="mt-4 space-y-4">
|
||||||
{stats.containers.map((container) => (
|
{stats.containers.map((container) => (
|
||||||
<ContainerCard key={container.id} container={container} />
|
<ContainerCard
|
||||||
|
key={container.name || container.id}
|
||||||
|
container={container}
|
||||||
|
detailed={stats.authenticated}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { apiFetch } from '../lib/api'
|
import { apiFetch } from '../lib/api'
|
||||||
|
import { useAuth } from '../lib/auth'
|
||||||
|
|
||||||
interface CpuStats {
|
interface CpuStats {
|
||||||
model: string
|
model: string
|
||||||
@@ -80,11 +81,18 @@ const iconProps = {
|
|||||||
} as const
|
} as const
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
|
const { authenticated, loading, openLogin } = useAuth()
|
||||||
const [stats, setStats] = useState<SystemStats | null>(null)
|
const [stats, setStats] = useState<SystemStats | null>(null)
|
||||||
const [error, setError] = useState(false)
|
const [error, setError] = useState(false)
|
||||||
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
|
const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// 系统状态仅管理员可见:未登录时直接跳过请求,渲染层会展示锁定提示。
|
||||||
|
// 这里不同步清空已有 state,避免 effect 内 setState 造成级联渲染。
|
||||||
|
if (!authenticated) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
@@ -107,7 +115,7 @@ export default function Home() {
|
|||||||
cancelled = true
|
cancelled = true
|
||||||
clearInterval(timer)
|
clearInterval(timer)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [authenticated])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -131,14 +139,16 @@ export default function Home() {
|
|||||||
<div>
|
<div>
|
||||||
<h2 className="text-2xl font-semibold text-slate-900">系统状态</h2>
|
<h2 className="text-2xl font-semibold text-slate-900">系统状态</h2>
|
||||||
<p className="mt-1 text-sm text-slate-500">
|
<p className="mt-1 text-sm text-slate-500">
|
||||||
{error
|
{!authenticated
|
||||||
? '无法获取系统信息,请确认后端服务已启动'
|
? '系统状态仅对管理员可见'
|
||||||
: stats
|
: error
|
||||||
? `实时运行状态一览,每 ${REFRESH_INTERVAL / 1000} 秒自动刷新`
|
? '无法获取系统信息,请确认后端服务已启动'
|
||||||
: '正在获取系统信息…'}
|
: stats
|
||||||
|
? `实时运行状态一览,每 ${REFRESH_INTERVAL / 1000} 秒自动刷新`
|
||||||
|
: '正在获取系统信息…'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{stats && lastUpdated && (
|
{authenticated && stats && lastUpdated && (
|
||||||
<p className="text-xs text-slate-400">
|
<p className="text-xs text-slate-400">
|
||||||
最后更新于 {lastUpdated.toLocaleTimeString()}
|
最后更新于 {lastUpdated.toLocaleTimeString()}
|
||||||
</p>
|
</p>
|
||||||
@@ -146,7 +156,23 @@ export default function Home() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-10 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
|
<div className="mt-10 rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
|
||||||
{stats ? (
|
{!authenticated ? (
|
||||||
|
<div className="py-12 text-center">
|
||||||
|
<div className="mx-auto grid size-14 place-items-center rounded-2xl bg-slate-100 text-2xl">
|
||||||
|
🔒
|
||||||
|
</div>
|
||||||
|
<p className="mt-4 text-sm font-medium text-slate-700">需要管理员登录</p>
|
||||||
|
<p className="mt-1 text-sm text-slate-500">登录后可查看 CPU、内存与开机时间等系统状态</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={openLogin}
|
||||||
|
disabled={loading}
|
||||||
|
className="mt-5 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-indigo-500 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
管理员登录
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : stats ? (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-slate-100 pb-4">
|
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-slate-100 pb-4">
|
||||||
<span className="text-sm text-slate-500">
|
<span className="text-sm text-slate-500">
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ services:
|
|||||||
expose:
|
expose:
|
||||||
- "9018"
|
- "9018"
|
||||||
mem_limit: 128m
|
mem_limit: 128m
|
||||||
|
environment:
|
||||||
|
# 管理员登录密码;不设置则禁止登录,仅对外公开只读监控。
|
||||||
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||||
|
# 会话 Cookie 签名密钥;不设置会随机生成,重启后需重新登录。
|
||||||
|
SESSION_SECRET: ${SESSION_SECRET:-}
|
||||||
# 后端镜像以 nonroot 运行,而 docker.sock 属于 root:docker(0660),
|
# 后端镜像以 nonroot 运行,而 docker.sock 属于 root:docker(0660),
|
||||||
# 这里把宿主机的 docker 组 GID 追加为附加组,让其有权限读取 socket。
|
# 这里把宿主机的 docker 组 GID 追加为附加组,让其有权限读取 socket。
|
||||||
# DOCKER_GID 由 Jenkinsfile 在部署时按宿主机实际 GID 注入,默认 999(Debian 常见值)。
|
# DOCKER_GID 由 Jenkinsfile 在部署时按宿主机实际 GID 注入,默认 999(Debian 常见值)。
|
||||||
|
|||||||
Reference in new issue
Block a user