认证服务 (Auth)
@ticos/auth 是 Ticos 平台提供的通用认证包,旨在为基于 Next.js 和 Supabase 构建的应用提供开箱即用的登录、注册和会话管理功能。
- 多方案登录:支持传统的邮箱密码认证以及 GitHub 等 OAuth 登录。
- 全栈兼容:同时提供客户端和服务端(Middleware/Server Actions)的 Supabase 客户端创建工具。
- 预置组件:包含符合 Ticos 设计规范的登录页、注册页和认证表单。
- 会话管理:自动处理 Token 存储、刷新以及路由保护。
在你的项目中安装该 Workspace 包:
pnpm add @ticos/auth1. 配置环境变量
Section titled “1. 配置环境变量”在使用 Auth 包的项目根目录 .env.local 中配置以下信息:
NEXT_PUBLIC_SUPABASE_URL=your-supabase-urlNEXT_PUBLIC_SUPABASE_ANON_KEY=your-supabase-anon-key2. 集成登录页面
Section titled “2. 集成登录页面”你可以直接使用预构成的 LoginForm 组件来快速搭建登录界面:
import { LoginForm } from '@ticos/auth';
export default function LoginPage() { return ( <div className="flex min-h-screen items-center justify-center"> <LoginForm redirect="/dashboard" logoComponent={<Logo className="h-12 w-12" />} /> </div> );}3. 在中间件中保护路由
Section titled “3. 在中间件中保护路由”利用 createServerSupabaseClient 在 Next.js Middleware 中实现路由守卫:
import { createServerSupabaseClient } from '@ticos/auth';import { NextResponse, type NextRequest } from 'next/server';
export async function middleware(req: NextRequest) { const supabase = await createServerSupabaseClient(); const { data: { session } } = await supabase.auth.getSession();
if (!session && !req.nextUrl.pathname.startsWith('/auth')) { return NextResponse.redirect(new URL('/auth/login', req.url)); }
return NextResponse.next();}API 参考
Section titled “API 参考”signUp(email, password): 注册新用户。signIn(email, password): 邮箱密码登录。signOut(): 退出当前会话。getUser(): 获取当前已认证的用户信息。isAuthenticated(): 快速检查当前是否处于登录状态。
createClient(): 在浏览器端创建 Supabase 客户端。createServerSupabaseClient(): 在服务端环境(Server Components/API Routes)创建适配 SSR 的 Supabase 客户端。
- UI 一致性:优先使用
LoginForm和RegisterPage组件,以确保应用与 Ticos 主站的交互逻辑和视觉风格一致。 - 服务端优先:对于敏感操作,始终通过
getUser()在服务端校验用户身份,不要仅依赖客户端状态。