"""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), }