### Standard Account Collection Setup Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md Example of setting up a basic 'accounts' collection using `withAccountCollection` with minimal configuration. ```typescript // src/collections/Accounts.ts import type { CollectionConfig } from 'payload' import { withAccountCollection } from 'payload-auth-plugin/collection' import { Users } from './Users' export const Accounts: CollectionConfig = withAccountCollection( { slug: 'accounts', }, Users.slug, ) ``` -------------------------------- ### Account Collection Setup with Custom Fields Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md Example of configuring an 'accounts' collection with additional custom fields and admin settings using `withAccountCollection`. ```typescript export const Accounts: CollectionConfig = withAccountCollection( { slug: 'accounts', admin: { defaultColumns: ['issuerName', 'user', 'createdAt'], useAsTitle: 'issuerName', }, fields: [ // Your extra fields are appended after the plugin's base fields { name: 'lastSignedInAt', type: 'date', label: 'Last Signed In', }, ], }, Users.slug, ) ``` -------------------------------- ### Install @simplewebauthn/browser Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md Install the necessary browser-side library for WebAuthn interactions. ```sh npm install @simplewebauthn/browser ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Clone your forked repository and install project dependencies using Bun. ```sh git clone https://github.com//payload-auth-plugin.git cd payload-auth-plugin bun install ``` -------------------------------- ### OAuth Provider Environment Variables Example (Google) Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/installation.md Example of environment variables required for a specific OAuth provider like Google. Refer to provider guides for exact names. ```sh GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= ``` -------------------------------- ### Install Plugin Dependencies Source: https://github.com/updot/payload-auth-plugin/blob/main/CONTRIBUTING.md Run this command in the root directory of the cloned repository to install all necessary project dependencies. ```bash pnpm install ``` -------------------------------- ### Run Example PayloadCMS Project Source: https://github.com/updot/payload-auth-plugin/blob/main/CONTRIBUTING.md Navigate to the example project and run the application to test your local plugin changes. Ensure the plugin is built first. ```bash cd /example/with-auth-plugin pnpm dev ``` -------------------------------- ### Minimal User Collection Setup Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md This snippet shows the most basic setup for a user collection using `withUsersCollection`. It only requires the `slug` property. ```typescript // src/collections/Users.ts import type { CollectionConfig } from 'payload' import { withUsersCollection } from 'payload-auth-plugin/collection' export const Users: CollectionConfig = withUsersCollection({ slug: 'users', }) ``` -------------------------------- ### Install Payload Auth Plugin with bun Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/installation.md Use this command to install the plugin using bun. ```sh bun add payload-auth-plugin ``` -------------------------------- ### OIDC Provider Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of how to create a new OIDC provider file. This includes defining the provider configuration and profile mapping. ```typescript import type { AccountInfo, OIDCProviderConfig, OAuthBaseProviderConfig, } from '../../types.js' type MyProviderConfig = OAuthBaseProviderConfig /** * Add MyProvider OIDC Provider * * #### Callback or Redirect URL pattern * ``` * https://example.com/api/{name}/oauth/callback/myprovider * ``` */ function MyProvider(config: MyProviderConfig): OIDCProviderConfig { const { overrideScope, ...restConfig } = config return { ...restConfig, id: 'myprovider', scope: overrideScope ?? 'email openid profile', issuer: 'https://accounts.myprovider.com', name: 'My Provider', algorithm: 'oidc', kind: 'oauth', profile: (profile): AccountInfo => ({ sub: profile.sub as string, name: profile.name as string, email: profile.email as string, picture: profile.picture as string, }), } } export default MyProvider ``` -------------------------------- ### User Collection Setup with Custom Fields Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md This example demonstrates configuring a user collection with custom fields, including an email, name fields, and a role selector. The `withUsersCollection` function merges these with its own injected fields. ```typescript // src/collections/Users.ts import type { CollectionConfig } from 'payload' import { withUsersCollection } from 'payload-auth-plugin/collection' export const Users: CollectionConfig = withUsersCollection({ slug: 'users', admin: { defaultColumns: ['email', 'first_name', 'last_name'], useAsTitle: 'email', }, fields: [ { name: 'email', // If you include an email-type field, the plugin won't add a duplicate type: 'email', required: true, label: 'Email', }, { name: 'first_name', type: 'text', label: 'First Name', }, { name: 'last_name', type: 'text', label: 'Last Name', }, { name: 'role', type: 'select', options: ['admin', 'editor', 'viewer'], defaultValue: 'viewer', }, ], timestamps: true, }) ``` -------------------------------- ### Callback URL Pattern Examples Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/README.md Examples of the expected callback URL format for different providers and environments. Ensure your domain, name, and provider ID are correctly substituted. ```plaintext https://myapp.com/api/admin/oauth/callback/google https://myapp.com/api/storefront/oauth/callback/github https://myapp.com/api/admin/oauth/callback/msft-entra ``` ```plaintext http://localhost:3000/api/admin/oauth/callback/google ``` -------------------------------- ### OAuth 2.0 Provider Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of how to create a new OAuth 2.0 provider file. This includes defining the authorization server details and profile mapping. ```typescript import type * as oauth from 'oauth4webapi' import type { OAuth2ProviderConfig, AccountInfo, OAuthBaseProviderConfig, } from '../../types.js' const authorization_server: oauth.AuthorizationServer = { issuer: 'https://myprovider.com', authorization_endpoint: 'https://myprovider.com/oauth/authorize', token_endpoint: 'https://myprovider.com/oauth/token', userinfo_endpoint: 'https://api.myprovider.com/v1/me', } type MyProviderConfig = OAuthBaseProviderConfig function MyProvider(config: MyProviderConfig): OAuth2ProviderConfig { const { overrideScope, ...restConfig } = config return { ...restConfig, id: 'myprovider', scope: overrideScope ?? 'email profile', authorization_server, name: 'My Provider', algorithm: 'oauth2', kind: 'oauth', profile: (profile): AccountInfo => ({ sub: profile.id as string, name: profile.name as string, email: profile.email as string, picture: profile.avatar_url as string, }), } } export default MyProvider ``` -------------------------------- ### Install Payload Auth Plugin with npm Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/installation.md Use this command to install the plugin using npm. ```sh npm install payload-auth-plugin ``` -------------------------------- ### Install Payload Auth Plugin with yarn Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/installation.md Use this command to install the plugin using yarn. ```sh yarn add payload-auth-plugin ``` -------------------------------- ### Install Payload Auth Plugin with pnpm Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/installation.md Use this command to install the plugin using pnpm. ```sh pnpm add payload-auth-plugin ``` -------------------------------- ### Full Auth Plugin Configuration Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/configuration.md Demonstrates a complete configuration for the authPlugin, showcasing multiple instances for admin and storefront applications with various providers like Google, Auth0, GitHub, and Password. ```typescript // payload.config.ts import { buildConfig } from 'payload' import { authPlugin } from 'payload-auth-plugin' import { GoogleAuthProvider, GitHubAuthProvider, Auth0AuthProvider, PasswordProvider, } from 'payload-auth-plugin/providers' import { Users } from './collections/Users' import { Accounts } from './collections/Accounts' import { renderForgotPasswordEmail } from './emails/forgotPassword' export default buildConfig({ serverURL: process.env.NEXT_PUBLIC_SERVER_URL!, collections: [Users, Accounts], plugins: [ // ── Admin panel ────────────────────────────────────────────────────────── authPlugin({ enabled: true, // default; can be toggled per environment name: 'admin', // → endpoints at /api/admin/... useAdmin: true, // integrate with Payload's admin session usersCollectionSlug: Users.slug, // 'users' accountsCollectionSlug: Accounts.slug, // 'accounts' allowOAuthAutoSignUp: false, // admins must be pre-created successRedirectPath: '/admin', errorRedirectPath: '/admin/login', providers: [ GoogleAuthProvider({ client_id: process.env.GOOGLE_CLIENT_ID!, client_secret: process.env.GOOGLE_CLIENT_SECRET!, }), Auth0AuthProvider({ client_id: process.env.AUTH0_CLIENT_ID!, client_secret: process.env.AUTH0_CLIENT_SECRET!, domain: process.env.AUTH0_DOMAIN!, }), ], }), // ── Frontend / storefront app ───────────────────────────────────────────── authPlugin({ name: 'storefront', usersCollectionSlug: Users.slug, accountsCollectionSlug: Accounts.slug, allowOAuthAutoSignUp: true, // anyone can self-register successRedirectPath: '/dashboard', errorRedirectPath: '/auth/signin', providers: [ GoogleAuthProvider({ client_id: process.env.GOOGLE_CLIENT_ID!, client_secret: process.env.GOOGLE_CLIENT_SECRET!, }), GitHubAuthProvider({ client_id: process.env.GITHUB_CLIENT_ID!, client_secret: process.env.GITHUB_CLIENT_SECRET!, }), PasswordProvider({ emailTemplates: { forgotPassword: renderForgotPasswordEmail, }, }), ], }), ], }) ``` -------------------------------- ### User Sign Up with Password Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/password.md Implement a user registration form using the password client method. This example shows how to handle form submission, user info, and auto-signin. ```tsx 'use client' import { appAuthClient } from '@/lib/auth' export default function SignUpPage() { const { password } = appAuthClient.register() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const data = new FormData(e.currentTarget) const result = await password({ email: data.get('email') as string, password: data.get('password') as string, // allowAutoSignin: true signs the user in immediately after registration allowAutoSignin: true, // userInfo sets additional fields on the created User document userInfo: { first_name: data.get('first_name'), last_name: data.get('last_name'), }, }) if (result.isError) { console.error(result.message) // result.kind === 'Conflict' means the email is already registered } } return (
) } ``` -------------------------------- ### User Sign In with Password Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/password.md Create a sign-in form using the password client method. This example demonstrates handling form submission and checking for authentication errors. ```tsx 'use client' import { appAuthClient } from '@/lib/auth' export default function SignInPage() { const { password } = appAuthClient.signin() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const data = new FormData(e.currentTarget) const result = await password({ email: data.get('email') as string, password: data.get('password') as string, }) if (result.isError) { console.error(result.message) // result.kind === 'NotAuthenticated' means wrong email or password } } return (
) } ``` -------------------------------- ### Export Provider from Index Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of how to export a newly created provider from the providers index file. ```typescript import MyProvider from './oidc/myprovider.js' // or ./oauth2/myprovider.js export { // ... existing exports MyProvider, } ``` -------------------------------- ### OAuth Sign-in Buttons Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Provides a React component to render buttons for initiating OAuth sign-in with different providers like Google, GitHub, and Discord. ```tsx 'use client' import { adminAuthClient } from '@/lib/auth' export function OAuthButtons() { const { oauth } = adminAuthClient.signin() return (
) } ``` -------------------------------- ### Okta Callback URL Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/okta.md Add this redirect URI to your Okta OIDC application configuration. Replace `{name}` with your plugin's name. ```plaintext https://your-domain.com/api/{name}/oauth/callback/okta ``` -------------------------------- ### Run Pending Migrations (Bash) Source: https://github.com/updot/payload-auth-plugin/blob/main/examples/with-website/README.md Execute this command on the server after building your project and before starting the application to apply any pending database migrations. It records which migrations have been run. ```bash pnpm payload migrate ``` -------------------------------- ### Add Vercel Blob Storage Adapter Source: https://github.com/updot/payload-auth-plugin/blob/main/examples/with-website/README.md Install the Vercel blob storage adapter for Payload. ```bash pnpm add @payloadcms/storage-vercel-blob ``` -------------------------------- ### Add Vercel Postgres DB Adapter Source: https://github.com/updot/payload-auth-plugin/blob/main/examples/with-website/README.md Install the Vercel Postgres database adapter for Payload. ```bash pnpm add @payloadcms/db-vercel-postgres ``` -------------------------------- ### Password Provider Configuration Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/password.md This object represents the configuration for the Password Provider, including email templates for password recovery. ```typescript { id: 'password', kind: 'password', emailTemplates: { forgotPassword: renderForgotPasswordEmail, }, } ``` -------------------------------- ### Password Sign-in Form Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md A React component demonstrating a form for user sign-in using email and password. Handles form submission and logs errors if the sign-in fails. ```tsx 'use client' import { appAuthClient } from '@/lib/auth' export function SignInForm() { const { password } = appAuthClient.signin() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const data = new FormData(e.currentTarget) const result = await password({ email: data.get('email') as string, password: data.get('password') as string, }) if (result.isError) { console.error(result.message) } } return (
) } ``` -------------------------------- ### User Registration Form Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md A client-side form component for user registration using email and password. It demonstrates how to use the `register().password()` method and handle the submission, including optional fields like `allowAutoSignin` and `userInfo`. ```tsx 'use client' import { appAuthClient } from '@/lib/auth' export function SignUpForm() { const { password } = appAuthClient.register() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const data = new FormData(e.currentTarget) const result = await password({ email: data.get('email') as string, password: data.get('password') as string, allowAutoSignin: true, userInfo: { first_name: data.get('first_name'), last_name: data.get('last_name'), }, }) if (result.isError) console.error(result.message) if (result.isSuccess) console.log('Account created!') } return (
) } ``` -------------------------------- ### Trigger GitLab Sign-in from a Component Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/gitlab.md Use the auth client to create a button that initiates the GitLab OAuth sign-in flow. This example demonstrates client-side usage. ```tsx 'use client' import { adminAuthClient } from '@/lib/auth' export function GitLabSignInButton() { const { oauth } = adminAuthClient.signin() return ( ) } ``` -------------------------------- ### Payload Configuration with PasskeyAuthProvider Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md Example of how to integrate the PasskeyAuthProvider into your Payload configuration file. Ensure your Payload serverURL is correctly set as it's used to derive WebAuthn options. ```typescript // payload.config.ts import { buildConfig } from 'payload' import { authPlugin } from 'payload-auth-plugin' import { PasskeyAuthProvider } from 'payload-auth-plugin/providers' export default buildConfig({ plugins: [ authPlugin({ name: 'app', usersCollectionSlug: 'users', accountsCollectionSlug: 'accounts', successRedirectPath: '/dashboard', errorRedirectPath: '/auth/signin', providers: [ PasskeyAuthProvider(), ], }), ], }) ``` -------------------------------- ### Configuring Google Authentication with Custom Params Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/google.md Customize the sign-in flow using the `params` option. This example forces the account picker and restricts sign-in to a specific Google Workspace domain. ```typescript GoogleAuthProvider({ client_id: process.env.GOOGLE_CLIENT_ID!, client_secret: process.env.GOOGLE_CLIENT_SECRET!, params: { prompt: 'select_account', hd: 'mycompany.com', // only allow sign-in from mycompany.com accounts }, }) ``` -------------------------------- ### Configuring JumpCloudAuthProvider with Override Scope Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/jumpcloud.md Example of initializing JumpCloudAuthProvider with a custom scope that includes 'offline_access'. Ensure environment variables for client ID and secret are set. ```typescript JumpCloudAuthProvider({ client_id: process.env.JUMP_CLOUD_CLIENT_ID!, client_secret: process.env.JUMP_CLOUD_CLIENT_SECRET!, overrideScope: 'openid email profile offline_access', }) ``` -------------------------------- ### Configure Common Params Options Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/microsoft-entra.md Pass Microsoft-specific query parameters using the `params` field. This example demonstrates forcing the account picker, pre-filling the username, and restricting sign-in to a specific domain. ```typescript MicrosoftEntraAuthProvider({ client_id: process.env.MSFT_ENTRA_CLIENT_ID!, client_secret: process.env.MSFT_ENTRA_CLIENT_SECRET!, tenant_id: process.env.MSFT_ENTRA_TENANT_ID!, params: { // Force account picker even when user is already signed in prompt: 'select_account', // Pre-fill the email/username field login_hint: 'user@mycompany.com', // Restrict sign-in to a specific domain (for multitenant apps) domain_hint: 'mycompany.com', }, }) ``` -------------------------------- ### User Collection Setup with Custom Access Rules Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md This snippet shows how to override the default access rules provided by `withUsersCollection`. It allows public reads while restricting creation to administrators. ```typescript export const Users: CollectionConfig = withUsersCollection({ slug: 'users', fields: [ /* ... */ ], access: { // Allow public reads (e.g. for public profiles) read: () => true, // Only admins can create users directly create: ({ req: { user } }) => user?.role === 'admin', // Keep other defaults by not specifying them here // (defaults from withUsersCollection are merged with spread — your keys win) }, }) ``` -------------------------------- ### Payload Configuration with Auth Plugin Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/README.md Example of configuring the payload-auth-plugin in a Payload CMS project. It demonstrates importing necessary modules and setting up authentication providers like Google and Password. ```typescript // payload.config.ts import { buildConfig } from 'payload' import { authPlugin } from 'payload-auth-plugin' import { GoogleAuthProvider, PasswordProvider } from 'payload-auth-plugin/providers' import { Users } from './collections/Users' import { Accounts } from './collections/Accounts' export default buildConfig({ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, collections: [Users, Accounts], plugins: [ authPlugin({ name: 'admin', useAdmin: true, usersCollectionSlug: Users.slug, accountsCollectionSlug: Accounts.slug, successRedirectPath: '/admin', errorRedirectPath: '/admin/login', providers: [ GoogleAuthProvider({ client_id: process.env.GOOGLE_CLIENT_ID!, client_secret: process.env.GOOGLE_CLIENT_SECRET!, }), PasswordProvider({ emailTemplates: { forgotPassword: myEmailTemplate }, }), ], }), ], }) ``` -------------------------------- ### Callback URLs for Microsoft Entra Setup Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/microsoft-entra.md These are the callback URLs to configure in your Azure Portal application registration. Ensure you replace `{name}` with the name used in your authPlugin() configuration. ```text https://your-domain.com/api/{name}/oauth/callback/msft-entra ``` ```text http://localhost:3000/api/{name}/oauth/callback/msft-entra ``` -------------------------------- ### Override Collection Fields and Access Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md Example demonstrating how to override specific fields, access rules, and admin configurations for the users collection. Only the desired keys need to be specified, with others falling back to plugin defaults. ```typescript export const Users: CollectionConfig = withUsersCollection({ slug: 'users', fields: [{ name: 'role', type: 'text' }], access: { read: () => true, // override: allow public reads // create / delete / update → remain as plugin defaults }, admin: { useAsTitle: 'email', // override: display email in the admin list title // defaultColumns → remains as plugin default (['name', 'email']) }, }) ``` -------------------------------- ### Passkey Authentication Flow Overview Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md Illustrates the steps involved in both registering a new passkey and authenticating with an existing one, highlighting the browser-server interaction and the security of private keys. ```text Registration (creating a passkey): Browser Server │ │ │ 1. Request options (challenge) │─────────────────►│ │◄─────────────────│ │ │ │ 2. Create credential (biometric prompt) │ (local to device)│ │ │ │ 3. Send credential response │─────────────────►│ │ │ 4. Verify & store credential │◄─────────────────│ │ 5. Session cookie│ Authentication (signing in with a passkey): Browser Server │ │ │ 1. Request options (challenge) │─────────────────►│ │◄─────────────────│ │ │ │ 2. Sign challenge (biometric prompt) │ (local to device)│ │ │ │ 3. Send assertion response │─────────────────►│ │ │ 4. Verify signature & counter │◄─────────────────│ │ 5. Session cookie│ ``` -------------------------------- ### Conventional Commit Message - Docs Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of a conventional commit message for documentation changes. ```git commit docs: add Twitch provider setup guide ``` -------------------------------- ### Build Project Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Command to build the project after adding a new provider. ```sh bun build ``` -------------------------------- ### Conventional Commit Message - Fix Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of a conventional commit message for a bug fix, detailing the problem and resolution. ```git commit fix: prevent session cookie from being set on failed OAuth callback Previously, if the provider returned an error during the callback, the plugin would still attempt to create a session, causing a misleading 'authenticated' state. Closes #38 ``` -------------------------------- ### Conventional Commit Message - Feature Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Example of a conventional commit message for a new feature, including an optional body and footer. ```git commit feat: add LinkedIn OIDC provider Implements OAuth 2.0 sign-in via LinkedIn using the standard authorization_server configuration pattern. Closes #42 ``` -------------------------------- ### Build Plugin Locally Source: https://github.com/updot/payload-auth-plugin/blob/main/CONTRIBUTING.md Execute this command in the root directory to build the plugin. This generates a '/dist' directory and is necessary for local testing. ```bash pnpm build ``` -------------------------------- ### Create Payload App with Website Template Source: https://github.com/updot/payload-auth-plugin/blob/main/examples/with-website/README.md Use the create-payload-app CLI to clone the website template directly to your machine. ```bash pnpx create-payload-app my-project -t website ``` -------------------------------- ### register().password() Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Creates a new user account with email and password. It allows for optional auto-signin and additional user information. ```APIDOC ## POST /api/{name}/auth/signup ### Description Creates a new user account with email and password. Optionally, the user can be automatically signed in, and additional user information can be provided. ### Method POST ### Endpoint `/api/{name}/auth/signup` ### Parameters #### Request Body - **email** (string) - Yes - The new user's email address. Must be unique. - **password** (string) - Yes - The new user's plaintext password. - **allowAutoSignin** (boolean) - No - If `true`, the user is automatically signed in after successful registration. Defaults to `false`. - **userInfo** (Record) - No - Additional fields to set on the created User document (e.g. `first_name`, `last_name`). Keys must match fields defined on your Users collection. ### Request Example ```json { "email": "user@example.com", "password": "plaintext_password", "allowAutoSignin": true, "userInfo": { "first_name": "John", "last_name": "Doe" } } ``` ### Response #### Success Response (200) - **isSuccess** (boolean) - Indicates if the operation was successful. - **message** (string) - A message indicating the outcome of the operation. #### Response Example ```json { "isSuccess": true, "message": "Account created!" } ``` ``` -------------------------------- ### React Email Forgot Password Template Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/password.md An example of a forgot password email template implemented using React Email components. This template includes a verification code and link. ```tsx // src/emails/forgotPassword.tsx import { Html, Body, Container, Heading, Text, Button, Preview } from '@react-email/components' interface ForgotPasswordEmailProps { verificationCode: string verificationLink: string user: { email: string } } export function ForgotPasswordEmail({ verificationCode, verificationLink, user, }: ForgotPasswordEmailProps) { return ( Reset your password Reset your password Hi {user.email}, Click the button below to reset your password. This link expires in 1 hour. Or copy this code: {verificationCode} If you didn't request a password reset, you can safely ignore this email. ) } // Export a render function for use in PasswordProvider export async function renderForgotPasswordEmail(context: ForgotPasswordEmailProps) { const { render } = await import('@react-email/render') return render() } ``` -------------------------------- ### Initialize Auth Client Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/password.md Create an instance of the AuthClient to interact with the authentication system. Ensure the client is initialized with the correct plugin name. ```typescript import { AuthClient } from 'payload-auth-plugin/client' export const appAuthClient = new AuthClient('app') ``` -------------------------------- ### Start Session Refresh Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/session-management.md Starts an interval to automatically refresh the session every 10 minutes. If the session expires, it stops the refresh interval and calls the onExpired callback. Requires the `appAuthClient` to be initialized. ```typescript // src/lib/sessionRefresh.ts 'use client' import { appAuthClient } from '@/lib/auth' let refreshInterval: ReturnType | null = null export function startSessionRefresh(onExpired: () => void) { stopSessionRefresh() refreshInterval = setInterval(async () => { const result = await appAuthClient.refreshSession() if (result.isError) { stopSessionRefresh() onExpired() } }, 10 * 60 * 1000) // every 10 minutes } export function stopSessionRefresh() { if (refreshInterval !== null) { clearInterval(refreshInterval) refreshInterval = null } } ``` -------------------------------- ### OktaAuthProvider Configuration with Params Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/okta.md Configure the OktaAuthProvider with client credentials and specific Okta query parameters like 'prompt', 'login_hint', and 'idp'. ```typescript OktaAuthProvider({ client_id: process.env.OKTA_CLIENT_ID!, client_secret: process.env.OKTA_CLIENT_SECRET!, domain: process.env.OKTA_DOMAIN!, params: { // Force the Okta login page even if the user has an active session prompt: 'login', // Pre-fill the username/email field login_hint: 'user@company.com', // Specify a specific Identity Provider (IdP) to skip Okta's IdP chooser idp: 'your-idp-id', }, }) ``` -------------------------------- ### Get Session User Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/README.md Retrieves the currently authenticated user's session information. ```APIDOC ## GET /api/{name}/session/user ### Description Retrieves the currently authenticated user's session information. ### Method GET ### Endpoint /api/{name}/session/user ### Response #### Success Response (200 OK) Returns the authenticated user's data. ``` -------------------------------- ### Configure Authentication Providers Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/configuration.md Set up multiple authentication providers including Google, GitHub, and Password. Ensure necessary environment variables for client IDs and secrets are configured. ```typescript import { GoogleAuthProvider, GitHubAuthProvider, PasswordProvider, } from 'payload-auth-plugin/providers' authPlugin({ providers: [ GoogleAuthProvider({ client_id: process.env.GOOGLE_CLIENT_ID!, client_secret: process.env.GOOGLE_CLIENT_SECRET!, }), GitHubAuthProvider({ client_id: process.env.GITHUB_CLIENT_ID!, client_secret: process.env.GITHUB_CLIENT_SECRET!, }), PasswordProvider({ emailTemplates: { forgotPassword: renderForgotPasswordEmail, }, }), ], // ... }) ``` -------------------------------- ### Initialize Frontend Auth Client Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/setup.md Create a new AuthClient instance in your frontend application's library, referencing the name of the frontend plugin instance. ```typescript // src/lib/auth.ts — add a second client for the frontend export const appAuthClient = new AuthClient('app') ``` -------------------------------- ### Register Admin Login Component Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/setup.md Configure your Payload setup to include the custom admin login component. This ensures it's rendered on the admin login page. ```typescript // payload.config.ts export default buildConfig({ admin: { components: { afterLogin: ['@/components/AdminLogin/index#AdminLogin'], }, }, // ... rest of config }) ``` -------------------------------- ### Password Sign-up Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/README.md Registers a new user with the provided credentials. ```APIDOC ## POST /api/{name}/auth/signup ### Description Registers a new user with the provided credentials. ### Method POST ### Endpoint /api/{name}/auth/signup ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example { "email": "newuser@example.com", "password": "securepassword" } ### Response #### Success Response (201 Created) Returns the newly created user's information. ``` -------------------------------- ### Trigger Twitch Sign-in from a React Component Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/twitch.md Implement a button in your React component to initiate the Twitch sign-in flow. This example uses the `adminAuthClient` to handle the OAuth redirect. ```tsx // src/components/TwitchSignIn.tsx 'use client' import { adminAuthClient } from '@/lib/auth' export function TwitchSignInButton() { const { oauth } = adminAuthClient.signin() return ( ) } ``` -------------------------------- ### Initialize PasskeyAuthProvider Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md The PasskeyAuthProvider function takes no arguments and returns a PasskeyProviderConfig object. ```typescript PasskeyAuthProvider() // → PasskeyProviderConfig { id: 'passkey', kind: 'passkey' } ``` -------------------------------- ### Build the Plugin Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Compile the plugin's code, generating ESM and TypeScript declaration files in the /dist directory. Re-run this command after making changes. ```sh bun build ``` -------------------------------- ### Trigger Keycloak Sign-in from a Component Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/keycloak.md Implement a button in your React component to initiate the Keycloak sign-in flow. This uses the `adminAuthClient` to get the OAuth client and trigger the redirect. ```tsx // src/components/KeycloakSignIn.tsx 'use client' import { adminAuthClient } from '@/lib/auth' export function KeycloakSignInButton() { const { oauth } = adminAuthClient.signin() // Use the same `identifier` you passed to KeyCloakAuthProvider return ( ) } ``` -------------------------------- ### Generate a Changeset Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/contributing.md Run this command to create a new changeset for versioning and changelog generation. Follow the prompts to select the bump type and provide a summary. ```sh bunx changeset ``` -------------------------------- ### SessionUser Type and Usage Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/session-management.md Defines a custom user type and demonstrates how to retrieve and use session data. Assumes an authenticated client `adminAuthClient` and access to request headers. ```typescript type SessionUser = { id: string email: string first_name?: string last_name?: string role?: string } const session = await adminAuthClient.getSession({ headers: await headers() }) if (session.isSuccess) { const user = session.data as SessionUser console.log(user.email) } ``` -------------------------------- ### Sign In with Passkey Client-Side Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md Handles the client-side logic for authenticating a user with an existing Passkey. This involves fetching authentication options from the server, initiating the browser's WebAuthn prompt, and submitting the assertion for server-side verification. ```tsx // src/components/PasskeySignIn.tsx 'use client' import { startAuthentication } from '@simplewebauthn/browser' export function PasskeySignInButton() { const handleSignIn = async () => { // Step 1: Get authentication options from the server const optionsRes = await fetch( `${process.env.NEXT_PUBLIC_PAYLOAD_AUTH_URL}/api/app/passkey/auth-options`, { method: 'POST' } ) const options = await optionsRes.json() // Step 2: Trigger the browser's WebAuthn dialog let assertion try { assertion = await startAuthentication(options) } catch (err) { console.error('Authentication cancelled or failed:', err) return } // Step 3: Send the assertion to the server for verification const verifyRes = await fetch( `${process.env.NEXT_PUBLIC_PAYLOAD_AUTH_URL}/api/app/passkey/auth`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(assertion), } ) const result = await verifyRes.json() if (result.isSuccess) { // Session cookie is now set — navigate to the protected area window.location.href = '/dashboard' } else { console.error('Authentication failed:', result.message) } } return ( ) } ``` -------------------------------- ### Usage Example: Integrating deleteLinkedAccounts Hook Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/collections.md Demonstrates how to integrate the deleteLinkedAccounts hook into your Payload Users collection configuration. Ensure the Accounts collection slug is correctly passed to the hook factory. ```typescript // src/collections/Users.ts import type { CollectionConfig } from 'payload' import { withUsersCollection } from 'payload-auth-plugin/collection' import { deleteLinkedAccounts } from 'payload-auth-plugin/collection/hooks' import { Accounts } from './Accounts' export const Users: CollectionConfig = withUsersCollection({ slug: 'users', fields: [ // ... your fields ], hooks: { afterDelete: [ deleteLinkedAccounts(Accounts.slug), // You can add more afterDelete hooks here ], }, }) ``` -------------------------------- ### Get Client Session in Custom Hook Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Fetches the current user's session client-side. Use this in custom React hooks for client components. It automatically handles session cookies. ```typescript 'use client' import { useEffect, useState } from 'react' import { appAuthClient } from '@/lib/auth' type SessionState = { loading: boolean isSuccess: boolean message: string data: Record } export function useSession(): SessionState { const [state, setState] = useState({ loading: true, isSuccess: false, message: '', data: {}, }) useEffect(() => { appAuthClient.getClientSession().then((result) => { setState({ loading: false, isSuccess: result.isSuccess, message: result.message, data: (result.data as Record) ?? {}, }) }) }, []) return state } ``` ```typescript 'use client' import { useSession } from '@/hooks/useSession' export function UserBadge() { const { loading, isSuccess, data } = useSession() if (loading) return Loading… if (!isSuccess) return Not signed in return {(data as any).email} } ``` -------------------------------- ### Auth0 Environment Variables Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/auth0.md Configure your Auth0 credentials by setting these environment variables. ```sh AUTH0_DOMAIN=your-tenant.auth0.com AUTH0_CLIENT_ID=your-client-id AUTH0_CLIENT_SECRET=your-client-secret ``` -------------------------------- ### TwitchAuthProvider with Custom Scope Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/twitch.md Example of configuring TwitchAuthProvider to override the default scope and include additional Twitch API scopes like 'channel:read:subscriptions'. Ensure only necessary scopes are requested. ```typescript TwitchAuthProvider({ client_id: process.env.TWITCH_CLIENT_ID!, client_secret: process.env.TWITCH_CLIENT_SECRET!, overrideScope: 'openid user:read:email channel:read:subscriptions', }) ``` -------------------------------- ### AuthClient Constructor Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Initializes a new AuthClient instance. This client maps directly to the plugin's API endpoints and provides a typed, promise-based API. ```APIDOC ## AuthClient Constructor ### Description Initializes a new `AuthClient` instance. This client maps directly to the plugin's API endpoints and provides a typed, promise-based API for use in React / Next.js components. ### Signature ```ts new AuthClient(name: string, options?: { payloadBaseURL?: string }) ``` ### Parameters #### Path Parameters - **name** (string) - Required - Must match the `name` option passed to `authPlugin()` in your Payload config. This is used to construct the correct API endpoint paths (e.g. `/api/{name}/oauth/...`). #### Query Parameters - **options.payloadBaseURL** (string) - Optional - Base URL of your Payload server. Defaults to `process.env.NEXT_PUBLIC_PAYLOAD_AUTH_URL`. Useful when you need to point to a different server in tests or SSR contexts. ### Throws - `MissingPayloadAuthBaseURL`: if neither `options.payloadBaseURL` nor `NEXT_PUBLIC_PAYLOAD_AUTH_URL` is set. ### Examples ```ts // Standard setup — reads base URL from environment variable export const adminAuthClient = new AuthClient('admin') // Explicit base URL — useful for testing or SSR overrides export const appAuthClient = new AuthClient('app', { payloadBaseURL: 'https://api.myapp.com', }) ``` ``` -------------------------------- ### Get Session Server-Side in Next.js Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Fetches the current user's session server-side in Next.js by forwarding request headers. Use this in Server Components, page.tsx files, Route Handlers, and server actions. ```ts // src/app/dashboard/page.tsx import { redirect } from 'next/navigation' import { headers } from 'next/headers' import { adminAuthClient } from '@/lib/auth' export default async function DashboardPage() { const session = await adminAuthClient.getSession({ headers: await headers(), }) if (session.isError) { redirect('/admin/login') } const user = session.data as { id: string; email: string } return (

