Compare commits
9 Commits
4fc755d558
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 22d8cb9c11 | |||
| 79e2db8492 | |||
| 1042b48102 | |||
| 5ff58ac4d6 | |||
| bd56a73b63 | |||
| a7fc2e49f0 | |||
| 4b7ccb0a30 | |||
| ca11965e8f | |||
| 11191a6e1d |
+6
-2
@@ -1,12 +1,16 @@
|
|||||||
FROM python:3.12-slim
|
FROM python:3.12-slim
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
ARG APT_MIRROR=mirrors.tuna.tsinghua.edu.cn
|
||||||
|
RUN sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" \
|
||||||
|
/etc/apt/sources.list /etc/apt/sources.list.d/*.sources 2>/dev/null || true \
|
||||||
|
&& apt-get update && apt-get install -y --no-install-recommends \
|
||||||
fping iputils-ping && \
|
fping iputils-ping && \
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
ARG PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||||
|
RUN pip install --no-cache-dir --index-url "$PIP_INDEX_URL" -r requirements.txt
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ LEGACY_DEFAULT_SECRET = "change-me-to-a-long-random-string"
|
|||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
# ---------- 运行环境 ----------
|
# ---------- 运行环境 ----------
|
||||||
environment: Literal["development", "test", "production"] = "development"
|
environment: Literal["development", "test", "production"] = "development"
|
||||||
|
auth_enabled: bool = False
|
||||||
|
|
||||||
# ---------- 数据库 ----------
|
# ---------- 数据库 ----------
|
||||||
DATABASE_URL: str = "sqlite+aiosqlite:///./pingwatch.db"
|
DATABASE_URL: str = "sqlite+aiosqlite:///./pingwatch.db"
|
||||||
@@ -71,7 +72,7 @@ class Settings(BaseSettings):
|
|||||||
# ---------- CORS ----------
|
# ---------- CORS ----------
|
||||||
CORS_ORIGINS: str = "http://localhost:5173,http://10.10.10.7:5173,http://10.10.10.7"
|
CORS_ORIGINS: str = "http://localhost:5173,http://10.10.10.7:5173,http://10.10.10.7"
|
||||||
|
|
||||||
model_config = {"env_file": ".env", "env_file_encoding": "utf-8"}
|
model_config = {"env_file": ".env", "env_file_encoding": "utf-8", "extra": "ignore"}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def CASDOOR_ENDPOINT(self) -> str:
|
def CASDOOR_ENDPOINT(self) -> str:
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ from app.models.user import User, UserRoleEnum
|
|||||||
from app.core.deps import get_db
|
from app.core.deps import get_db
|
||||||
|
|
||||||
logger = logging.getLogger("pingwatch.auth")
|
logger = logging.getLogger("pingwatch.auth")
|
||||||
security = HTTPBearer()
|
security = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||||
@@ -99,10 +99,22 @@ async def exchange_code_for_user(code: str) -> Optional[dict]:
|
|||||||
|
|
||||||
|
|
||||||
async def get_current_user(
|
async def get_current_user(
|
||||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> User:
|
) -> User:
|
||||||
"""从 PingWatch JWT 中解析当前登录用户"""
|
"""从 PingWatch JWT 中解析当前登录用户"""
|
||||||
|
if not settings.auth_enabled:
|
||||||
|
return User(
|
||||||
|
id=0,
|
||||||
|
casdoor_uid="local-anonymous-admin",
|
||||||
|
username="local-admin",
|
||||||
|
display_name="本地管理员",
|
||||||
|
role=UserRoleEnum.admin,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if credentials is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少认证信息")
|
||||||
token = credentials.credentials
|
token = credentials.credentials
|
||||||
try:
|
try:
|
||||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
||||||
|
|||||||
@@ -118,6 +118,12 @@ def _upgrade_postgresql_alert_type(connection: Connection) -> None:
|
|||||||
"""Permit the degraded alert value for databases using PostgreSQL enums."""
|
"""Permit the degraded alert value for databases using PostgreSQL enums."""
|
||||||
if connection.dialect.name == "postgresql":
|
if connection.dialect.name == "postgresql":
|
||||||
enum_name = AlertEvent.__table__.c.alert_type.type.name
|
enum_name = AlertEvent.__table__.c.alert_type.type.name
|
||||||
|
enum_exists = connection.execute(
|
||||||
|
text("SELECT 1 FROM pg_type WHERE typname = :enum_name"),
|
||||||
|
{"enum_name": enum_name},
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if enum_exists is None:
|
||||||
|
return
|
||||||
connection.execute(
|
connection.execute(
|
||||||
text(
|
text(
|
||||||
f"ALTER TYPE {_quote(connection, enum_name)} "
|
f"ALTER TYPE {_quote(connection, enum_name)} "
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Authentication switch behavior."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from app.config import settings
|
||||||
|
from app.core.auth import get_current_user
|
||||||
|
from app.models.user import UserRoleEnum
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_auth_disabled_provides_local_admin_without_token(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "auth_enabled", False)
|
||||||
|
|
||||||
|
user = await get_current_user(credentials=None, db=None)
|
||||||
|
|
||||||
|
assert user.id == 0
|
||||||
|
assert user.username == "local-admin"
|
||||||
|
assert user.role == UserRoleEnum.admin
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_auth_enabled_still_requires_a_token(monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "auth_enabled", True)
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as exc_info:
|
||||||
|
await get_current_user(credentials=None, db=None)
|
||||||
|
|
||||||
|
assert exc_info.value.status_code == 401
|
||||||
@@ -9,7 +9,8 @@ def test_compose_does_not_embed_password_or_net_admin_capability():
|
|||||||
|
|
||||||
assert "POSTGRES_PASSWORD=pingwatch123" not in compose
|
assert "POSTGRES_PASSWORD=pingwatch123" not in compose
|
||||||
assert "NET_ADMIN" not in compose
|
assert "NET_ADMIN" not in compose
|
||||||
assert "127.0.0.1:8001:8000" in compose
|
assert "PINGWATCH_BACKEND_BIND" in compose
|
||||||
|
assert "VITE_AUTH_ENABLED" in compose
|
||||||
|
|
||||||
|
|
||||||
def test_oauth_client_does_not_disable_tls_verification():
|
def test_oauth_client_does_not_disable_tls_verification():
|
||||||
|
|||||||
@@ -66,3 +66,13 @@ def test_enabled_wecom_delivery_requires_all_credentials():
|
|||||||
|
|
||||||
with pytest.raises(ValueError, match="WECOM"):
|
with pytest.raises(ValueError, match="WECOM"):
|
||||||
validate_runtime_settings(settings)
|
validate_runtime_settings(settings)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ignores_compose_only_environment_fields():
|
||||||
|
settings = Settings(
|
||||||
|
environment="test",
|
||||||
|
postgres_password="compose-only",
|
||||||
|
pingwatch_backend_bind="127.0.0.1:18065",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert settings.environment == "test"
|
||||||
|
|||||||
+7
-2
@@ -8,7 +8,7 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
- TZ=Asia/Shanghai
|
- TZ=Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8001:8000"
|
- "${PINGWATCH_BACKEND_BIND:-127.0.0.1:8001}:8000"
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -16,11 +16,16 @@ services:
|
|||||||
- pingwatch_data:/app/data
|
- pingwatch_data:/app/data
|
||||||
networks:
|
networks:
|
||||||
- pingwatch-net
|
- pingwatch-net
|
||||||
|
extra_hosts:
|
||||||
|
- "host.docker.internal:host-gateway"
|
||||||
cap_add:
|
cap_add:
|
||||||
- NET_RAW
|
- NET_RAW
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
build: ./frontend
|
build:
|
||||||
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
VITE_AUTH_ENABLED: "${VITE_AUTH_ENABLED:-false}"
|
||||||
container_name: pingwatch-frontend
|
container_name: pingwatch-frontend
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
+4
-1
@@ -3,8 +3,11 @@ FROM node:20-alpine AS builder
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json ./
|
COPY package.json ./
|
||||||
RUN npm install
|
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||||
|
RUN npm config set registry "$NPM_REGISTRY" && npm install
|
||||||
COPY . .
|
COPY . .
|
||||||
|
ARG VITE_AUTH_ENABLED=false
|
||||||
|
ENV VITE_AUTH_ENABLED=$VITE_AUTH_ENABLED
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# 运行阶段
|
# 运行阶段
|
||||||
|
|||||||
@@ -50,8 +50,19 @@ const router = createRouter({
|
|||||||
routes,
|
routes,
|
||||||
})
|
})
|
||||||
|
|
||||||
// 路由守卫:检查登录
|
// 默认运行在内网免登录模式;需要 Casdoor 时构建时设置 VITE_AUTH_ENABLED=true。
|
||||||
|
const authEnabled = import.meta.env.VITE_AUTH_ENABLED === 'true'
|
||||||
|
|
||||||
router.beforeEach((to, from, next) => {
|
router.beforeEach((to, from, next) => {
|
||||||
|
if (!authEnabled) {
|
||||||
|
if (to.name === 'Login') {
|
||||||
|
next({ name: 'Dashboard' })
|
||||||
|
} else {
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const token = localStorage.getItem('token')
|
const token = localStorage.getItem('token')
|
||||||
if (to.name !== 'Login' && !token) {
|
if (to.name !== 'Login' && !token) {
|
||||||
next({ name: 'Login' })
|
next({ name: 'Login' })
|
||||||
|
|||||||
@@ -3,12 +3,19 @@ import { ref, computed } from 'vue'
|
|||||||
import { authApi, statsApi } from '@/api'
|
import { authApi, statsApi } from '@/api'
|
||||||
|
|
||||||
export const useAppStore = defineStore('app', () => {
|
export const useAppStore = defineStore('app', () => {
|
||||||
|
const authEnabled = import.meta.env.VITE_AUTH_ENABLED === 'true'
|
||||||
|
const localAdmin = {
|
||||||
|
id: 0,
|
||||||
|
username: 'local-admin',
|
||||||
|
display_name: '本地管理员',
|
||||||
|
role: 'admin',
|
||||||
|
}
|
||||||
// 用户状态
|
// 用户状态
|
||||||
const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
|
const user = ref(authEnabled ? JSON.parse(localStorage.getItem('user') || 'null') : localAdmin)
|
||||||
const token = ref(localStorage.getItem('token') || '')
|
const token = ref(localStorage.getItem('token') || '')
|
||||||
|
|
||||||
const isLoggedIn = computed(() => !!token.value)
|
const isLoggedIn = computed(() => !authEnabled || !!token.value)
|
||||||
const isAdmin = computed(() => user.value?.role === 'admin')
|
const isAdmin = computed(() => !authEnabled || user.value?.role === 'admin')
|
||||||
|
|
||||||
function setUser(userData, tokenStr) {
|
function setUser(userData, tokenStr) {
|
||||||
user.value = userData
|
user.value = userData
|
||||||
@@ -18,6 +25,7 @@ export const useAppStore = defineStore('app', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function logout() {
|
function logout() {
|
||||||
|
if (!authEnabled) return
|
||||||
user.value = null
|
user.value = null
|
||||||
token.value = ''
|
token.value = ''
|
||||||
localStorage.removeItem('user')
|
localStorage.removeItem('user')
|
||||||
@@ -77,7 +85,7 @@ export const useAppStore = defineStore('app', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
user, token, isLoggedIn, isAdmin,
|
user, token, authEnabled, isLoggedIn, isAdmin,
|
||||||
setUser, logout,
|
setUser, logout,
|
||||||
dashboardData, loading, fetchDashboard,
|
dashboardData, loading, fetchDashboard,
|
||||||
connectWebSocket,
|
connectWebSocket,
|
||||||
|
|||||||
@@ -58,7 +58,7 @@
|
|||||||
</el-breadcrumb>
|
</el-breadcrumb>
|
||||||
</div>
|
</div>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<el-dropdown @command="handleCommand">
|
<el-dropdown v-if="store.authEnabled" @command="handleCommand">
|
||||||
<span class="user-info">
|
<span class="user-info">
|
||||||
{{ store.user?.display_name || store.user?.username }}
|
{{ store.user?.display_name || store.user?.username }}
|
||||||
<el-icon><ArrowDown /></el-icon>
|
<el-icon><ArrowDown /></el-icon>
|
||||||
@@ -74,6 +74,7 @@
|
|||||||
</el-dropdown-menu>
|
</el-dropdown-menu>
|
||||||
</template>
|
</template>
|
||||||
</el-dropdown>
|
</el-dropdown>
|
||||||
|
<span v-else class="user-info">本地管理员</span>
|
||||||
</div>
|
</div>
|
||||||
</el-header>
|
</el-header>
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user