supabase
Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...
auth-provider
认证提供商统一接口,支持 Supabase Auth、Clerk、Firebase Auth 等主流认证服务。 提供用户注册、登录、OAuth、会话管理、权限验证等功能。
Full skill instructions
统一的认证接口,支持主流认证服务,让 Agent 系统快速实现用户认证。
| 提供商 | 类型 | 免费额度 | 特点 |
|---|---|---|---|
| Supabase Auth | OSS | 50k MAU | RLS 统合、PostgreSQL 一体 |
| Clerk | 商用 | 10k MAU | 最佳 DX、预构建 UI |
| Firebase Auth | 商用 | 50k MAU | Google 生态、多平台 |
| Auth0 | 商用 | 7.5k MAU | 企业级、SAML/LDAP |
from agentflow.skills.builtin.auth_provider import AuthProvider, SupabaseAuthConfig
# 配置
config = SupabaseAuthConfig(
url="https://xxx.supabase.co",
anon_key="eyJ...",
jwt_secret="your-jwt-secret", # 用于验证 JWT
)
# 初始化
auth = AuthProvider(provider="supabase", config=config)
# 注册
user = await auth.sign_up(
email="[email protected]",
password="secure_password_123",
metadata={"name": "Test User"},
)
# 登录
session = await auth.sign_in(
email="[email protected]",
password="secure_password_123",
)
print(f"访问令牌: {session.access_token}")
print(f"用户 ID: {session.user.id}")
# OAuth 登录
oauth_url = await auth.sign_in_with_oauth(
provider="google",
redirect_to="https://myapp.com/auth/callback",
)
print(f"重定向用户到: {oauth_url}")
from agentflow.skills.builtin.auth_provider import AuthProvider, ClerkConfig
config = ClerkConfig(
secret_key="sk_test_...",
publishable_key="pk_test_...",
)
auth = AuthProvider(provider="clerk", config=config)
# 验证会话令牌
user = await auth.verify_session(token="sess_xxx")
# 获取用户信息
user_info = await auth.get_user(user_id="user_xxx")
# 邮箱密码注册
user = await auth.sign_up(
email="[email protected]",
password="secure_password",
metadata={
"name": "John Doe",
"role": "user",
},
email_confirm=True, # 需要邮箱确认
)
# 手机号注册(需要配置 SMS 服务)
user = await auth.sign_up_with_phone(
phone="+81901234567",
password="secure_password",
)
# 邮箱密码登录
session = await auth.sign_in(
email="[email protected]",
password="secure_password",
)
# Magic Link 登录(无密码)
await auth.sign_in_with_magic_link(
email="[email protected]",
redirect_to="https://myapp.com/auth/callback",
)
# OTP 登录
await auth.sign_in_with_otp(
email="[email protected]", # 或 phone="+81901234567"
)
# 用户收到验证码后
session = await auth.verify_otp(
email="[email protected]",
token="123456",
type="email",
)
# 登出当前设备
await auth.sign_out()
# 登出所有设备
await auth.sign_out(scope="global")
# 发起 OAuth 登录
oauth_url = await auth.sign_in_with_oauth(
provider="google",
redirect_to="https://myapp.com/auth/callback",
scopes=["email", "profile"],
)
# 处理回调
session = await auth.handle_oauth_callback(
code="auth_code_from_callback",
state="state_from_callback",
)
# iOS 应用需要支持 Apple 登录
oauth_url = await auth.sign_in_with_oauth(
provider="apple",
redirect_to="https://myapp.com/auth/callback",
)
# 获取当前会话
session = await auth.get_session()
if session:
print(f"用户: {session.user.email}")
print(f"过期时间: {session.expires_at}")
else:
print("未登录")
# 刷新访问令牌
new_session = await auth.refresh_session(
refresh_token=session.refresh_token,
)
# 验证并解析 JWT
payload = await auth.verify_jwt(
token=request.headers.get("Authorization").replace("Bearer ", ""),
)
user_id = payload.get("sub")
email = payload.get("email")
# 获取当前用户
user = await auth.get_current_user()
# 获取指定用户(需要管理员权限)
user = await auth.get_user(user_id="user_xxx")
# 更新用户信息
await auth.update_user(
user_id="user_xxx",
data={
"name": "New Name",
"avatar_url": "https://...",
},
)
# 更新密码
await auth.update_password(
current_password="old_password",
new_password="new_password",
)
# 删除用户(需要管理员权限)
await auth.delete_user(user_id="user_xxx")
# 发送重置邮件
await auth.reset_password_for_email(
email="[email protected]",
redirect_to="https://myapp.com/auth/reset-password",
)
# 更新密码(在重置页面)
await auth.update_password_with_token(
token="reset_token",
new_password="new_secure_password",
)
# 生成 TOTP 密钥
totp = await auth.enroll_mfa(
factor_type="totp",
friendly_name="Authenticator App",
)
print(f"二维码 URI: {totp.qr_code}")
print(f"密钥: {totp.secret}")
# 验证并激活
await auth.verify_mfa(
factor_id=totp.id,
code="123456", # 来自 Authenticator App
)
# 登录时需要 MFA
session = await auth.sign_in(email, password)
if session.mfa_required:
# 发起 MFA 挑战
challenge = await auth.create_mfa_challenge(
factor_id=session.mfa_factors[0].id,
)
# 验证 MFA
session = await auth.verify_mfa_challenge(
challenge_id=challenge.id,
code="123456",
)
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer
app = FastAPI()
security = HTTPBearer()
async def get_current_user(token: str = Depends(security)):
"""验证并获取当前用户."""
try:
payload = await auth.verify_jwt(token.credentials)
return payload
except AuthError:
raise HTTPException(401, "Invalid token")
@app.get("/protected")
async def protected_route(user: dict = Depends(get_current_user)):
return {"message": f"Hello {user['email']}"}
# 角色检查
async def require_admin(user: dict = Depends(get_current_user)):
if user.get("role") != "admin":
raise HTTPException(403, "Admin required")
return user
@app.delete("/admin/users/{user_id}")
async def delete_user(user_id: str, admin: dict = Depends(require_admin)):
await auth.delete_user(user_id)
return {"deleted": user_id}
// middleware.ts
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(req: NextRequest) {
const res = NextResponse.next()
const supabase = createMiddlewareClient({ req, res })
const { data: { session } } = await supabase.auth.getSession()
if (!session && req.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', req.url))
}
return res
}
from agentflow.skills import SkillEngine
engine = SkillEngine()
@engine.tool("authenticate_user")
async def authenticate_user(email: str, password: str) -> dict:
"""用户登录"""
try:
session = await auth.sign_in(email=email, password=password)
return {
"success": True,
"user_id": session.user.id,
"access_token": session.access_token,
}
except AuthError as e:
return {"success": False, "error": str(e)}
@engine.tool("verify_token")
async def verify_token(token: str) -> dict:
"""验证访问令牌"""
try:
payload = await auth.verify_jwt(token)
return {
"valid": True,
"user_id": payload.get("sub"),
"email": payload.get("email"),
}
except AuthError:
return {"valid": False}
@engine.tool("get_user_info")
async def get_user_info(user_id: str) -> dict:
"""获取用户信息"""
user = await auth.get_user(user_id)
return {
"id": user.id,
"email": user.email,
"name": user.metadata.get("name"),
"created_at": user.created_at.isoformat(),
}
import os
config = SupabaseAuthConfig(
url=os.environ["SUPABASE_URL"],
anon_key=os.environ["SUPABASE_ANON_KEY"],
jwt_secret=os.environ["SUPABASE_JWT_SECRET"],
)
from agentflow.skills.builtin.auth_provider import (
AuthError,
InvalidCredentialsError,
UserNotFoundError,
TokenExpiredError,
EmailNotConfirmedError,
)
try:
session = await auth.sign_in(email, password)
except InvalidCredentialsError:
return {"error": "邮箱或密码错误"}
except EmailNotConfirmedError:
return {"error": "请先确认邮箱"}
except TokenExpiredError:
return {"error": "会话已过期,请重新登录"}
except AuthError as e:
logger.error(f"认证错误: {e}")
return {"error": "认证失败"}
# 启用 RLS(Supabase)
# 在数据库中配置 RLS 策略确保数据隔离
# JWT 配置
config = SupabaseAuthConfig(
...
jwt_expiry=3600, # 1 小时过期
refresh_token_expiry=604800, # 7 天
)
# 密码策略
await auth.sign_up(
email=email,
password=password,
password_options={
"min_length": 12,
"require_uppercase": True,
"require_number": True,
"require_special": True,
},
)
| 场景 | 推荐 | 理由 |
|---|---|---|
| 使用 PostgreSQL | Supabase Auth | RLS 集成、数据库一体 |
| 最佳开发体验 | Clerk | 预构建 UI、组织管理 |
| Google 生态 | Firebase Auth | Firestore/FCM 集成 |
| 企业 SSO | Auth0 | SAML/LDAP/Active Directory |
Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...
Comprehensive guides and best practices for Neon Serverless Postgres, covering setup, connection methods, authentication, and platform APIs.
Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.
A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.
Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.
Complete Better Auth server and client setup with database adapters, session management, plugins, and security configuration.
Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".
Complete Cloudflare platform integration with decision trees for compute, storage, AI, networking, security, and infrastructure-as-code.
Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.
Send, read, and manage Gmail messages, drafts, labels, and account settings.
Comprehensive website auditing across 230+ rules in 21 categories including SEO, performance, security, and accessibility.
Shared authentication, CLI syntax, and output formatting patterns for gws Google Workspace commands.
Discover your celebrity doppelgänger with StarByFace!
GeoSpy: Pricing, Features, FAQs, and Alternatives for AI Teams
Detect AI-generated voices to protect against audio fraud.
Ensure Your Content's Originality with AI Plagiarism Checker
Upscale images by 400% without quality loss
Protect your social media from copyright disputes
Accurately Detect AI-Generated Content with TheChecker.AI
Chrome extension that detects and flags AI-generated content