Welcome, {user.email}

) } ``` -------------------------------- ### Instantiate AuthClient Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Instantiate the AuthClient with a name and optional options. The name must match the Payload config, and options can specify the Payload base URL. ```typescript export const adminAuthClient = new AuthClient('admin') ``` ```typescript export const appAuthClient = new AuthClient('app', { payloadBaseURL: 'https://api.myapp.com', }) ``` -------------------------------- ### Password Recovery Form Example Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md A client-side form component to initiate the password recovery flow. It takes an email address and calls the `forgotPassword` method. The UI updates to inform the user once the recovery email has been sent. ```tsx 'use client' import { useState } from 'react' import { appAuthClient } from '@/lib/auth' export function ForgotPasswordForm() { const [sent, setSent] = useState(false) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const data = new FormData(e.currentTarget) const result = await appAuthClient.forgotPassword({ email: data.get('email') as string, }) if (result.isSuccess) setSent(true) if (result.isError) console.error(result.message) } if (sent) return

Check your inbox for a recovery link.

return (
) } ``` -------------------------------- ### Register User with Password Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/auth-client.md Creates a new user account using email and password. Optionally allows automatic sign-in and includes additional user information. This method corresponds to a POST /api/{name}/auth/signup request. ```typescript register(): { password: (payload: PasswordSignupPayload) => Promise } ``` ```typescript password(payload: PasswordSignupPayload): Promise ``` -------------------------------- ### Register Passkey Client-Side Source: https://github.com/updot/payload-auth-plugin/blob/main/docs/providers/passkey.md Handles the client-side logic for registering a new Passkey. This involves getting registration options from the server, triggering the browser's WebAuthn API, and sending the resulting credential to the server for verification. ```tsx // src/components/RegisterPasskey.tsx 'use client' import { startRegistration } from '@simplewebauthn/browser' import { appAuthClient } from '@/lib/auth' export function RegisterPasskeyButton() { const handleRegister = async () => { // Step 1: Get registration options from the server const optionsRes = await fetch( `${process.env.NEXT_PUBLIC_PAYLOAD_AUTH_URL}/api/app/passkey/register-options`, { method: 'POST' } ) const options = await optionsRes.json() // Step 2: Trigger the browser's WebAuthn dialog (biometric / security key prompt) let credential try { credential = await startRegistration(options) } catch (err) { console.error('Registration cancelled or failed:', err) return } // Step 3: Send the credential response to the server for verification const verifyRes = await fetch( `${process.env.NEXT_PUBLIC_PAYLOAD_AUTH_URL}/api/app/passkey/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credential), } ) const result = await verifyRes.json() if (result.isSuccess) { console.log('Passkey registered successfully!') } else { console.error('Registration failed:', result.message) } } return ( ) } ```