feat(admin): 从管理端免登打开 Dify 控制台
工作人员经一次性跳转进入本地 Dify。AI 智能体菜单去掉已停用项,文件页工具栏收进表头,并关闭快速入口。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d96f7a2238
commit
60158935f4
14 files changed
+521
-53
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import request from '@/utils/http'
|
||||
|
||||
export interface DifySsoResult {
|
||||
redirectUrl: string
|
||||
email: string
|
||||
nextPath: string
|
||||
expiresIn: number
|
||||
}
|
||||
|
||||
/** Exchange the current admin session for a Dify console redirect URL. */
|
||||
export function createDifySso(nextPath = '/apps') {
|
||||
return request.post<DifySsoResult>({
|
||||
url: '/api/admin/dify/sso',
|
||||
data: { nextPath }
|
||||
})
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export const headerBarConfig: HeaderBarFeatureConfig = {
|
||||
description: '页面刷新按钮'
|
||||
},
|
||||
fastEnter: {
|
||||
enabled: true,
|
||||
enabled: false,
|
||||
description: '快速入口功能,提供常用应用和链接的快速访问'
|
||||
},
|
||||
breadcrumb: {
|
||||
|
||||
@@ -46,7 +46,7 @@ export const SETTING_DEFAULT_CONFIG = {
|
||||
/** 是否显示菜单按钮 */
|
||||
showMenuButton: true,
|
||||
/** 是否显示快速入口 */
|
||||
showFastEnter: true,
|
||||
showFastEnter: false,
|
||||
/** 是否显示刷新按钮 */
|
||||
showRefreshButton: true,
|
||||
/** 是否显示面包屑 */
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<template>
|
||||
<div class="box-border h-full min-h-[calc(100vh-120px)] w-full" v-loading="isLoading">
|
||||
<el-result
|
||||
v-if="errorMessage"
|
||||
class="flex min-h-[calc(100vh-120px)] items-center justify-center"
|
||||
icon="warning"
|
||||
title="无法嵌入打开 Dify"
|
||||
:sub-title="errorMessage"
|
||||
>
|
||||
<template #extra>
|
||||
<el-button type="primary" @click="loadFrame">重试</el-button>
|
||||
</template>
|
||||
</el-result>
|
||||
<iframe
|
||||
v-else-if="iframeUrl"
|
||||
ref="iframeRef"
|
||||
:src="iframeUrl"
|
||||
title="AI智能体"
|
||||
class="h-full min-h-[calc(100vh-120px)] w-full border-none"
|
||||
@load="handleIframeLoad"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { createDifySso } from '@/api/dify'
|
||||
|
||||
defineOptions({ name: 'DifySsoOpen' })
|
||||
|
||||
const route = useRoute()
|
||||
const isLoading = ref(true)
|
||||
const errorMessage = ref('')
|
||||
const iframeUrl = ref('')
|
||||
const iframeRef = ref<HTMLIFrameElement | null>(null)
|
||||
|
||||
const PATH_MAP: Record<string, string> = {
|
||||
'/dify/home': '/',
|
||||
'/dify/apps': '/apps',
|
||||
'/dify/datasets': '/datasets',
|
||||
'/dify/skills': '/skills',
|
||||
'/dify/integrations': '/integrations',
|
||||
'/dify/marketplace': '/marketplace',
|
||||
'/dify/tools': '/tools',
|
||||
'/dify/explore': '/explore/apps'
|
||||
}
|
||||
|
||||
function resolveNextPath(): string {
|
||||
const fromQuery = String(route.query.next || '').trim()
|
||||
if (fromQuery.startsWith('/') && !fromQuery.startsWith('//')) {
|
||||
return fromQuery
|
||||
}
|
||||
return PATH_MAP[route.path] || '/apps'
|
||||
}
|
||||
|
||||
async function loadFrame() {
|
||||
isLoading.value = true
|
||||
errorMessage.value = ''
|
||||
iframeUrl.value = ''
|
||||
try {
|
||||
const result = await createDifySso(resolveNextPath())
|
||||
iframeUrl.value = result.redirectUrl
|
||||
} catch (error: any) {
|
||||
errorMessage.value = error?.message || '免登失败'
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleIframeLoad(): void {
|
||||
isLoading.value = false
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.fullPath,
|
||||
() => {
|
||||
void loadFrame()
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
void loadFrame()
|
||||
})
|
||||
</script>
|
||||
@@ -3,16 +3,38 @@
|
||||
<div class="file-page art-full-height">
|
||||
<ElCard class="art-table-card">
|
||||
<div class="file-toolbar">
|
||||
<div class="file-toolbar__upload">
|
||||
<span class="file-toolbar__label">上传到</span>
|
||||
<ElRadioGroup v-model="bucket">
|
||||
<ElRadioButton value="public">公开</ElRadioButton>
|
||||
<ElRadioButton value="private">私有</ElRadioButton>
|
||||
</ElRadioGroup>
|
||||
<ElButton v-auth="'file:upload'" type="primary" @click="pickFiles">选择文件</ElButton>
|
||||
<span class="file-toolbar__hint">可多选,也可在本页粘贴图片</span>
|
||||
<input ref="fileInput" class="hidden" type="file" multiple @change="onPick" />
|
||||
</div>
|
||||
<ArtTableHeader
|
||||
v-model:columns="columnChecks"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
>
|
||||
<template #left>
|
||||
<div class="file-toolbar__main">
|
||||
<div class="file-toolbar__upload">
|
||||
<span class="file-toolbar__label">上传到</span>
|
||||
<ElRadioGroup v-model="bucket">
|
||||
<ElRadioButton value="public">公开</ElRadioButton>
|
||||
<ElRadioButton value="private">私有</ElRadioButton>
|
||||
</ElRadioGroup>
|
||||
<ElButton v-auth="'file:upload'" type="primary" @click="pickFiles">选择文件</ElButton>
|
||||
<input ref="fileInput" class="hidden" type="file" multiple @change="onPick" />
|
||||
</div>
|
||||
|
||||
<ListKeywordSearch v-model="keyword" placeholder="检索文件名" @search="searchFiles">
|
||||
<ElSelect
|
||||
v-model="listBucket"
|
||||
clearable
|
||||
placeholder="全部桶"
|
||||
class="file-toolbar__bucket"
|
||||
@change="reload"
|
||||
>
|
||||
<ElOption label="公开" value="public" />
|
||||
<ElOption label="私有" value="private" />
|
||||
</ElSelect>
|
||||
</ListKeywordSearch>
|
||||
</div>
|
||||
</template>
|
||||
</ArtTableHeader>
|
||||
|
||||
<div v-if="tasks.length" class="file-toolbar__tasks">
|
||||
<div v-for="task in tasks" :key="task.id" class="file-toolbar__task">
|
||||
@@ -32,26 +54,6 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="file-toolbar__filters">
|
||||
<ListKeywordSearch v-model="keyword" placeholder="检索文件名" @search="searchFiles">
|
||||
<ElSelect
|
||||
v-model="listBucket"
|
||||
clearable
|
||||
placeholder="全部桶"
|
||||
class="file-toolbar__bucket"
|
||||
@change="reload"
|
||||
>
|
||||
<ElOption label="公开" value="public" />
|
||||
<ElOption label="私有" value="private" />
|
||||
</ElSelect>
|
||||
</ListKeywordSearch>
|
||||
<ArtTableHeader
|
||||
v-model:columns="columnChecks"
|
||||
:loading="loading"
|
||||
@refresh="refreshData"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ArtTable
|
||||
@@ -286,14 +288,23 @@
|
||||
|
||||
<style scoped>
|
||||
.file-toolbar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
margin-bottom: 12px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.file-toolbar :deep(#art-table-header) {
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.file-toolbar__main {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 16px;
|
||||
}
|
||||
|
||||
.file-toolbar__upload {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -301,8 +312,7 @@
|
||||
gap: 10px 12px;
|
||||
}
|
||||
|
||||
.file-toolbar__label,
|
||||
.file-toolbar__hint {
|
||||
.file-toolbar__label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
@@ -312,6 +322,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.file-toolbar__task-meta {
|
||||
@@ -322,23 +333,15 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.file-toolbar__filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
}
|
||||
|
||||
.file-toolbar__filters :deep(.list-keyword-search-bar) {
|
||||
.file-toolbar :deep(.list-keyword-search-bar) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.file-toolbar__filters :deep(#art-table-header) {
|
||||
flex: 1 1 220px;
|
||||
min-width: 0;
|
||||
.file-toolbar :deep(.list-keyword-search) {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.file-toolbar__bucket {
|
||||
width: 140px;
|
||||
width: 120px;
|
||||
}
|
||||
</style>
|
||||
@@ -18,12 +18,16 @@ REDIS_TIMEOUT_SEC=30
|
||||
REDIS_SSL_ENABLED=false
|
||||
|
||||
STORAGE_TYPE=minio
|
||||
# MINIO_ENDPOINT:服务端访问 MinIO 的地址(内网或本机即可)。
|
||||
MINIO_ENDPOINT=127.0.0.1:9000
|
||||
MINIO_ACCESS_KEY=
|
||||
MINIO_SECRET_KEY=
|
||||
MINIO_BUCKET_PUBLIC=gsfdc-public
|
||||
MINIO_BUCKET_PRIVATE=gsfdc-private
|
||||
MINIO_SECURE=false
|
||||
# MINIO_BASE_URL:公开图片/附件对外访问基址(含公开桶路径)。
|
||||
# 门户与管理端接口返回的 imageUrl、附件 url 都基于此项拼接,不跟站点主域名走。
|
||||
# 本地可直连 MinIO;生产填独立资源域名,例如 https://static.example.com(反代到公开桶)。
|
||||
MINIO_BASE_URL=http://127.0.0.1:9000/gsfdc-public
|
||||
|
||||
# 手机号、身份证字段加密。与 API_PAYLOAD_AES_KEY 不是同一把钥匙。32 字节密钥的 Base64。
|
||||
@@ -44,3 +48,9 @@ SMTP_USER=
|
||||
SMTP_PASSWORD=
|
||||
SMTP_SENDER=
|
||||
SMTP_USE_SSL=true
|
||||
|
||||
# Dify 控制台免登桥(与 demo-dify 的 GSREA_SSO_SECRET 相同,至少 32 字符)
|
||||
DIFY_PUBLIC_URL=http://127.0.0.1:13080
|
||||
DIFY_SSO_SECRET=
|
||||
DIFY_SSO_EMAIL_DOMAIN=gsrea.local
|
||||
DIFY_SSO_TTL_SEC=90
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.deps import require_staff
|
||||
from app.db import get_db
|
||||
from app.services import dify_sso as dify_sso_service
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_staff)])
|
||||
|
||||
|
||||
class SsoOpenIn(BaseModel):
|
||||
nextPath: str | None = Field(default="/apps", description="Dify console path after login")
|
||||
|
||||
|
||||
def _actor_id(principal: dict = Depends(require_staff)) -> int:
|
||||
try:
|
||||
return int(principal["sub"])
|
||||
except (TypeError, ValueError):
|
||||
from fastapi import HTTPException
|
||||
|
||||
raise HTTPException(status_code=401, detail="登录已失效")
|
||||
|
||||
|
||||
@router.post("/dify/sso")
|
||||
def open_dify_sso(
|
||||
body: SsoOpenIn,
|
||||
actor_id: int = Depends(_actor_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Issue a one-shot redirect URL that logs the current staff into Dify."""
|
||||
return dify_sso_service.issue_redirect(db, user_id=actor_id, next_path=body.nextPath)
|
||||
@@ -11,6 +11,7 @@ from app.api.admin.reports import router as admin_reports_router
|
||||
from app.api.admin.legal import router as admin_legal_router
|
||||
from app.api.admin.rbac import public_router as rbac_public_router
|
||||
from app.api.admin.rbac import router as rbac_router
|
||||
from app.api.admin.dify_sso import router as admin_dify_sso_router
|
||||
from app.api.admin.routes import router as admin_router
|
||||
from app.api.admin.security import public_router as security_public_router
|
||||
from app.api.admin.security import router as security_router
|
||||
@@ -49,4 +50,5 @@ api_router.include_router(admin_edu_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_legal_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_expert_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_uploaded_cases_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_dify_sso_router, prefix="/api/admin")
|
||||
api_router.include_router(admin_router, prefix="/api/admin")
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
import sys
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import Base, SessionLocal, get_engine
|
||||
@@ -106,6 +106,26 @@ def _find_resource(db: Session, parent_id: int | None, name: str) -> AdminResour
|
||||
|
||||
# Keep system management after all business top-level menus.
|
||||
SYSTEM_MENU_SORT = 99
|
||||
# AI agent console sits immediately above system management.
|
||||
AI_AGENT_MENU_SORT = 98
|
||||
|
||||
# Mirrors Dify console main nav entries that are usable in this community build.
|
||||
# Contacts needs HITL IM (disabled locally) and was blank; Agents removed per product request.
|
||||
# Home is soft-deleted (status=cancelled): hidden from sidebar and menu admin, row kept.
|
||||
AI_AGENT_MENUS = (
|
||||
("AiAgentApps", "工作室", "/dify/apps", "ri:apps-2-line", 1),
|
||||
("AiAgentDatasets", "知识库", "/dify/datasets", "ri:book-2-line", 2),
|
||||
("AiAgentSkills", "Skills", "/dify/skills", "ri:magic-line", 3),
|
||||
("AiAgentIntegrations", "集成", "/dify/integrations", "ri:puzzle-2-line", 4),
|
||||
("AiAgentMarketplace", "Marketplace", "/dify/marketplace", "ri:store-2-line", 5),
|
||||
)
|
||||
AI_AGENT_SOFT_DELETED_MENUS = (
|
||||
("AiAgentHome", "主页", "/dify/home", "ri:home-4-line", 99),
|
||||
)
|
||||
AI_AGENT_RETIRED_MENU_NAMES = (
|
||||
"AiAgentAgents",
|
||||
"AiAgentContacts",
|
||||
)
|
||||
|
||||
|
||||
def ensure_system_menu_order(db: Session) -> None:
|
||||
@@ -120,6 +140,135 @@ def ensure_system_menu_order(db: Session) -> None:
|
||||
db.flush()
|
||||
|
||||
|
||||
def _delete_resource_tree(db: Session, root: AdminResource) -> None:
|
||||
"""Permanently remove a duplicated menu tree (MySQL allows multiple NULL-parent rows with the same name)."""
|
||||
stack = [root.id]
|
||||
ordered: list[int] = []
|
||||
while stack:
|
||||
current_id = stack.pop()
|
||||
ordered.append(current_id)
|
||||
ordered_children = list(
|
||||
db.scalars(select(AdminResource.id).where(AdminResource.parent_id == current_id)).all()
|
||||
)
|
||||
stack.extend(ordered_children)
|
||||
# Flush each delete so MySQL never sees parent removal before children.
|
||||
for resource_id in reversed(ordered):
|
||||
db.execute(delete(AdminRoleResource).where(AdminRoleResource.resource_id == resource_id))
|
||||
db.execute(delete(AdminResource).where(AdminResource.id == resource_id))
|
||||
db.flush()
|
||||
|
||||
|
||||
def _soft_delete_resource(db: Session, row: AdminResource) -> None:
|
||||
"""Hide a menu from sidebar + menu admin while keeping the row (status=cancelled)."""
|
||||
row.visible = False
|
||||
row.status = "cancelled"
|
||||
db.execute(delete(AdminRoleResource).where(AdminRoleResource.resource_id == row.id))
|
||||
db.flush()
|
||||
|
||||
|
||||
def ensure_ai_agent_menu(db: Session) -> None:
|
||||
"""Seed Dify SSO entry menus above System management."""
|
||||
# MySQL unique(parent_id, name) does not block duplicate top-level rows when parent_id is NULL.
|
||||
directories = list(
|
||||
db.scalars(
|
||||
select(AdminResource)
|
||||
.where(AdminResource.parent_id.is_(None), AdminResource.name == "AiAgent")
|
||||
.order_by(AdminResource.id.asc())
|
||||
).all()
|
||||
)
|
||||
for extra in directories[1:]:
|
||||
_delete_resource_tree(db, extra)
|
||||
db.flush()
|
||||
|
||||
directory = _ensure_resource(
|
||||
db,
|
||||
parent_id=None,
|
||||
resource_type="directory",
|
||||
name="AiAgent",
|
||||
title="AI智能体",
|
||||
path="/dify",
|
||||
component="",
|
||||
icon="ri:sparkling-2-line",
|
||||
permission="",
|
||||
sort=AI_AGENT_MENU_SORT,
|
||||
visible=True,
|
||||
)
|
||||
pages = [
|
||||
_ensure_resource(
|
||||
db,
|
||||
parent_id=directory.id,
|
||||
resource_type="menu",
|
||||
name=name,
|
||||
title=title,
|
||||
path=path,
|
||||
component="/dify/sso-open",
|
||||
icon=icon,
|
||||
permission="",
|
||||
sort=sort,
|
||||
visible=True,
|
||||
)
|
||||
for name, title, path, icon, sort in AI_AGENT_MENUS
|
||||
]
|
||||
soft_deleted_pages = []
|
||||
for name, title, path, icon, sort in AI_AGENT_SOFT_DELETED_MENUS:
|
||||
row = _ensure_resource(
|
||||
db,
|
||||
parent_id=directory.id,
|
||||
resource_type="menu",
|
||||
name=name,
|
||||
title=title,
|
||||
path=path,
|
||||
component="/dify/sso-open",
|
||||
icon=icon,
|
||||
permission="",
|
||||
sort=sort,
|
||||
visible=False,
|
||||
)
|
||||
_soft_delete_resource(db, row)
|
||||
soft_deleted_pages.append(row)
|
||||
# Collapse any child duplicates under the kept directory.
|
||||
for name, *_rest in (*AI_AGENT_MENUS, *AI_AGENT_SOFT_DELETED_MENUS):
|
||||
siblings = list(
|
||||
db.scalars(
|
||||
select(AdminResource)
|
||||
.where(AdminResource.parent_id == directory.id, AdminResource.name == name)
|
||||
.order_by(AdminResource.id.asc())
|
||||
).all()
|
||||
)
|
||||
for extra in siblings[1:]:
|
||||
_delete_resource_tree(db, extra)
|
||||
for retired_name in AI_AGENT_RETIRED_MENU_NAMES:
|
||||
for row in db.scalars(
|
||||
select(AdminResource).where(
|
||||
AdminResource.parent_id == directory.id,
|
||||
AdminResource.name == retired_name,
|
||||
)
|
||||
).all():
|
||||
_delete_resource_tree(db, row)
|
||||
role = db.scalar(select(AdminRole).where(AdminRole.code == SUPER_CODE))
|
||||
if role is None:
|
||||
db.flush()
|
||||
return
|
||||
linked = set(
|
||||
db.scalars(
|
||||
select(AdminRoleResource.resource_id).where(AdminRoleResource.role_id == role.id)
|
||||
).all()
|
||||
)
|
||||
# Soft-deleted menus stay unlinked so they never reappear via role grants.
|
||||
for resource_id in [directory.id, *[page.id for page in pages]]:
|
||||
if resource_id not in linked:
|
||||
db.add(AdminRoleResource(role_id=role.id, resource_id=resource_id))
|
||||
for page in soft_deleted_pages:
|
||||
if page.id in linked:
|
||||
db.execute(
|
||||
delete(AdminRoleResource).where(
|
||||
AdminRoleResource.role_id == role.id,
|
||||
AdminRoleResource.resource_id == page.id,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
|
||||
|
||||
def _ensure_resource(
|
||||
db: Session,
|
||||
*,
|
||||
@@ -947,6 +1096,8 @@ def seed_superuser(db: Session, username: str, password: str) -> None:
|
||||
db.add(AdminUserRole(user_id=user.id, role_id=role.id))
|
||||
db.flush()
|
||||
ensure_home_menu(db)
|
||||
ensure_ai_agent_menu(db)
|
||||
ensure_system_menu_order(db)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -41,6 +41,11 @@ class Settings(BaseSettings):
|
||||
smtp_password: str = ""
|
||||
smtp_sender: str = ""
|
||||
smtp_use_ssl: bool = True
|
||||
# Dify console SSO bridge (demo). Shared HMAC secret with demo-dify GSREA_SSO_SECRET.
|
||||
dify_public_url: str = "http://127.0.0.1:13080"
|
||||
dify_sso_secret: str = ""
|
||||
dify_sso_email_domain: str = "gsrea.local"
|
||||
dify_sso_ttl_sec: int = 90
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
|
||||
@@ -49,6 +49,7 @@ def prepare_runtime() -> None:
|
||||
seed_ip_blacklist(db)
|
||||
from app.commands.create_superuser import (
|
||||
ensure_about_menu,
|
||||
ensure_ai_agent_menu,
|
||||
ensure_directory_menu,
|
||||
ensure_expert_menu,
|
||||
ensure_home_menu,
|
||||
@@ -71,6 +72,7 @@ def prepare_runtime() -> None:
|
||||
ensure_discipline_menu(db)
|
||||
ensure_tech_menu(db)
|
||||
ensure_edu_menu(db)
|
||||
ensure_ai_agent_menu(db)
|
||||
ensure_system_menu_order(db)
|
||||
db.commit()
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Issue short-lived tickets so admin staff can open Dify without a second login."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
import jwt
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.models.rbac import AdminUser
|
||||
|
||||
_USERNAME_SAFE = re.compile(r"^[a-zA-Z0-9._-]+$")
|
||||
_NEXT_SAFE = re.compile(r"^/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$")
|
||||
|
||||
|
||||
def _bad(detail: str, code: int = status.HTTP_400_BAD_REQUEST) -> None:
|
||||
raise HTTPException(status_code=code, detail=detail)
|
||||
|
||||
|
||||
def resolve_next_path(raw: str | None) -> str:
|
||||
value = (raw or "/apps").strip() or "/apps"
|
||||
if not value.startswith("/"):
|
||||
value = "/" + value
|
||||
if value.startswith("//") or not _NEXT_SAFE.match(value):
|
||||
_bad("无效的跳转路径")
|
||||
return value
|
||||
|
||||
|
||||
def email_for_username(username: str) -> str:
|
||||
settings = get_settings()
|
||||
domain = (settings.dify_sso_email_domain or "gsrea.local").strip().lower()
|
||||
return f"{username.lower()}@{domain}"
|
||||
|
||||
|
||||
def issue_redirect(db: Session, *, user_id: int, next_path: str | None) -> dict:
|
||||
settings = get_settings()
|
||||
secret = (settings.dify_sso_secret or "").strip()
|
||||
public_url = (settings.dify_public_url or "").strip().rstrip("/")
|
||||
if len(secret) < 32:
|
||||
_bad("Dify 免登未配置密钥", status.HTTP_503_SERVICE_UNAVAILABLE)
|
||||
if not public_url:
|
||||
_bad("Dify 免登未配置公网地址", status.HTTP_503_SERVICE_UNAVAILABLE)
|
||||
|
||||
user = db.get(AdminUser, user_id)
|
||||
if user is None or user.status != "active":
|
||||
_bad("账号不可用", status.HTTP_403_FORBIDDEN)
|
||||
username = (user.username or "").strip()
|
||||
if not username or not _USERNAME_SAFE.match(username):
|
||||
_bad("用户名无法映射到 Dify 账号")
|
||||
|
||||
next_value = resolve_next_path(next_path)
|
||||
now = datetime.now(timezone.utc)
|
||||
jti = uuid4().hex
|
||||
ticket = jwt.encode(
|
||||
{
|
||||
"typ": "dify_sso",
|
||||
"sub": str(user.id),
|
||||
"username": username,
|
||||
"name": (user.display_name or username)[:30],
|
||||
"email": email_for_username(username),
|
||||
"next": next_value,
|
||||
"jti": jti,
|
||||
"iat": now,
|
||||
"exp": now + timedelta(seconds=max(30, settings.dify_sso_ttl_sec)),
|
||||
},
|
||||
secret,
|
||||
algorithm="HS256",
|
||||
)
|
||||
redirect_url = f"{public_url}/console/api/gsrea/sso/consume?ticket={quote(ticket, safe='')}"
|
||||
return {
|
||||
"redirectUrl": redirect_url,
|
||||
"email": email_for_username(username),
|
||||
"nextPath": next_value,
|
||||
"expiresIn": max(30, settings.dify_sso_ttl_sec),
|
||||
}
|
||||
|
||||
@@ -587,7 +587,10 @@ def replace_role_resources(db: Session, role_id: int, resource_ids: list[int]) -
|
||||
|
||||
|
||||
def list_resources(db: Session) -> list[dict]:
|
||||
rows = list(db.scalars(select(AdminResource)).all())
|
||||
# Soft-deleted (status=cancelled) menus are kept in DB but excluded from menu admin.
|
||||
rows = list(
|
||||
db.scalars(select(AdminResource).where(AdminResource.status.in_(tuple(RESOURCE_STATUSES)))).all()
|
||||
)
|
||||
return build_tree(rows)
|
||||
|
||||
|
||||
|
||||
@@ -66,14 +66,14 @@ _install_stub(
|
||||
)
|
||||
|
||||
from app.api.admin.rbac import public_router, router
|
||||
from app.commands.create_superuser import seed_superuser
|
||||
from app.commands.create_superuser import ensure_ai_agent_menu, seed_superuser
|
||||
from app.core.config import get_settings
|
||||
from app.core.masking import mask_mobile
|
||||
from app.core.security import create_access_token
|
||||
from app.db import Base, get_db, get_engine
|
||||
from app.main import create_app
|
||||
from app.models.rbac import AdminResource, AdminRole, AdminRoleResource, AdminUser, AdminUserRole, utcnow
|
||||
from app.services.rbac import count_full_admins, preserve_full_admin
|
||||
from app.services.rbac import count_full_admins, list_resources as list_resource_tree, preserve_full_admin
|
||||
|
||||
get_settings.cache_clear()
|
||||
|
||||
@@ -680,6 +680,87 @@ def test_preserve_last_full_admin(client: TestClient):
|
||||
db.close()
|
||||
|
||||
|
||||
def test_ensure_ai_agent_menu_removes_duplicate_roots(client: TestClient):
|
||||
connection = client.app.state.connection
|
||||
db = Session(
|
||||
bind=connection,
|
||||
autoflush=False,
|
||||
expire_on_commit=False,
|
||||
join_transaction_mode="create_savepoint",
|
||||
)
|
||||
try:
|
||||
ensure_ai_agent_menu(db)
|
||||
db.flush()
|
||||
first = db.scalar(
|
||||
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "AiAgent")
|
||||
)
|
||||
assert first is not None
|
||||
# Simulate MySQL NULL-parent unique gap: a second root with the same name.
|
||||
dup = AdminResource(
|
||||
parent_id=None,
|
||||
type="directory",
|
||||
name="AiAgent",
|
||||
title="AI智能体",
|
||||
path="/dify",
|
||||
component="",
|
||||
icon="ri:sparkling-2-line",
|
||||
permission="",
|
||||
sort=98,
|
||||
visible=True,
|
||||
status="active",
|
||||
)
|
||||
db.add(dup)
|
||||
db.flush()
|
||||
child = AdminResource(
|
||||
parent_id=dup.id,
|
||||
type="menu",
|
||||
name="AiAgentHome",
|
||||
title="主页",
|
||||
path="/dify/home",
|
||||
component="/dify/sso-open",
|
||||
icon="ri:home-4-line",
|
||||
permission="",
|
||||
sort=1,
|
||||
visible=True,
|
||||
status="active",
|
||||
)
|
||||
db.add(child)
|
||||
db.flush()
|
||||
before = db.scalars(
|
||||
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "AiAgent")
|
||||
).all()
|
||||
assert len(before) == 2
|
||||
|
||||
ensure_ai_agent_menu(db)
|
||||
db.flush()
|
||||
after = db.scalars(
|
||||
select(AdminResource).where(AdminResource.parent_id.is_(None), AdminResource.name == "AiAgent")
|
||||
).all()
|
||||
assert len(after) == 1
|
||||
assert after[0].id == first.id
|
||||
home = db.scalar(
|
||||
select(AdminResource).where(
|
||||
AdminResource.parent_id == first.id,
|
||||
AdminResource.name == "AiAgentHome",
|
||||
)
|
||||
)
|
||||
assert home is not None
|
||||
assert home.status == "cancelled"
|
||||
assert home.visible is False
|
||||
tree = list_resource_tree(db)
|
||||
ai_nodes = [node for node in tree if node["name"] == "AiAgent"]
|
||||
assert len(ai_nodes) == 1
|
||||
# Soft-deleted menus must not appear in menu-admin tree.
|
||||
home_titles = [
|
||||
child["title"]
|
||||
for child in (ai_nodes[0].get("children") or [])
|
||||
if child["name"] == "AiAgentHome"
|
||||
]
|
||||
assert home_titles == []
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_seed_superuser_is_idempotent(client: TestClient):
|
||||
connection = client.app.state.connection
|
||||
db = Session(
|
||||
|
||||
Reference in new issue
Block a user