Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

16.4 KB
Raw Blame
import { post, get, put } from '@/utils/request'
import i18n from '@/i18n'

const t = (key: string) => i18n.global.t(key)

// 用户登录接口
export interface LoginRequest {
  email: string
  password: string
}

export interface LoginResponse {
  success: boolean
  message?: string
  user?: {
    id: string
    username: string
    email: string
    avatar?: string
    tenant_id: number
    can_access_all_tenants?: boolean
    is_system_admin?: boolean
    is_active: boolean
    created_at: string
    updated_at: string
  }
  tenant?: {
    id: number
    name: string
    description: string
    status: string
    business: string
    storage_quota: number
    storage_used: number
    created_at: string
    updated_at: string
  } | null
  // active_tenant mirrors `tenant` for endpoints that distinguish home
  // tenant from current tenant (e.g. /auth/register-by-invite). Only
  // one of `tenant` / `active_tenant` is populated by any given endpoint.
  active_tenant?: {
    id: number
    name: string
    description?: string
    status?: string
    business?: string
    storage_quota?: number
    storage_used?: number
    created_at?: string
    updated_at?: string
  } | null
  memberships?: MembershipInfo[]
  token?: string
  refresh_token?: string
}

export interface OIDCAuthURLResponse {
  success: boolean
  authorization_url?: string
  state?: string
  message?: string
}

export interface OIDCConfigResponse {
  success: boolean
  enabled: boolean
  provider_display_name?: string
  message?: string
}

// 用户注册接口
export interface RegisterRequest {
  username: string
  email: string
  password: string
}

export interface RegisterResponse {
  success: boolean
  message?: string
  data?: {
    user: {
      id: string
      username: string
      email: string
    }
    tenant: {
      id: string
      name: string
    }
  }
}

// 用户偏好(与后端 types.UserPreferences 对齐,字段可选 = 没显式设置过)。
// 新加 key 时记得:后端 service.UpdateUserPreferences 也要在 merge 分支里
// 处理;前端调用方按需读 / 默认值降级。
export interface UserPreferences {
  browser_search_instructions?: string | null
  // last_active_tenant_id 持久化「刷新 / 换设备 / 重新登录后回到上次的空间」
  // 偏好;后端在 Login / RefreshToken 时校验 membership 有效后才会沿用,
  // 否则回退到 home 并清掉这个字段。传 0 给 PATCH 表示「清除偏好」。
  last_active_tenant_id?: number | null
  // oidc_only_login 为 true 表示账号由 OIDC 自动开通且用户尚未设置已知密码。
  oidc_only_login?: boolean
  // gallery 记录图库的个人状态:搜索激活模式与逐字段开/关(按属性 ID)。
  // 每次变更整体覆盖该块;后端会校验 mode 与 status 取值。
  gallery?: {
    mode?: 'all' | 'custom'
    status?: Record<string, string>
  }
}

// 用户信息接口
export interface UserInfo {
  id: string
  username: string
  email: string
  avatar?: string
  tenant_id: string
  can_access_all_tenants?: boolean
  preferences?: UserPreferences
  is_system_admin?: boolean
  created_at: string
  updated_at: string
}

/**
 * 把后端返回的 user JSON 规范化成前端 UserInfo。
 *
 * 历史上有 4 处独立的 setUser 调用(Login、autoSetup、token rehydrate、
 * /auth/me 主动 refresh)各自手写字段白名单,每加一个 user 字段都要在
 * 4 处同步——否则该字段就被悄悄过滤掉。is_system_admin 上线时就因为
 * 漏拷一处而看不到「系统管理」入口;这个工厂存在的目的就是杜绝同类
 * 漏拷再发生。**新增 user 字段请只改这里**。
 *
 * fallbackTenantId 是 tenant_id 缺失时的兜底来源——
 *   - autoSetup 响应顶层有 tenant.id,但 user 对象上没有 tenant_id
 *   - /auth/me 偶发只返回 user 不带 tenant 时也走兜底
 * 调用方按需传入;不传则保持空字符串(与历史行为一致)。
 *
 * 字段读取统一走 `=== true` 而不是 `|| false`,对偶发非 boolean
 * 类型(后端某天传 1/0 或字符串)做严格收敛,避免把 truthy 字符串
 * 误判为权限通过。
 */
export function userInfoFromApi(
  u: any,
  fallbackTenantId?: string | number | null,
): UserInfo {
  const rawTenantId =
    u?.tenant_id !== undefined && u?.tenant_id !== null && u.tenant_id !== ''
      ? u.tenant_id
      : fallbackTenantId ?? ''
  const tid = Number(rawTenantId) > 0 ? rawTenantId : ''
  return {
    id: u?.id || '',
    username: u?.username || '',
    email: u?.email || '',
    avatar: u?.avatar,
    tenant_id: String(tid) || '',
    can_access_all_tenants: u?.can_access_all_tenants === true,
    is_system_admin: u?.is_system_admin === true,
    preferences: u?.preferences,
    created_at: u?.created_at || new Date().toISOString(),
    updated_at: u?.updated_at || new Date().toISOString(),
  }
}

