演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
170 lines
5.6 KiB
Python
170 lines
5.6 KiB
Python
"""GSREA admin → Dify console SSO bridge (community edition custom)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import secrets
|
|
import urllib.parse
|
|
from typing import Any
|
|
|
|
import jwt
|
|
from flask import redirect, request
|
|
from flask_restx import Resource
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from configs import dify_config
|
|
from controllers.console import console_ns
|
|
from controllers.console.wraps import setup_required
|
|
from extensions.ext_application_services import application_services
|
|
from extensions.ext_database import db
|
|
from extensions.ext_redis import redis_client
|
|
from libs.helper import extract_remote_ip
|
|
from libs.token import (
|
|
set_access_token_to_cookie,
|
|
set_csrf_token_to_cookie,
|
|
set_refresh_token_to_cookie,
|
|
)
|
|
from models.account import Tenant, TenantAccountJoin, TenantAccountRole
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_TOKEN_TYPE = "dify_sso"
|
|
_JTI_KEY = "gsrea:sso:jti:{jti}"
|
|
|
|
|
|
def _sso_secret() -> str:
|
|
return (os.environ.get("GSREA_SSO_SECRET") or "").strip()
|
|
|
|
|
|
def _console_web_url() -> str:
|
|
configured = (os.environ.get("GSREA_SSO_CONSOLE_WEB_URL") or "").strip().rstrip("/")
|
|
if configured:
|
|
return configured
|
|
return (dify_config.CONSOLE_WEB_URL or "http://127.0.0.1:13080").rstrip("/")
|
|
|
|
|
|
def _safe_next_path(raw: Any) -> str:
|
|
value = str(raw or "/apps").strip() or "/apps"
|
|
if not value.startswith("/"):
|
|
value = "/" + value
|
|
parsed = urllib.parse.urlsplit(value)
|
|
if parsed.scheme or parsed.netloc or value.startswith("//"):
|
|
return "/apps"
|
|
return value
|
|
|
|
|
|
def _signin_error(message: str):
|
|
query = urllib.parse.urlencode({"message": message})
|
|
return redirect(f"{_console_web_url()}/signin?{query}")
|
|
|
|
|
|
def _decode_ticket(ticket: str) -> dict[str, Any]:
|
|
secret = _sso_secret()
|
|
if len(secret) < 32:
|
|
raise ValueError("SSO is not configured")
|
|
payload = jwt.decode(ticket, secret, algorithms=["HS256"])
|
|
if payload.get("typ") != _TOKEN_TYPE:
|
|
raise ValueError("invalid token type")
|
|
if not payload.get("email") or not payload.get("jti"):
|
|
raise ValueError("incomplete token")
|
|
return payload
|
|
|
|
|
|
def _burn_jti(jti: str) -> bool:
|
|
return bool(redis_client.set(_JTI_KEY.format(jti=jti), "1", nx=True, ex=180))
|
|
|
|
|
|
def _ensure_default_membership(account_id: str) -> None:
|
|
with sessionmaker(db.engine, expire_on_commit=False).begin() as session:
|
|
tenant = session.scalars(select(Tenant).order_by(Tenant.created_at.asc()).limit(1)).first()
|
|
if tenant is None:
|
|
raise RuntimeError("no workspace")
|
|
membership = session.scalar(
|
|
select(TenantAccountJoin)
|
|
.where(TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account_id)
|
|
.limit(1)
|
|
)
|
|
if membership is None:
|
|
session.add(
|
|
TenantAccountJoin(
|
|
tenant_id=tenant.id,
|
|
account_id=account_id,
|
|
role=TenantAccountRole.EDITOR,
|
|
current=True,
|
|
)
|
|
)
|
|
return
|
|
membership.current = True
|
|
if membership.role == TenantAccountRole.OWNER:
|
|
return
|
|
|
|
|
|
def _ensure_account(email: str, name: str, ip_address: str):
|
|
lifecycle = application_services().accounts.lifecycle
|
|
account = lifecycle.get_account_by_email_with_case_fallback(email)
|
|
if account is None:
|
|
account = lifecycle.create_account(
|
|
email=email.lower(),
|
|
name=(name or email.split("@", 1)[0])[:30],
|
|
interface_language="zh-Hans",
|
|
password=secrets.token_urlsafe(32),
|
|
is_setup=True,
|
|
initialized=True,
|
|
status="active",
|
|
ip_address=ip_address,
|
|
)
|
|
return account
|
|
|
|
|
|
def _redirect_with_session(tokens, target_url: str):
|
|
response = redirect(target_url)
|
|
set_access_token_to_cookie(request, response, tokens.access_token)
|
|
set_refresh_token_to_cookie(request, response, tokens.refresh_token)
|
|
set_csrf_token_to_cookie(request, response, tokens.csrf_token)
|
|
# Admin embeds Dify in an iframe and owns primary navigation; hide Dify's left main nav.
|
|
response.set_cookie(
|
|
"gsrea_embed",
|
|
"1",
|
|
max_age=60 * 60 * 24 * 30,
|
|
path="/",
|
|
httponly=False,
|
|
samesite="Lax",
|
|
)
|
|
return response
|
|
|
|
|
|
@console_ns.route("/gsrea/sso/consume")
|
|
class GsreaSsoConsumeApi(Resource):
|
|
@setup_required
|
|
def get(self):
|
|
ticket = (request.args.get("ticket") or "").strip()
|
|
if not ticket:
|
|
return _signin_error("缺少免登票据")
|
|
try:
|
|
payload = _decode_ticket(ticket)
|
|
except Exception:
|
|
logger.info("gsrea sso ticket rejected", exc_info=True)
|
|
return _signin_error("免登票据无效或已过期")
|
|
|
|
jti = str(payload["jti"])
|
|
if not _burn_jti(jti):
|
|
return _signin_error("免登票据已使用")
|
|
|
|
email = str(payload["email"]).lower()
|
|
name = str(payload.get("name") or email.split("@", 1)[0])
|
|
next_path = _safe_next_path(payload.get("next"))
|
|
ip_address = extract_remote_ip(request)
|
|
|
|
try:
|
|
account = _ensure_account(email=email, name=name, ip_address=ip_address)
|
|
_ensure_default_membership(account.id)
|
|
tokens = application_services().accounts.lifecycle.login(account.id, ip_address=ip_address)
|
|
except Exception:
|
|
logger.exception("gsrea sso provision failed for %s", email)
|
|
return _signin_error("免登开通失败,请联系管理员")
|
|
|
|
target = f"{_console_web_url()}{next_path}"
|
|
return _redirect_with_session(tokens, target)
|