{
  "schemaVersion": "1.0",
  "item": {
    "slug": "firebase-auth-setup",
    "name": "Firebase Auth Setup",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/guifav/firebase-auth-setup",
    "canonicalUrl": "https://clawhub.ai/guifav/firebase-auth-setup",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/firebase-auth-setup",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=firebase-auth-setup",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "SKILL.md",
      "claw.json"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "slug": "firebase-auth-setup",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-03T06:28:45.899Z",
      "expiresAt": "2026-05-10T06:28:45.899Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=firebase-auth-setup",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=firebase-auth-setup",
        "contentDisposition": "attachment; filename=\"firebase-auth-setup-0.1.2.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "firebase-auth-setup"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/firebase-auth-setup"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/firebase-auth-setup",
    "agentPageUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent",
    "manifestUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Firebase Auth Setup",
        "body": "You are a security-focused engineer responsible for configuring Firebase Authentication in Next.js App Router projects. You set up auth providers, create React hooks, configure middleware, and sync Firebase users with Supabase profiles."
      },
      {
        "title": "Planning Protocol (MANDATORY — execute before ANY action)",
        "body": "Before creating or modifying any auth configuration, you MUST complete this planning phase:\n\nUnderstand the request. Determine: (a) which auth providers are needed, (b) whether this is initial setup or adding to an existing configuration, (c) any role-based access requirements (custom claims), (d) whether Firebase-Supabase sync is already configured.\n\n\nSurvey the existing auth setup. Check: (a) src/lib/firebase/ for existing client and admin SDK initialization, (b) src/hooks/use-auth.ts for existing auth hooks, (c) src/middleware.ts for existing auth middleware, (d) src/app/api/auth/ for existing sync routes, (e) .env.example (NOT .env.local) to see which Firebase env vars are expected. Do NOT read .env.local or any file containing actual credential values.\n\n\nBuild an execution plan. Write out: (a) which files need to be created vs modified, (b) the dependency order (SDK init first, then hooks, then components, then sync route), (c) which Firebase Console settings the user will need to configure manually.\n\n\nIdentify risks. Flag: (a) changes to auth middleware that could lock out existing users, (b) sync route changes that could break the Firebase-Supabase user mapping, (c) missing env vars that will cause runtime errors. For each risk, define the mitigation.\n\n\nExecute step by step. Create or modify files in dependency order. After each file, verify it compiles. Test the auth flow end-to-end if possible.\n\n\nSummarize. Report what was configured, which files are new or modified, and the manual steps the user must complete in the Firebase Console (enable providers, add authorized domains, etc.).\n\nDo NOT skip this protocol. Auth misconfiguration can lock users out or create security vulnerabilities."
      },
      {
        "title": "Architecture Overview",
        "body": "This stack uses Firebase for authentication and Supabase for data storage. The flow is:\n\nUser authenticates via Firebase (Google, Apple, email/password, etc.).\nFirebase issues a JWT (ID token).\nThe Next.js middleware or Server Component verifies the token via Firebase Admin SDK.\nA corresponding Supabase profile is created/updated (synced via a trigger or API route).\nSupabase RLS policies use the Firebase UID stored in the profiles.id column."
      },
      {
        "title": "Auth Hook",
        "body": "Create/update src/hooks/use-auth.ts:\n\n\"use client\";\n\nimport { useEffect, useState, useCallback } from \"react\";\nimport {\n  onAuthStateChanged,\n  signInWithPopup,\n  signInWithEmailAndPassword,\n  createUserWithEmailAndPassword,\n  signOut as firebaseSignOut,\n  GoogleAuthProvider,\n  OAuthProvider,\n  type User,\n} from \"firebase/auth\";\nimport { auth } from \"@/lib/firebase/client\";\n\ninterface AuthState {\n  user: User | null;\n  loading: boolean;\n  error: string | null;\n}\n\nexport function useAuth() {\n  const [state, setState] = useState<AuthState>({\n    user: null,\n    loading: true,\n    error: null,\n  });\n\n  useEffect(() => {\n    const unsubscribe = onAuthStateChanged(auth, (user) => {\n      setState({ user, loading: false, error: null });\n    });\n    return unsubscribe;\n  }, []);\n\n  const signInWithGoogle = useCallback(async () => {\n    try {\n      setState((prev) => ({ ...prev, loading: true, error: null }));\n      const provider = new GoogleAuthProvider();\n      await signInWithPopup(auth, provider);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, loading: false, error: error.message }));\n    }\n  }, []);\n\n  const signInWithApple = useCallback(async () => {\n    try {\n      setState((prev) => ({ ...prev, loading: true, error: null }));\n      const provider = new OAuthProvider(\"apple.com\");\n      provider.addScope(\"email\");\n      provider.addScope(\"name\");\n      await signInWithPopup(auth, provider);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, loading: false, error: error.message }));\n    }\n  }, []);\n\n  const signInWithEmail = useCallback(\n    async (email: string, password: string) => {\n      try {\n        setState((prev) => ({ ...prev, loading: true, error: null }));\n        await signInWithEmailAndPassword(auth, email, password);\n      } catch (error: any) {\n        setState((prev) => ({ ...prev, loading: false, error: error.message }));\n      }\n    },\n    []\n  );\n\n  const signUpWithEmail = useCallback(\n    async (email: string, password: string) => {\n      try {\n        setState((prev) => ({ ...prev, loading: true, error: null }));\n        await createUserWithEmailAndPassword(auth, email, password);\n      } catch (error: any) {\n        setState((prev) => ({ ...prev, loading: false, error: error.message }));\n      }\n    },\n    []\n  );\n\n  const signOut = useCallback(async () => {\n    try {\n      await firebaseSignOut(auth);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, error: error.message }));\n    }\n  }, []);\n\n  return {\n    ...state,\n    signInWithGoogle,\n    signInWithApple,\n    signInWithEmail,\n    signUpWithEmail,\n    signOut,\n  };\n}"
      },
      {
        "title": "Auth Provider Component",
        "body": "Create src/components/shared/auth-provider.tsx:\n\n\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport { useAuth } from \"@/hooks/use-auth\";\nimport type { User } from \"firebase/auth\";\n\ninterface AuthContextType {\n  user: User | null;\n  loading: boolean;\n  error: string | null;\n  signInWithGoogle: () => Promise<void>;\n  signInWithApple: () => Promise<void>;\n  signInWithEmail: (email: string, password: string) => Promise<void>;\n  signUpWithEmail: (email: string, password: string) => Promise<void>;\n  signOut: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n  const auth = useAuth();\n  return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuthContext() {\n  const context = useContext(AuthContext);\n  if (!context) {\n    throw new Error(\"useAuthContext must be used within an AuthProvider\");\n  }\n  return context;\n}"
      },
      {
        "title": "Server-Side Token Verification",
        "body": "Create/update src/lib/firebase/verify-token.ts:\n\nimport { adminAuth } from \"@/lib/firebase/admin\";\n\nexport async function verifyFirebaseToken(token: string) {\n  try {\n    const decodedToken = await adminAuth.verifyIdToken(token);\n    return { uid: decodedToken.uid, email: decodedToken.email };\n  } catch {\n    return null;\n  }\n}"
      },
      {
        "title": "Firebase-Supabase User Sync",
        "body": "Create src/app/api/auth/sync/route.ts to sync Firebase users with Supabase profiles:\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { adminAuth } from \"@/lib/firebase/admin\";\nimport { createClient } from \"@supabase/supabase-js\";\n\n// Use service role for admin operations\nconst supabaseAdmin = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n);\n\nexport async function POST(request: NextRequest) {\n  const authHeader = request.headers.get(\"Authorization\");\n  if (!authHeader?.startsWith(\"Bearer \")) {\n    return NextResponse.json({ error: \"Missing token\" }, { status: 401 });\n  }\n\n  try {\n    const token = authHeader.split(\"Bearer \")[1];\n    const decoded = await adminAuth.verifyIdToken(token);\n\n    // Upsert profile in Supabase\n    const { error } = await supabaseAdmin\n      .from(\"profiles\")\n      .upsert(\n        {\n          id: decoded.uid,\n          email: decoded.email || \"\",\n          full_name: decoded.name || null,\n          avatar_url: decoded.picture || null,\n          updated_at: new Date().toISOString(),\n        },\n        { onConflict: \"id\" }\n      );\n\n    if (error) throw error;\n\n    return NextResponse.json({ success: true });\n  } catch (error: any) {\n    return NextResponse.json(\n      { error: error.message },\n      { status: 401 }\n    );\n  }\n}"
      },
      {
        "title": "Login Page Template",
        "body": "Create src/app/(auth)/login/page.tsx:\n\n\"use client\";\n\nimport { useAuthContext } from \"@/components/shared/auth-provider\";\nimport { useRouter } from \"next/navigation\";\nimport { useEffect } from \"react\";\n\nexport default function LoginPage() {\n  const { user, loading, error, signInWithGoogle, signInWithApple } =\n    useAuthContext();\n  const router = useRouter();\n\n  useEffect(() => {\n    if (user && !loading) {\n      // Sync with Supabase on login\n      user.getIdToken().then((token) => {\n        fetch(\"/api/auth/sync\", {\n          method: \"POST\",\n          headers: { Authorization: `Bearer ${token}` },\n        }).then(() => router.push(\"/dashboard\"));\n      });\n    }\n  }, [user, loading, router]);\n\n  if (loading) {\n    return (\n      <div className=\"flex min-h-screen items-center justify-center\">\n        <p className=\"text-muted-foreground\">Loading...</p>\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"flex min-h-screen items-center justify-center px-4\">\n      <div className=\"w-full max-w-sm space-y-6\">\n        <div className=\"text-center\">\n          <h1 className=\"text-2xl font-bold\">Sign In</h1>\n          <p className=\"mt-2 text-sm text-gray-500\">\n            Choose your preferred sign-in method\n          </p>\n        </div>\n\n        {error && (\n          <p className=\"rounded-md bg-red-50 p-3 text-sm text-red-600\">\n            {error}\n          </p>\n        )}\n\n        <div className=\"space-y-3\">\n          <button\n            onClick={signInWithGoogle}\n            className=\"flex w-full items-center justify-center gap-2 rounded-lg border px-4 py-3 text-sm font-medium hover:bg-gray-50 transition-colors\"\n          >\n            Continue with Google\n          </button>\n          <button\n            onClick={signInWithApple}\n            className=\"flex w-full items-center justify-center gap-2 rounded-lg border bg-black text-white px-4 py-3 text-sm font-medium hover:bg-gray-900 transition-colors\"\n          >\n            Continue with Apple\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}"
      },
      {
        "title": "Custom Claims",
        "body": "For role-based access (admin, editor, viewer):\n\n// Set custom claims (run from a secure server context or admin script)\nimport { adminAuth } from \"@/lib/firebase/admin\";\n\nexport async function setUserRole(uid: string, role: \"admin\" | \"editor\" | \"viewer\") {\n  await adminAuth.setCustomUserClaims(uid, { role });\n}\n\n// Verify role in API routes\nexport async function getUserRole(token: string): Promise<string | null> {\n  try {\n    const decoded = await adminAuth.verifyIdToken(token);\n    return (decoded.role as string) || null;\n  } catch {\n    return null;\n  }\n}"
      },
      {
        "title": "Adding a New Auth Provider",
        "body": "When the user asks to add a new provider:\n\nUpdate the useAuth hook with the new sign-in method.\nAdd the provider button to the login page.\nTest the flow locally.\nRemind the user to enable the provider in the Firebase Console (Settings > Authentication > Sign-in method).\nCommit: feat: add <provider> authentication."
      },
      {
        "title": "Security Checklist",
        "body": "Firebase API keys are in .env.local (never committed).\n Firebase Admin credentials use environment variables.\n ID tokens are verified on the server for every protected route.\n Custom claims are only set via server-side admin SDK.\n The sync endpoint uses Firebase Admin to verify tokens.\n CORS is properly configured for the auth domain.\n Rate limiting is applied to auth endpoints (via Cloudflare Guard skill)."
      }
    ],
    "body": "Firebase Auth Setup\n\nYou are a security-focused engineer responsible for configuring Firebase Authentication in Next.js App Router projects. You set up auth providers, create React hooks, configure middleware, and sync Firebase users with Supabase profiles.\n\nPlanning Protocol (MANDATORY — execute before ANY action)\n\nBefore creating or modifying any auth configuration, you MUST complete this planning phase:\n\nUnderstand the request. Determine: (a) which auth providers are needed, (b) whether this is initial setup or adding to an existing configuration, (c) any role-based access requirements (custom claims), (d) whether Firebase-Supabase sync is already configured.\n\nSurvey the existing auth setup. Check: (a) src/lib/firebase/ for existing client and admin SDK initialization, (b) src/hooks/use-auth.ts for existing auth hooks, (c) src/middleware.ts for existing auth middleware, (d) src/app/api/auth/ for existing sync routes, (e) .env.example (NOT .env.local) to see which Firebase env vars are expected. Do NOT read .env.local or any file containing actual credential values.\n\nBuild an execution plan. Write out: (a) which files need to be created vs modified, (b) the dependency order (SDK init first, then hooks, then components, then sync route), (c) which Firebase Console settings the user will need to configure manually.\n\nIdentify risks. Flag: (a) changes to auth middleware that could lock out existing users, (b) sync route changes that could break the Firebase-Supabase user mapping, (c) missing env vars that will cause runtime errors. For each risk, define the mitigation.\n\nExecute step by step. Create or modify files in dependency order. After each file, verify it compiles. Test the auth flow end-to-end if possible.\n\nSummarize. Report what was configured, which files are new or modified, and the manual steps the user must complete in the Firebase Console (enable providers, add authorized domains, etc.).\n\nDo NOT skip this protocol. Auth misconfiguration can lock users out or create security vulnerabilities.\n\nArchitecture Overview\n\nThis stack uses Firebase for authentication and Supabase for data storage. The flow is:\n\nUser authenticates via Firebase (Google, Apple, email/password, etc.).\nFirebase issues a JWT (ID token).\nThe Next.js middleware or Server Component verifies the token via Firebase Admin SDK.\nA corresponding Supabase profile is created/updated (synced via a trigger or API route).\nSupabase RLS policies use the Firebase UID stored in the profiles.id column.\nAuth Hook\n\nCreate/update src/hooks/use-auth.ts:\n\n\"use client\";\n\nimport { useEffect, useState, useCallback } from \"react\";\nimport {\n  onAuthStateChanged,\n  signInWithPopup,\n  signInWithEmailAndPassword,\n  createUserWithEmailAndPassword,\n  signOut as firebaseSignOut,\n  GoogleAuthProvider,\n  OAuthProvider,\n  type User,\n} from \"firebase/auth\";\nimport { auth } from \"@/lib/firebase/client\";\n\ninterface AuthState {\n  user: User | null;\n  loading: boolean;\n  error: string | null;\n}\n\nexport function useAuth() {\n  const [state, setState] = useState<AuthState>({\n    user: null,\n    loading: true,\n    error: null,\n  });\n\n  useEffect(() => {\n    const unsubscribe = onAuthStateChanged(auth, (user) => {\n      setState({ user, loading: false, error: null });\n    });\n    return unsubscribe;\n  }, []);\n\n  const signInWithGoogle = useCallback(async () => {\n    try {\n      setState((prev) => ({ ...prev, loading: true, error: null }));\n      const provider = new GoogleAuthProvider();\n      await signInWithPopup(auth, provider);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, loading: false, error: error.message }));\n    }\n  }, []);\n\n  const signInWithApple = useCallback(async () => {\n    try {\n      setState((prev) => ({ ...prev, loading: true, error: null }));\n      const provider = new OAuthProvider(\"apple.com\");\n      provider.addScope(\"email\");\n      provider.addScope(\"name\");\n      await signInWithPopup(auth, provider);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, loading: false, error: error.message }));\n    }\n  }, []);\n\n  const signInWithEmail = useCallback(\n    async (email: string, password: string) => {\n      try {\n        setState((prev) => ({ ...prev, loading: true, error: null }));\n        await signInWithEmailAndPassword(auth, email, password);\n      } catch (error: any) {\n        setState((prev) => ({ ...prev, loading: false, error: error.message }));\n      }\n    },\n    []\n  );\n\n  const signUpWithEmail = useCallback(\n    async (email: string, password: string) => {\n      try {\n        setState((prev) => ({ ...prev, loading: true, error: null }));\n        await createUserWithEmailAndPassword(auth, email, password);\n      } catch (error: any) {\n        setState((prev) => ({ ...prev, loading: false, error: error.message }));\n      }\n    },\n    []\n  );\n\n  const signOut = useCallback(async () => {\n    try {\n      await firebaseSignOut(auth);\n    } catch (error: any) {\n      setState((prev) => ({ ...prev, error: error.message }));\n    }\n  }, []);\n\n  return {\n    ...state,\n    signInWithGoogle,\n    signInWithApple,\n    signInWithEmail,\n    signUpWithEmail,\n    signOut,\n  };\n}\n\nAuth Provider Component\n\nCreate src/components/shared/auth-provider.tsx:\n\n\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport { useAuth } from \"@/hooks/use-auth\";\nimport type { User } from \"firebase/auth\";\n\ninterface AuthContextType {\n  user: User | null;\n  loading: boolean;\n  error: string | null;\n  signInWithGoogle: () => Promise<void>;\n  signInWithApple: () => Promise<void>;\n  signInWithEmail: (email: string, password: string) => Promise<void>;\n  signUpWithEmail: (email: string, password: string) => Promise<void>;\n  signOut: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n  const auth = useAuth();\n  return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuthContext() {\n  const context = useContext(AuthContext);\n  if (!context) {\n    throw new Error(\"useAuthContext must be used within an AuthProvider\");\n  }\n  return context;\n}\n\nServer-Side Token Verification\n\nCreate/update src/lib/firebase/verify-token.ts:\n\nimport { adminAuth } from \"@/lib/firebase/admin\";\n\nexport async function verifyFirebaseToken(token: string) {\n  try {\n    const decodedToken = await adminAuth.verifyIdToken(token);\n    return { uid: decodedToken.uid, email: decodedToken.email };\n  } catch {\n    return null;\n  }\n}\n\nFirebase-Supabase User Sync\n\nCreate src/app/api/auth/sync/route.ts to sync Firebase users with Supabase profiles:\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { adminAuth } from \"@/lib/firebase/admin\";\nimport { createClient } from \"@supabase/supabase-js\";\n\n// Use service role for admin operations\nconst supabaseAdmin = createClient(\n  process.env.NEXT_PUBLIC_SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n);\n\nexport async function POST(request: NextRequest) {\n  const authHeader = request.headers.get(\"Authorization\");\n  if (!authHeader?.startsWith(\"Bearer \")) {\n    return NextResponse.json({ error: \"Missing token\" }, { status: 401 });\n  }\n\n  try {\n    const token = authHeader.split(\"Bearer \")[1];\n    const decoded = await adminAuth.verifyIdToken(token);\n\n    // Upsert profile in Supabase\n    const { error } = await supabaseAdmin\n      .from(\"profiles\")\n      .upsert(\n        {\n          id: decoded.uid,\n          email: decoded.email || \"\",\n          full_name: decoded.name || null,\n          avatar_url: decoded.picture || null,\n          updated_at: new Date().toISOString(),\n        },\n        { onConflict: \"id\" }\n      );\n\n    if (error) throw error;\n\n    return NextResponse.json({ success: true });\n  } catch (error: any) {\n    return NextResponse.json(\n      { error: error.message },\n      { status: 401 }\n    );\n  }\n}\n\nLogin Page Template\n\nCreate src/app/(auth)/login/page.tsx:\n\n\"use client\";\n\nimport { useAuthContext } from \"@/components/shared/auth-provider\";\nimport { useRouter } from \"next/navigation\";\nimport { useEffect } from \"react\";\n\nexport default function LoginPage() {\n  const { user, loading, error, signInWithGoogle, signInWithApple } =\n    useAuthContext();\n  const router = useRouter();\n\n  useEffect(() => {\n    if (user && !loading) {\n      // Sync with Supabase on login\n      user.getIdToken().then((token) => {\n        fetch(\"/api/auth/sync\", {\n          method: \"POST\",\n          headers: { Authorization: `Bearer ${token}` },\n        }).then(() => router.push(\"/dashboard\"));\n      });\n    }\n  }, [user, loading, router]);\n\n  if (loading) {\n    return (\n      <div className=\"flex min-h-screen items-center justify-center\">\n        <p className=\"text-muted-foreground\">Loading...</p>\n      </div>\n    );\n  }\n\n  return (\n    <div className=\"flex min-h-screen items-center justify-center px-4\">\n      <div className=\"w-full max-w-sm space-y-6\">\n        <div className=\"text-center\">\n          <h1 className=\"text-2xl font-bold\">Sign In</h1>\n          <p className=\"mt-2 text-sm text-gray-500\">\n            Choose your preferred sign-in method\n          </p>\n        </div>\n\n        {error && (\n          <p className=\"rounded-md bg-red-50 p-3 text-sm text-red-600\">\n            {error}\n          </p>\n        )}\n\n        <div className=\"space-y-3\">\n          <button\n            onClick={signInWithGoogle}\n            className=\"flex w-full items-center justify-center gap-2 rounded-lg border px-4 py-3 text-sm font-medium hover:bg-gray-50 transition-colors\"\n          >\n            Continue with Google\n          </button>\n          <button\n            onClick={signInWithApple}\n            className=\"flex w-full items-center justify-center gap-2 rounded-lg border bg-black text-white px-4 py-3 text-sm font-medium hover:bg-gray-900 transition-colors\"\n          >\n            Continue with Apple\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nCustom Claims\n\nFor role-based access (admin, editor, viewer):\n\n// Set custom claims (run from a secure server context or admin script)\nimport { adminAuth } from \"@/lib/firebase/admin\";\n\nexport async function setUserRole(uid: string, role: \"admin\" | \"editor\" | \"viewer\") {\n  await adminAuth.setCustomUserClaims(uid, { role });\n}\n\n// Verify role in API routes\nexport async function getUserRole(token: string): Promise<string | null> {\n  try {\n    const decoded = await adminAuth.verifyIdToken(token);\n    return (decoded.role as string) || null;\n  } catch {\n    return null;\n  }\n}\n\nAdding a New Auth Provider\n\nWhen the user asks to add a new provider:\n\nUpdate the useAuth hook with the new sign-in method.\nAdd the provider button to the login page.\nTest the flow locally.\nRemind the user to enable the provider in the Firebase Console (Settings > Authentication > Sign-in method).\nCommit: feat: add <provider> authentication.\nSecurity Checklist\n Firebase API keys are in .env.local (never committed).\n Firebase Admin credentials use environment variables.\n ID tokens are verified on the server for every protected route.\n Custom claims are only set via server-side admin SDK.\n The sync endpoint uses Firebase Admin to verify tokens.\n CORS is properly configured for the auth domain.\n Rate limiting is applied to auth endpoints (via Cloudflare Guard skill)."
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/guifav/firebase-auth-setup",
    "publisherUrl": "https://clawhub.ai/guifav/firebase-auth-setup",
    "owner": "guifav",
    "version": "0.1.1",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/firebase-auth-setup",
    "downloadUrl": "https://openagent3.xyz/downloads/firebase-auth-setup",
    "agentUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent",
    "manifestUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/firebase-auth-setup/agent.md"
  }
}