// 空间信息接口
export interface TenantInfo {
  id: string
  name: string
  description?: string
  status?: string
  business?: string
  owner_id: string
  storage_quota?: number
  storage_used?: number
  created_at: string
  updated_at: string
  knowledge_bases?: KnowledgeBaseInfo[]
}

// 知识库信息接口
export interface KnowledgeBaseInfo {
  id: string
  name: string
  description: string
  tenant_id: string
  // creator_id is the user id of whoever originally created the KB.
  // Set by PR 5 of the multi-tenant RBAC series; nullable for legacy
  // KBs created before that migration backfilled the column.
  creator_id?: string
  // creator_name 由后端 list 接口批量回填(username 优先,退化到 email),
  // 仅用于列表卡片来源徽章;缺失代表无法解析(已删除 / 老数据)。
  creator_name?: string
  created_at: string
  updated_at: string
  document_count?: number
  chunk_count?: number
}

// 模型信息接口
export interface ModelInfo {
  id: string
  name: string
  type: string
  source: string
  description?: string
  is_default?: boolean
  created_at: string
  updated_at: string
}

/**
 * 用户登录
 */
export async function login(data: LoginRequest): Promise<LoginResponse> {
  try {
    const response = await post('/api/v1/auth/login', data)
    return response as unknown as LoginResponse
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.loginFailed')
    }
  }
}

/**
 * 获取 OIDC 登录跳转地址
 */
export async function getOIDCAuthorizationURL(redirectURI: string): Promise<OIDCAuthURLResponse> {
  try {
    const response = await get(`/api/v1/auth/oidc/url?redirect_uri=${encodeURIComponent(redirectURI)}`)
    return response as unknown as OIDCAuthURLResponse
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.loginFailed')
    }
  }
}

/**
 * 获取 OIDC 登录配置
 */
export async function getOIDCConfig(): Promise<OIDCConfigResponse> {
  try {
    const response = await get('/api/v1/auth/oidc/config')
    return response as unknown as OIDCConfigResponse
  } catch (error: any) {
    return {
      success: false,
      enabled: false,
      message: error.message || t('error.auth.loginFailed')
    }
  }
}

/**
 * 获取认证配置(仅返回前端渲染需要的公开字段,例如注册模式)。
 *
 * 后端通过 `auth.registration_mode` 控制是否允许自助注册:
 *   - "self_serve"  保留现有自助注册入口(默认)
 *   - "invite_register" 仅持有效邀请链接可注册
 *   - "invite_only" 禁止注册,已有账号仍可接受邀请
 *
 * 失败时隐藏注册入口,避免误展示不允许的注册流程。
 */
export interface AuthConfigResponse {
  success: boolean
  registration_mode: 'self_serve' | 'invite_register' | 'invite_only' | string
  complex_password_enabled: boolean
}

export async function getAuthConfig(): Promise<AuthConfigResponse> {
  try {
    const response = await get('/api/v1/auth/config')
    return response as unknown as AuthConfigResponse
  } catch {
    return { success: false, registration_mode: '', complex_password_enabled: false }
  }
}

/**
 * 用户注册
 */
export async function register(data: RegisterRequest): Promise<RegisterResponse> {
  try {
    const response = await post('/api/v1/auth/register', data)
    return response as unknown as RegisterResponse
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.registerFailed')
    }
  }
}

/**
 * Lite 版自动初始化(创建默认用户/空间 + 签发令牌)
 */
let autoSetupPromise: Promise<LoginResponse> | null = null

export function autoSetup(): Promise<LoginResponse> {
  if (autoSetupPromise) return autoSetupPromise

  const request = (async () => {
    try {
      const nativeApp = (window as any).go?.main?.App
      if (!nativeApp?.GetAutoSetupToken) return { success: false, message: 'Desktop authentication required' }
      const token = await nativeApp.GetAutoSetupToken()
      const response = await post('/api/v1/auth/auto-setup', {}, {
        headers: { 'X-WeKnora-Desktop-Token': token },
      })
      return response as unknown as LoginResponse
    } catch (error: any) {
      return {
        success: false,
        message: error.message || 'Auto-setup unavailable'
      }
    }
  })()

  autoSetupPromise = request
  void request.then(
    () => { if (autoSetupPromise === request) autoSetupPromise = null },
    () => { if (autoSetupPromise === request) autoSetupPromise = null },
  )
  return request
}

/**
 * Membership row returned alongside /auth/me. Mirrors the LoginResponse
 * shape so the frontend can refresh `currentTenantRole` on every page
 * load — without it, role changes after login (e.g. an Owner demoting
 * us in a peer tenant) stay invisible until the user logs out and back
 * in.
 */
export interface MembershipInfo {
  tenant_id: number
  tenant_name?: string
  role: string
}

/**
 * 获取当前用户信息
 */
export interface AuthCapabilities {
  can_create_tenant: boolean
  auto_accept_invitation: boolean
}

export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities; preference_defaults?: { browser_search_instructions: string } }; message?: string }> {
  try {
    const response = await get('/api/v1/auth/me')
    return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[]; tenant_required?: boolean; capabilities?: AuthCapabilities; preference_defaults?: { browser_search_instructions: string } }; message?: string }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.getUserFailed')
    }
  }
}

