@choiceform/shared-auth

v0.1.17

Published

Shared authentication package for Choiceform projects

Readme

@choiceform/shared-auth

共享认证包 - 基于 Better Auth 的统一认证解决方案

功能特性

  • Better Auth 集成(OAuth、Magic Link)
  • Legend State 状态管理
  • 自动伴生团队设置
  • Token 自动管理
  • 完整 TypeScript 类型支持
  • 预配置 API 客户端

安装

pnpm add @choiceform/shared-auth

环境变量

VITE_ONEAUTH_BASE_URL=https://oneauth.choiceform.io

快速开始

初始化

import { initAuth } from "@choiceform/shared-auth"

export const auth = initAuth({
  baseURL: import.meta.env.VITE_ONEAUTH_BASE_URL,
  tokenStorageKey: "auth-token",
})

在应用中使用

import { use$ } from "@legendapp/state/react"
import { auth } from "./lib/auth"

function App() {
  const { isAuthenticated, user } = use$(auth.authStore)

  if (!isAuthenticated) {
    return <SignInPage />
  }

  return <MainApp user={user} />
}

登录

// OAuth 登录
const handleOAuthSignIn = async () => {
  const callbackURL = new URL("/dashboard", window.location.origin)
  const newUserCallbackURL = new URL("/dashboard?isNew=true", window.location.origin)
  
  await auth.authActions.signIn(
    "github",
    callbackURL.toString(),
    newUserCallbackURL.toString()
  )
}

// Magic Link 登录
const handleMagicLink = async (email: string) => {
  const callbackURL = new URL("/dashboard", window.location.origin)
  
  await auth.authActions.signInWithMagicLink(
    email,
    callbackURL.toString()
  )
}

认证状态同步

新用户登录后,使用 setupCompanionTeam 设置伴生组织和团队:

import { setupCompanionTeam } from "@choiceform/shared-auth"

// 在认证成功后调用
setupCompanionTeam(auth, token, {
  isNewUser: searchParams.get("isNew") === "true",
  onComplete: () => {
    // 刷新 session
  },
})

API

initAuth(config)

快速初始化(使用默认配置)。

| 参数 | 类型 | 说明 | |------|------|------| | baseURL | string | OneAuth API 地址 | | tokenStorageKey | string | localStorage key(默认 auth-token) | | plugins | BetterAuthPlugin[] | Better Auth 插件 |

createAuth(config)

创建认证实例(完整配置)。

AuthInstance

| 属性 | 说明 | |------|------| | authStore | Legend State store | | authActions | 认证操作(signIn, signOut 等) | | authApi | 认证 API | | organizationApi | 组织 API | | teamApi | 团队 API | | tokenStorage | Token 存储工具 |

工具方法

// 获取用户
const user = auth.getCurrentUser()
const userId = auth.getCurrentUserId()

// 认证状态
const authenticated = auth.isAuthenticated()
const loading = auth.isLoading()
const loaded = auth.isLoaded()

// 等待认证完成
await auth.waitForAuth()

// Token
const token = auth.getAuthTokenSync()
const headers = auth.getAuthHeadersSync()

类型

import type {
  SessionUser,
  AuthState,
  AuthConfig,
  Organization,
  Team,
  Member,
} from "@choiceform/shared-auth"

SessionUser

interface SessionUser {
  id: string
  email: string
  name: string
  image?: string
  metadata?: { color?: string }
  inherentOrganizationId?: string  // 伴生组织
  inherentTeamId?: string          // 伴生团队
  activeOrganizationId?: string
  activeTeamId?: string
  // ...
}

响应式状态

import { use$ } from "@legendapp/state/react"
import { auth } from "./lib/auth"

function Profile() {
  const user = use$(auth.authStore.user)
  const loading = use$(auth.authStore.loading)

  if (loading) return <Loading />
  if (!user) return <SignIn />

  return <div>Hello, {user.name}</div>
}

更新日志

v0.2.0

  • 服务器地址更换为 https://oneauth.choiceform.io
  • 伴生组织/团队改从 session 获取(inherentOrganizationIdinherentTeamId
  • 新增 onboard API、Magic Link 支持
  • 移除 UI 组件(AuthSyncProtectedRouteSignInPage),由业务端实现
  • 代码清理和优化

v0.1.x

  • 初始版本

License

MIT