/**
 * 更新当前用户的偏好设置(PATCH 语义:只发要改的字段,后端只覆盖发了的 key,
 * 其它 key 保持不变)。后端会返回更新后的完整 preferences 对象。
 */
export async function updateMyPreferences(
  patch: Partial<UserPreferences>,
): Promise<{ success: boolean; data?: UserPreferences; message?: string }> {
  try {
    const response = await put('/api/v1/auth/me/preferences', patch)
    return response as unknown as { success: boolean; data?: UserPreferences; message?: string }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.updatePreferencesFailed'),
    }
  }
}

/**
 * 获取当前空间信息
 */
export async function getCurrentTenant(): Promise<{ success: boolean; data?: TenantInfo; message?: string }> {
  try {
    const response = await get('/api/v1/auth/tenant')
    return response as unknown as { success: boolean; data?: TenantInfo; message?: string }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.getTenantFailed')
    }
  }
}

/**
 * 刷新Token
 */
export async function refreshToken(refreshToken: string): Promise<{ success: boolean; data?: { token: string; refreshToken: string }; message?: string }> {
  try {
    const response: any = await post('/api/v1/auth/refresh', { refreshToken })
    if (response && response.success) {
      if (response.access_token || response.refresh_token) {
        return {
          success: true,
          data: {
            token: response.access_token,
            refreshToken: response.refresh_token,
          }
        }
      }
    }

    // 其他情况直接返回原始消息
    return {
      success: false,
      message: response?.message || t('error.auth.refreshTokenFailed')
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.refreshTokenFailed')
    }
  }
}

/**
 * 用户登出
 */
export async function logout(): Promise<{ success: boolean; message?: string }> {
  try {
    await post('/api/v1/auth/logout', {})
    return {
      success: true
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.message || t('error.auth.logoutFailed')
    }
  }
}

export interface ChangePasswordRequest {
  old_password: string
  new_password: string
}

/** Map change-password API failures to localized UI strings. */
export function resolveChangePasswordError(error: any): string {
  const details =
    typeof error?.error?.details === 'string'
      ? error.error.details
      : typeof error?.details === 'string'
        ? error.details
        : ''
  switch (details) {
    case 'invalid_old_password':
      return t('userProfile.changePassword.failed')
    case 'password_policy':
      return t('userProfile.changePassword.policyFailed')
    case 'same_password':
      return t('userProfile.changePassword.sameAsCurrent')
    default:
      return error?.message || t('userProfile.changePassword.failed')
  }
}

/**
 * Self-service password rotation. On success the backend revokes every
 * outstanding session for the caller, so the client should clear local
 * auth state and send the user back to /login.
 */
export async function changePassword(
  data: ChangePasswordRequest,
): Promise<{ success: boolean; message?: string }> {
  try {
    const response = await post('/api/v1/auth/change-password', data)
    return response as unknown as { success: boolean; message?: string }
  } catch (error: any) {
    return {
      success: false,
      message: resolveChangePasswordError(error),
    }
  }
}

/**
 * 验证Token有效性
 */
export async function validateToken(): Promise<{ success: boolean; valid?: boolean; message?: string }> {
  try {
    const response = await get('/api/v1/auth/validate')
    return response as unknown as { success: boolean; valid?: boolean; message?: string }
  } catch (error: any) {
    return {
      success: false,
      valid: false,
      message: error.message || t('error.auth.validateTokenFailed')
    }
  }
}





// ---- share-link registration --------------------------------------------

// InviteLookup is the public projection of a share-link row used by
// /register?token=xxx — enough to render the registration page header
// ("X invited you to Y") without leaking sensitive inviter fields.
export interface InviteLookup {
  tenant_id: number
  tenant_name?: string
  role: string
  expires_at: string
}

export interface InviteLookupResponse {
  success: boolean
  data?: InviteLookup
  message?: string
}

export interface RegisterByInviteRequest {
  token: string
  email: string
  username: string
  password: string
}

/**
 * Resolve a share-link token (no auth) into the context the
 * registration page needs (tenant name, role, expiry). Returns 410
 * when the link is invalid / revoked / expired.
 *
 * Uses POST + body (rather than GET + path) so the plaintext token
 * never appears in access logs, browser history, or tracing spans.
 */
export async function getInvitationByToken(token: string): Promise<InviteLookupResponse> {
  try {
    const response = await post(`/api/v1/auth/invitations/lookup`, { token })
    return response as unknown as InviteLookupResponse
  } catch (error: any) {
    return { success: false, message: error.message || '' }
  }
}

/**
 * Complete registration via a share-link token. The invitee supplies
 * their own email — the token is the authorisation, not an identity
 * lock.
 */
export async function registerByInvite(data: RegisterByInviteRequest): Promise<LoginResponse> {
  try {
    const response = await post('/api/v1/auth/register-by-invite', data)
    return response as unknown as LoginResponse
  } catch (error: any) {
    return { success: false, message: error.message || t('error.auth.registerFailed') }
  }
}