### Full Featured OAuth Plugin Setup Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Illustrates a comprehensive setup for the OAuth plugin, enabling open signup, profile synchronization, and account linking. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], externalIdentityResource: { resourceId: 'externalIdentities' }, emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', userAvatarField: 'avatar', openSignup: { enabled: true, defaultFieldValues: { role: 'user' } }, }) ``` -------------------------------- ### OAuthPlugin Constructor Example Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Instantiate the OAuthPlugin with configuration options including email field, OAuth2 adapters, external identity resource settings, and signup configurations. This example demonstrates setting up Google and GitHub authentication. ```typescript import OAuthPlugin from '@adminforth/oauth'; import { GoogleAuthAdapter, GitHubAuthAdapter } from 'adminforth'; const oauthPlugin = new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), new GitHubAuthAdapter({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, }), ], externalIdentityResource: { resourceId: 'externalIdentities', }, emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', openSignup: { enabled: true, defaultFieldValues: { role: 'user', }, }, buttonText: 'Sign in with', iconOnly: false, pill: true, }); ``` -------------------------------- ### Example POST Request to OAuth Callback Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md An example of a POST request to the /oauth/callback endpoint, including authorization code and state parameters. ```http POST https://app.example.com/api/rest/oauth/callback?code=4%2F0AY0e-g...&state=eyJwcm92aWRlciI6Ikdvb2dsZUF1dGhBZGFwdGVyIn0%3D ``` -------------------------------- ### Initialize ExternalIdentityStore Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/ExternalIdentityStore.md Example of initializing the ExternalIdentityStore with custom resource configurations. ```typescript import OAuthPlugin, { ExternalIdentityStore } from '@adminforth/oauth'; const oauthPlugin = new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], externalIdentityResource: { resourceId: 'externalIdentities', adminUserIdField: 'userId', providerField: 'oauthProvider', subjectField: 'providerId', emailField: 'providerEmail', fullNameField: 'providerFullName', avatarUrlField: 'providerAvatar', }, }); ``` -------------------------------- ### Basic Login Only Plugin Setup Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Demonstrates the minimal configuration for the OAuth plugin, supporting basic OAuth login without account linking. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [new GoogleAuthAdapter(/* ... */)], }) ``` -------------------------------- ### Handling plugin configuration errors Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md This example illustrates error handling during the initialization of an OAuthPlugin. It catches configuration errors, logs them, and exits the process if the configuration is invalid. ```typescript try { const plugin = new OAuthPlugin({ emailField: 'email', emailConfirmedField: 'emailConfirmed', adapters: [new GoogleAuthAdapter(/* ... */)], }); } catch (error) { // Configuration error - fix and restart app console.error('Plugin configuration error:', error.message); process.exit(1); } ``` -------------------------------- ### Full-Featured OAuth Plugin Setup Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md A comprehensive configuration for the OAuth plugin, enabling multiple providers, account linking, and additional user profile fields. This setup supports advanced features like open signup and avatar synchronization. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], externalIdentityResource: { resourceId: 'externalIdentities' }, emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', userAvatarField: 'avatar', openSignup: { enabled: true }, }) ``` -------------------------------- ### OAuth with Account Linking Setup Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Configures the OAuth plugin to allow users to link multiple OAuth accounts to their existing AdminForth account. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter(/* ... */), new GitHubAuthAdapter(/* ... */), ], externalIdentityResource: { resourceId: 'externalIdentities' }, }) ``` -------------------------------- ### Configuration Error: Avatar Upload Plugin Not Found Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md If `userAvatarField` is specified, an upload plugin must be configured for the same field. This example shows the incorrect setup and the correct setup with both plugins. ```typescript new OAuthPlugin({ emailField: 'email', userAvatarField: 'avatar', adapters: [/* ... */], }); ``` ```typescript { resourceId: 'users', plugins: [ new FileUploadPlugin({ // Upload plugin first pathColumnName: 'avatar', /* ... */ }), new OAuthPlugin({ // OAuth plugin references same field emailField: 'email', userAvatarField: 'avatar', adapters: [/* ... */], }), ], } ``` -------------------------------- ### Configuration Error: Missing Primary Key on User Resource Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md The user resource configuration must include a primary key. This example shows how to correctly define a user resource with a primary key. ```typescript { resourceId: 'users', table: 'users', columns: [ { name: 'id', type: AdminForthDataTypes.INTEGER, primaryKey: true }, // ← Must have primaryKey: true { name: 'email', type: AdminForthDataTypes.STRING }, ], } ``` -------------------------------- ### Example of verifying connected accounts before disconnecting Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md This TypeScript snippet shows how to fetch a user's connected accounts and verify if a specific identity exists within that list before attempting to disconnect it. ```typescript const accounts = await externalIdentityStore.connectedAccounts(userId, adapters); // Verify identity ID exists in accounts.identities before disconnecting ``` -------------------------------- ### Example Request to Retrieve External Identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md This snippet shows how to make a POST request to the /api/rest/oauth/external-identities endpoint to fetch a list of connected OAuth providers and user identities. Ensure the Content-Type header is set to application/json. ```javascript const response = await fetch('/api/rest/oauth/external-identities', { method: 'POST', body: JSON.stringify({}), headers: { 'Content-Type': 'application/json', }, }); ``` -------------------------------- ### Email-Only Login Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Configure the OAuth plugin for a simple email-only login flow. This setup is suitable when you only need to authenticate users based on their email address. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* single provider */], }) ``` -------------------------------- ### Example Request to Disconnect an Identity Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md This snippet demonstrates how to send a POST request to the /api/rest/oauth/external-identity/disconnect endpoint, including the necessary identityId in the JSON body. ```javascript const response = await fetch('/api/rest/oauth/external-identity/disconnect', { method: 'POST', body: JSON.stringify({ identityId: '1' }), headers: { 'Content-Type': 'application/json', }, }); ``` -------------------------------- ### Example of handling OAuth callback errors in frontend Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md This snippet demonstrates how to handle potential errors returned from the OAuth callback API in a frontend application. It checks for 'error' in the response data and logs network errors. ```javascript try { const response = await fetch('/api/rest/oauth/callback?code=...&state=...', { method: 'POST', }); const data = await response.json(); if (data.error) { // Handle error console.error('OAuth error:', data.error); // Show user-friendly message } else if (data.allowedLogin) { // Login successful location.href = '/'; } else if (data.redirectTo) { // Account linking successful location.href = data.redirectTo; } } catch (err) { console.error('Network error:', err); } ``` -------------------------------- ### OAuth Plugin Endpoint Registration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md The OAuth plugin automatically registers several endpoints upon initialization. No manual setup is required for these endpoints, as they integrate directly with AdminForth. ```typescript // Endpoints are registered automatically during plugin initialization // No manual setup required; the plugin integrates directly with AdminForth ``` -------------------------------- ### GET /api/rest/oauth/external-identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md Retrieves a list of available OAuth providers and the user's currently connected external identities. ```APIDOC ## GET /api/rest/oauth/external-identities ### Description Retrieves a list of available OAuth providers and the user's currently connected external identities. ### Method GET ### Endpoint /api/rest/oauth/external-identities ### Response #### Success Response (200) - **providers** (Array) - List of available OAuth providers with connection status - **providers[].provider** (string) - Adapter class name - **providers[].name** (string) - Display name of provider - **providers[].icon** (string) - SVG icon as HTML string - **providers[].connected** (boolean) - Whether user has linked an account for this provider - **identities** (Array) - List of OAuth accounts linked to current user - **identities[].id** (string) - Primary key of the external identity record - **identities[].provider** (string) - Adapter class name - **identities[].providerName** (string) - Display name of provider - **identities[].providerIcon** (string) - SVG icon as HTML string - **identities[].subject** (string) - OAuth provider's unique user identifier - **identities[].email** (string | null) - Email from OAuth provider if stored - **identities[].phone** (string | null) - Phone from OAuth provider if stored - **identities[].fullName** (string | null) - Full name from OAuth provider if stored - **identities[].avatarUrl** (string | null) - Avatar URL from OAuth provider if stored #### Response Example { "providers": [ { "provider": "GoogleAuthAdapter", "name": "Google", "icon": "...", "connected": true }, { "provider": "GitHubAuthAdapter", "name": "GitHub", "icon": "...", "connected": false } ], "identities": [ { "id": "1", "provider": "GoogleAuthAdapter", "providerName": "Google", "providerIcon": "...", "subject": "google-user-123", "email": "user@gmail.com", "phone": null, "fullName": "John Doe", "avatarUrl": "https://example.com/avatar.jpg" } ] } ### Status Codes | Status | |---| | 200 | Successfully retrieved accounts | | 401 | User not authenticated | ``` -------------------------------- ### Get Plugin Instance Representation Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Returns a unique identifier for the plugin instance. This method is used to prevent the creation of multiple instances of the plugin within the same application. ```typescript instanceUniqueRepresentation(pluginOptions: any): string ``` -------------------------------- ### Configuration Error: Email Confirmed Field Not Found Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md The `emailConfirmedField` must exist in the user resource columns. This example illustrates the incorrect and correct ways to specify this field. ```typescript new OAuthPlugin({ emailField: 'email', emailConfirmedField: 'verified', // Column doesn't exist adapters: [/* ... */], }); ``` ```typescript new OAuthPlugin({ emailField: 'email', emailConfirmedField: 'emailConfirmed', // Use actual column name adapters: [/* ... */], }); ``` -------------------------------- ### Enable Signup for OAuth Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md If a user is not found and signup is disabled, enable signup by setting `openSignup.enabled` to true. Alternatively, pre-register the user. ```typescript new OAuthPlugin({ openSignup: { enabled: true, defaultFieldValues: { role: 'user' }, }, }); ``` ```typescript await adminforth.resource('users').create({ email: 'user@example.com', fullName: 'User Name', }); ``` -------------------------------- ### Minimal OAuth Plugin Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Sets up the OAuth plugin with the essential email field and a Google authentication adapter. Ensure GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables are set. ```typescript import OAuthPlugin from '@adminforth/oauth'; import { GoogleAuthAdapter } from 'adminforth'; const plugin = new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], }); ``` -------------------------------- ### setupEndpoints Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Registers the OAuth callback endpoint and endpoints for managing external identities with the AdminForth server. This method is invoked automatically during the plugin's initialization process. ```APIDOC ## setupEndpoints ### Description Registers OAuth callback endpoint and external identity management endpoints with the AdminForth server. Called automatically during plugin initialization. ### Method Signature ```typescript setupEndpoints(server: IHttpServer): void ``` ### Parameters - **server** (IHttpServer) - The HTTP server instance to register endpoints on. ``` -------------------------------- ### Configure OAuth with Open Signup and Profile Sync Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Use this configuration to enable users to sign up via OAuth without pre-registration. It automatically populates user profiles with name, email, and avatar, marks emails as confirmed, and assigns a default role. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [new GoogleAuthAdapter(/* ... */)], externalIdentityResource: { resourceId: 'externalIdentities', }, emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', userAvatarField: 'avatar', openSignup: { enabled: true, defaultFieldValues: { role: 'user', }, }, }) ``` -------------------------------- ### Registering OAuth Plugin with AdminForth Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Initializes AdminForth and registers the OAuth plugin, configuring it with user resource details and adapters. ```typescript import AdminForth from 'adminforth'; import OAuthPlugin from '@adminforth/oauth'; const oauth = new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], }); const admin = new AdminForth({ resources: [ { resourceId: 'users', table: 'users', columns: [ { name: 'id', type: AdminForthDataTypes.INTEGER, primaryKey: true }, { name: 'email', type: AdminForthDataTypes.STRING }, { name: 'password_hash', type: AdminForthDataTypes.STRING }, { name: 'email_confirmed', type: AdminForthDataTypes.BOOLEAN }, ], plugins: [oauth], }, ], }); ``` -------------------------------- ### OAuthPlugin Constructor Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Initializes a new instance of the OAuthPlugin with the provided configuration options. This includes setting up email fields, OAuth2 provider adapters, and optional configurations for external identity, email confirmation, user details, button appearance, session duration, and signup behavior. ```APIDOC ## OAuthPlugin Constructor ### Description Creates a new OAuth plugin instance. ### Parameters - **options** (OAuthPluginOptions) - Required - Plugin configuration object - **options.emailField** (string) - Required - Name of the email column in the user resource - **options.adapters** (OAuth2Adapter[]) - Required - Array of OAuth2 provider adapters (e.g., from adminforth package) - **options.externalIdentityResource** (ExternalIdentityResourceOptions) - Optional - Configuration for external identity storage; enables account linking and connected accounts features - **options.emailConfirmedField** (string) - Optional - Name of the boolean column to track email confirmation status - **options.userFullNameField** (string) - Optional - Name of the column to store the user's full name from OAuth provider - **options.userAvatarField** (string) - Optional - Name of the column to store the user's avatar; requires an upload plugin configured for this field - **options.buttonText** (string) - Optional - Custom text prefix for OAuth button labels (Default: 'Continue with') - **options.iconOnly** (boolean) - Optional - Display only provider icons instead of full buttons (Default: false) - **options.pill** (boolean) - Optional - Use pill-shaped buttons (fully rounded borders) (Default: false) - **options.authenticationExpireDuration** (string) - Optional - Duration string (e.g., '7d', '24h') for how long OAuth login sessions are valid; overrides AdminForth default - **options.openSignup** (OpenSignupConfig) - Optional - Configuration for allowing new user signup via OAuth (Default: { enabled: false }) - **options.openSignup.enabled** (boolean) - Optional - Whether to create new users on their first OAuth login (Default: false) - **options.openSignup.defaultFieldValues** (Record) - Optional - Default values for user fields when creating new users via OAuth (Default: {}) - **options.componentsOrderUnderLoginButton** (number) - Optional - Z-index order for positioning the OAuth buttons component on the login page (Default: 0) ### Throws - Error: if `emailField` is not provided - Error: if the specified `emailField` does not exist in the user resource - Error: if `emailConfirmedField` is provided but does not exist in the user resource - Error: if `emailConfirmedField` is provided but is not a boolean type - Error: if `userFullNameField` is provided but does not exist in the user resource - Error: if `userAvatarField` is provided but no upload plugin is configured for that field - Error: if `userAvatarField` is used with OpenID/OpenID Connect adapters ``` -------------------------------- ### Full OAuth Plugin Configuration with Account Linking Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Set up the OAuth plugin with multiple authentication adapters and configure external identity resource for account linking and management. This includes options for signup, button text, and authentication expiration. ```typescript import OAuthPlugin from '@adminforth/oauth'; import { GoogleAuthAdapter, GitHubAuthAdapter } from 'adminforth'; const oauthPlugin = new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), new GitHubAuthAdapter({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, }), ], externalIdentityResource: { resourceId: 'externalIdentities', adminUserIdField: 'adminUserId', providerField: 'provider', subjectField: 'subject', emailField: 'providerEmail', fullNameField: 'providerName', avatarUrlField: 'avatarUrl', }, emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', userAvatarField: 'avatar', openSignup: { enabled: true, defaultFieldValues: { role: 'user', }, }, buttonText: 'Sign in with', iconOnly: false, pill: true, authenticationExpireDuration: '7d', }); ``` -------------------------------- ### Import OAuthPlugin Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Import the main OAuthPlugin class from the library. This is the primary entry point for using the plugin. ```typescript import OAuthPlugin from '@adminforth/oauth'; ``` -------------------------------- ### Configure Open Signup via OAuth Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Enable or disable user registration through OAuth login. When enabled, new users can create accounts. You can also set default values for new user records, such as role or status. ```typescript openSignup: { enabled: true, defaultFieldValues: { role: 'user', status: 'active', organizationId: 1, emailConfirmed: true, }, } ``` -------------------------------- ### Initiate OAuth Connection Request Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md Use this POST request to initiate an OAuth connection. It requires the provider name and the redirect URI. The response contains a URL to redirect the user to the OAuth provider. ```javascript const response = await fetch('/api/rest/oauth/external-identity/connect-action', { method: 'POST', body: JSON.stringify({ provider: 'GoogleAuthAdapter', redirectUri: window.location.origin + '/oauth/callback', }), headers: { 'Content-Type': 'application/json', }, }); const { action } = await response.json(); window.location.href = action.url; // Redirect to OAuth provider ``` -------------------------------- ### Minimal OAuth Plugin Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Configure the OAuth plugin with a single authentication adapter and register it with a user resource. Ensure necessary environment variables for client ID and secret are set. ```typescript import OAuthPlugin from '@adminforth/oauth'; import { GoogleAuthAdapter } from 'adminforth'; const oauthPlugin = new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], }); // Register with user resource const admin = new AdminForth({ resources: [ { resourceId: 'users', table: 'users', columns: [ { name: 'id', type: AdminForthDataTypes.INTEGER, primaryKey: true }, { name: 'email', type: AdminForthDataTypes.STRING }, { name: 'password_hash', type: AdminForthDataTypes.STRING }, ], plugins: [oauthPlugin], }, ], }); ``` -------------------------------- ### Import ExternalIdentityStore Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/ExternalIdentityStore.md Import the ExternalIdentityStore class from the AdminForth OAuth library. ```typescript import { ExternalIdentityStore } from '@adminforth/oauth'; ``` -------------------------------- ### General OAuth Provider Environment Variables Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Provides a general pattern for setting environment variables for any OAuth provider, using client ID and secret. ```bash PROVIDER_CLIENT_ID=your-client-id PROVIDER_CLIENT_SECRET=your-client-secret ``` -------------------------------- ### Configure OAuth Adapters Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Provides an array of OAuth2 provider adapters, each configured with client ID and secret. Supports AdminForth's built-in adapters like Google and GitHub, or custom implementations. ```typescript adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), new GitHubAuthAdapter({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, }), ] ``` -------------------------------- ### Full OAuth Plugin Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Configures the OAuth plugin with all available options, including multiple adapters, external identity storage, user profile fields, UI customizations, authentication settings, and open signup. ```typescript import OAuthPlugin from '@adminforth/oauth'; import { GoogleAuthAdapter, GitHubAuthAdapter } from 'adminforth'; const plugin = new OAuthPlugin({ // Required emailField: 'email', adapters: [ new GoogleAuthAdapter({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), new GitHubAuthAdapter({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, }), ], // External identity storage externalIdentityResource: { resourceId: 'externalIdentities', adminUserIdField: 'adminUserId', providerField: 'provider', subjectField: 'subject', emailField: 'providerEmail', phoneField: 'providerPhone', fullNameField: 'providerName', avatarUrlField: 'avatarUrl', externalUserIdField: 'externalUserId', metaField: 'metadata', }, // Optional fields emailConfirmedField: 'emailConfirmed', userFullNameField: 'fullName', userAvatarField: 'avatar', // UI options buttonText: 'Sign in with', iconOnly: false, pill: true, componentsOrderUnderLoginButton: 10, // Authentication options authenticationExpireDuration: '7d', // Open signup openSignup: { enabled: true, defaultFieldValues: { role: 'user', status: 'active', }, }, }); ``` -------------------------------- ### Multi-Provider Login with Account Linking Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Set up the OAuth plugin to support multiple authentication providers and enable account linking. This configuration allows users to connect multiple external identities to their account. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* multiple adapters */], externalIdentityResource: { resourceId: 'externalIdentities' }, }) ``` -------------------------------- ### Google OAuth Environment Variables Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Sets the necessary environment variables for Google OAuth authentication, including client ID and secret. ```bash GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=your-google-client-secret ``` -------------------------------- ### Minimum User Resource Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Defines the essential configuration for the user resource, including ID, email, and password hash columns. ```typescript { resourceId: 'users', table: 'users', columns: [ { name: 'id', type: AdminForthDataTypes.INTEGER, primaryKey: true }, { name: 'email', type: AdminForthDataTypes.STRING }, { name: 'password_hash', type: AdminForthDataTypes.STRING }, ], } ``` -------------------------------- ### GitHub OAuth Environment Variables Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Sets the necessary environment variables for GitHub OAuth authentication, including client ID and secret. ```bash GITHUB_CLIENT_ID=your-github-client-id GITHUB_CLIENT_SECRET=your-github-client-secret ``` -------------------------------- ### OpenSignupConfig Type Definition Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/types.md Defines the configuration for enabling and customizing OAuth-based user signup. Allows setting default values for new user records. ```typescript type OpenSignupConfig = { enabled?: boolean; defaultFieldValues?: Record; }; ``` -------------------------------- ### Configure External Identity Resource Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md When a user attempts an account linking action but the `externalIdentityResource` is not configured, configure it to enable external identities. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], externalIdentityResource: { resourceId: 'externalIdentities', }, }); ``` -------------------------------- ### Request Payload for Initiating Connection Action Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md When calling the POST /oauth/external-identity/connect-action endpoint, provide the OAuth provider class name and the desired redirect URI in this JSON format. ```json { "provider": "GoogleAuthAdapter", "redirectUri": "https://app.example.com/oauth/callback" } ``` -------------------------------- ### POST /oauth/external-identity/connect-action Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Initiates the account linking process for a specific external identity provider. This endpoint redirects the user to the provider's authorization page. ```APIDOC ## POST /oauth/external-identity/connect-action ### Description Initiates the account linking process for a specific external identity provider. This endpoint redirects the user to the provider's authorization page. ### Method POST ### Endpoint /oauth/external-identity/connect-action ### Parameters #### Request Body - **userId** (string) - Required - The ID of the user initiating the connection. - **provider** (string) - Required - The name of the OAuth provider to connect. ### Request Example ```json { "userId": "user_12345", "provider": "google" } ``` ### Response #### Success Response (200) - **redirectUrl** (string) - The URL to redirect the user to for OAuth authorization. #### Response Example ```json { "redirectUrl": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=...&scope=...&response_type=code&state=..." } ``` ``` -------------------------------- ### Account Linking and Disconnection Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md To link an external account to a new user when it's already connected, first disconnect it from the old user, then reconnect to the new user. Admins can also manually fix database records. ```typescript // Disconnect first await externalIdentityStore.disconnect(identityId, otherUserId); ``` ```typescript // Then connect to new user await externalIdentityStore.createOrUpdate(newUserId, identity); ``` -------------------------------- ### OAuth Callback Success Response (User Logged In) Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md This JSON response is returned upon successful user login via the /oauth/callback endpoint. ```json { "allowedLogin": true, "redirectTo": "/" } ``` -------------------------------- ### Response Payload for Initiating Connection Action Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md A successful request to initiate a connection action will return a JSON object containing an 'action' object. The 'action.url' field holds the OAuth provider's authorization URL. ```json { "action": { "type": "url", "url": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=...&state=..." } } ``` -------------------------------- ### POST /oauth/callback Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Handles the callback from the OAuth provider after user authentication. This endpoint is crucial for completing the OAuth flow and establishing a user session. ```APIDOC ## POST /oauth/callback ### Description Handles the callback from the OAuth provider after user authentication. This endpoint is crucial for completing the OAuth flow and establishing a user session. ### Method POST ### Endpoint /oauth/callback ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from the OAuth provider. - **state** (string) - Required - The state parameter to prevent CSRF attacks. ### Request Example ```json { "code": "authorization_code_from_provider", "state": "csrf_token_value" } ``` ### Response #### Success Response (200) - **userId** (string) - The ID of the authenticated user. - **token** (string) - The session token for the user. #### Response Example ```json { "userId": "user_12345", "token": "session_jwt_token" } ``` ``` -------------------------------- ### AdminForth Peer Dependency Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Specifies the required AdminForth version as a peer dependency in package.json. ```json { "peerDependencies": { "adminforth": "^2.50.0" } } ``` -------------------------------- ### Configure External Identity Storage Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Enables advanced OAuth features like account linking and discovery by configuring the external identity resource. If omitted, login relies solely on email matching. ```typescript externalIdentityResource: { resourceId: 'externalIdentities', adminUserIdField: 'adminUserId', providerField: 'provider', subjectField: 'subject', } ``` -------------------------------- ### OAuth Callback Success Response (Account Linked) Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md When the action is 'connect', this response redirects the user to the connected accounts page after successful account linking via the /oauth/callback endpoint. ```json { "redirectTo": "/settings/connected-accounts" } ``` -------------------------------- ### OAuth with Account Linking Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Configures the OAuth plugin to support account linking across multiple providers. It uses the 'externalIdentities' resource to manage linked accounts. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [ new GoogleAuthAdapter(/* ... */), new GitHubAuthAdapter(/* ... */), ], externalIdentityResource: { resourceId: 'externalIdentities', }, }) ``` -------------------------------- ### OAuthPluginOptions Interface Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/types.md Defines the main configuration object for the OAuthPlugin constructor. It specifies fields for user identification, external identity integration, button customization, session duration, signup options, and component ordering. ```typescript interface OAuthPluginOptions { emailField: string; externalIdentityResource?: ExternalIdentityResourceOptions; emailConfirmedField?: string; userFullNameField?: string; adapters: OAuth2Adapter[]; buttonText?: string; iconOnly?: boolean; pill?: boolean; authenticationExpireDuration?: string; openSignup?: { enabled?: boolean; defaultFieldValues?: Record; }; componentsOrderUnderLoginButton?: number; userAvatarField?: string; } ``` -------------------------------- ### Exported Modules Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/README.md Shows the default and named exports available from the plugin package. ```typescript // Default export import OAuthPlugin from '@adminforth/oauth'; // Named exports export { OAuthPlugin }; export { ExternalIdentityStore } from './externalIdentityStore'; export type { OAuthPluginOptions, ExternalIdentityResourceOptions, OAuthIdentity, OAuth2UserInfo, OAuthProviderState, HttpExtra, } from './types'; ``` -------------------------------- ### Verify Adapter Configuration for Invalid OAuth Provider Error Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md If an 'Invalid OAuth provider' error occurs, verify that the adapter mentioned in the state parameter is correctly configured and present in the `adapters` array. ```typescript new OAuthPlugin({ adapters: [ new GoogleAuthAdapter(/* ... */), // State mentions 'GoogleAuthAdapter' ], }); ``` -------------------------------- ### Configure Icon-Only OAuth Buttons Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Control whether OAuth buttons display only provider icons or both text and icons. Set to `true` for icons only, `false` for full button text and icon. ```typescript iconOnly: false // [Google icon] Continue with Google ``` ```typescript iconOnly: true // [Google icon] ``` -------------------------------- ### AdminForth Resource Configuration for External Identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Configures the 'externalIdentities' resource within AdminForth, mapping it to the 'external_identities' database table and defining its columns. ```typescript { resourceId: 'externalIdentities', table: 'external_identities', columns: [ { name: 'id', type: AdminForthDataTypes.INTEGER, primaryKey: true }, { name: 'admin_user_id', type: AdminForthDataTypes.INTEGER }, { name: 'provider', type: AdminForthDataTypes.STRING }, { name: 'subject', type: AdminForthDataTypes.STRING }, { name: 'provider_email', type: AdminForthDataTypes.STRING }, { name: 'provider_phone', type: AdminForthDataTypes.STRING }, { name: 'provider_name', type: AdminForthDataTypes.STRING }, { name: 'avatar_url', type: AdminForthDataTypes.STRING }, { name: 'external_user_id', type: AdminForthDataTypes.STRING }, { name: 'metadata', type: AdminForthDataTypes.JSON }, ], } ``` -------------------------------- ### Set OAuth Buttons Component Z-Index Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Define the z-index order for the OAuth buttons component when it's placed under the login button. Use this to control its stacking order among other injected components. ```typescript componentsOrderUnderLoginButton: 10 // Places OAuth buttons lower on page ``` -------------------------------- ### Configure Pill-Shaped OAuth Buttons Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Enable fully rounded (pill-shaped) borders for OAuth buttons by setting this to `true`. The default is `false`, resulting in standard rounded corners. ```typescript pill?: boolean default: false ``` -------------------------------- ### Configuration Error: User Full Name Field Not Found Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md The `userFullNameField` must exist in the user resource columns. This shows the incorrect and correct configurations for this field. ```typescript new OAuthPlugin({ emailField: 'email', userFullNameField: 'displayName', // Doesn't exist adapters: [/* ... */], }); ``` ```typescript new OAuthPlugin({ emailField: 'email', userFullNameField: 'fullName', // Use actual column name adapters: [/* ... */], }); ``` -------------------------------- ### OAuth Callback Error Response Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md This JSON response indicates an authentication failure during the OAuth callback process. ```json { "error": "User not found", "allowedLogin": false } ``` -------------------------------- ### createOrUpdate Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/ExternalIdentityStore.md Links a new or updates an existing external identity to a user. If the identity is already linked to another user, an error is thrown. ```APIDOC ## createOrUpdate ### Description Links a new or updates an existing external identity to a user. If the identity is already linked to another user, an error is thrown. ### Method createOrUpdate ### Parameters #### Path Parameters - **userId** (string) - Required - The primary key of the AdminForth user to link the identity to. #### Request Body - **provider** (string) - Required - The name of the OAuth adapter class (e.g., 'GoogleAuthAdapter'). - **subject** (string) - Required - The unique identifier for the user from the external OAuth provider. - **email** (string) - Optional - The email address of the user from the external provider. - **fullName** (string) - Optional - The full name of the user from the external provider. - **profilePictureUrl** (string) - Optional - The URL to the user's profile picture from the external provider. ### Request Example ```json { "provider": "GoogleAuthAdapter", "subject": "google-123456", "email": "user@gmail.com", "fullName": "John Doe", "profilePictureUrl": "https://example.com/avatar.jpg" } ``` ### Response This method does not explicitly define a return type for success, but it throws an error if the identity is already linked to another user. ``` -------------------------------- ### instanceUniqueRepresentation Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Returns a unique identifier for this plugin instance, used to prevent multiple instances of the OAuth plugin from being registered within the same application. ```APIDOC ## instanceUniqueRepresentation ### Description Returns a unique identifier for this plugin instance to prevent multiple instances per application. ### Method Signature ```typescript instanceUniqueRepresentation(pluginOptions: any): string ``` ### Returns #### Success Response - **string** - Always returns `"single"` to enforce a single instance per app. ``` -------------------------------- ### OAuth Callback State Parameter Structure Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/endpoints.md The state parameter for the /oauth/callback endpoint must be a Base64-encoded JSON object. It includes the provider name and optional action or redirect URI. ```json { "provider": "GoogleAuthAdapter", "action": "connect", "redirectUri": "https://app.example.com/oauth/callback" } ``` -------------------------------- ### Constructor Warning: External Identity Resource Deprecation Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md Using OAuth without `externalIdentityResource` is deprecated. This snippet demonstrates the old, deprecated method and the new, recommended approach. ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], }); ``` ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], externalIdentityResource: { resourceId: 'externalIdentities', }, }); ``` -------------------------------- ### modifyResourceConfig Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md This method is automatically called by AdminForth during plugin initialization. It configures the plugin for a specific user resource by validating settings and registering necessary components like custom pages and login buttons. ```APIDOC ## modifyResourceConfig ### Description Called automatically by AdminForth during plugin initialization to configure the plugin for a specific user resource. Validates configuration and registers custom pages and login button components. ### Method Signature ```typescript modifyResourceConfig( adminforth: IAdminForth, resource: AdminForthResource ): void ``` ### Parameters - **adminforth** (IAdminForth) - The AdminForth instance. - **resource** (AdminForthResource) - The user resource configuration. ### Throws - Error: if the user resource has no primary key - Error: if the specified resource fields do not exist - Error: if field types are invalid (e.g., emailConfirmedField not boolean) ``` -------------------------------- ### Handling specific identity store errors in backend custom code Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md This backend code snippet shows how to catch and handle errors from an ExternalIdentityStore, specifically checking for account linking conflicts and logging other general errors. ```typescript try { const externalIdentityStore = new ExternalIdentityStore(adminforth, config); await externalIdentityStore.createOrUpdate(userId, identity); } catch (error) { if (error.message.includes('already connected to another user')) { // Handle account linking conflict logger.warn('Account linking conflict', { userId, identity }); } else { // Handle other errors logger.error('Identity store error', { error }); } } ``` -------------------------------- ### OAuth Plugin Endpoints Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md The OAuth plugin automatically registers several endpoints for handling OAuth callbacks, managing external identity connections, and initiating connection flows. ```APIDOC ## POST /oauth/callback ### Description Handles the callback from an OAuth provider after user authentication. ### Method POST ### Endpoint /oauth/callback ## POST /oauth/external-identities ### Description Lists all external identities (connected accounts) associated with the current user. ### Method POST ### Endpoint /oauth/external-identities ## POST /oauth/external-identity/disconnect ### Description Disconnects a specified external identity from the user's account. ### Method POST ### Endpoint /oauth/external-identity/disconnect ## POST /oauth/external-identity/connect-action ### Description Initiates the account connection flow for an external identity. ### Method POST ### Endpoint /oauth/external-identity/connect-action ``` -------------------------------- ### Specify User Email Field Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Defines the user resource column for storing email addresses, used for login, fallback lookup, and new user creation. The field must be of string type. ```typescript emailField: 'email' ``` -------------------------------- ### validateConfigAfterDiscover Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Validates the OAuth plugin's configuration after the AdminForth resource discovery process. It ensures that if an avatar field is specified, an appropriate upload plugin is configured. ```APIDOC ## validateConfigAfterDiscover ### Description Validates plugin configuration after AdminForth resource discovery. Ensures that avatar upload plugin is properly configured if avatar field is specified. ### Method Signature ```typescript validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource): void ``` ### Parameters #### Path Parameters - **adminforth** (IAdminForth) - Required - The AdminForth instance - **resourceConfig** (AdminForthResource) - Required - The user resource configuration ### Throws - Error: if `userAvatarField` is specified but no upload plugin is configured for that field ``` -------------------------------- ### Constructor Error: Missing emailField Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md The OAuthPlugin constructor requires the `emailField` option to be provided. This snippet shows the incorrect and correct way to initialize the plugin. ```typescript new OAuthPlugin({ adapters: [/* ... */], }); ``` ```typescript new OAuthPlugin({ emailField: 'email', adapters: [/* ... */], }); ``` -------------------------------- ### HttpExtra Interface Definition Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/types.md Defines the structure for HTTP request and response context passed during OAuth callbacks. Includes headers, cookies, URL, query parameters, and body. ```typescript interface HttpExtra { headers: Record; cookies: Record; requestUrl: string; query: Record; body: Record; response?: any; } ``` -------------------------------- ### PostgreSQL Schema for External Identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Defines the SQL schema for storing external identity information, linking it to admin users. Includes fields for provider details, user IDs, and metadata. ```sql CREATE TABLE external_identities ( id SERIAL PRIMARY KEY, admin_user_id INT NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE, provider VARCHAR(255) NOT NULL, subject VARCHAR(255) NOT NULL, provider_email VARCHAR(255), provider_phone VARCHAR(255), provider_name VARCHAR(255), avatar_url TEXT, external_user_id VARCHAR(255), metadata JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(provider, subject) ); CREATE INDEX idx_external_identities_user_id ON external_identities(admin_user_id); CREATE INDEX idx_external_identities_provider_subject ON external_identities(provider, subject); ``` -------------------------------- ### Retrieve Connected Accounts Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/ExternalIdentityStore.md Fetches all OAuth identities linked to a user and the connection status for available providers. Useful for displaying a user's linked accounts and available options. ```typescript const accounts = await externalIdentityStore.connectedAccounts( userId, [googleAdapter, githubAdapter] ); console.log(accounts.providers); // [ // { provider: 'GoogleAuthAdapter', name: 'Google', icon: '...svg...', connected: true }, // { provider: 'GitHubAuthAdapter', name: 'GitHub', icon: '...svg...', connected: false }, // ] console.log(accounts.identities); // [ // { // id: '1', // provider: 'GoogleAuthAdapter', // providerName: 'Google', // subject: 'google-user-123', // email: 'user@gmail.com', // fullName: 'John Doe', // avatarUrl: 'https://...' // } // ] ``` -------------------------------- ### Adapter User Info Requirements for External Identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/errors.md When external identities are enabled, the OAuth adapter must return `provider` and `subject` fields in the user info. Ensure custom adapters implement this. ```typescript { provider: 'GoogleAuthAdapter', subject: '123456789', email: 'user@gmail.com', // ... } ``` -------------------------------- ### Validate Plugin Configuration Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/api-reference/OAuthPlugin.md Validates the plugin's configuration after AdminForth resource discovery. This function ensures that the avatar upload plugin is correctly set up if an avatar field is specified in the resource configuration. ```typescript validateConfigAfterDiscover( adminforth: IAdminForth, resourceConfig: AdminForthResource ): void ``` -------------------------------- ### POST /oauth/external-identities Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/INDEX.md Lists all connected external identity accounts for a given user. This is useful for displaying linked accounts to the user. ```APIDOC ## POST /oauth/external-identities ### Description Lists all connected external identity accounts for a given user. This is useful for displaying linked accounts to the user. ### Method POST ### Endpoint /oauth/external-identities ### Parameters #### Request Body - **userId** (string) - Required - The ID of the user whose external identities are to be listed. ### Request Example ```json { "userId": "user_12345" } ``` ### Response #### Success Response (200) - **identities** (array) - A list of connected external identity objects. - **provider** (string) - The name of the OAuth provider (e.g., 'google', 'github'). - **externalUserId** (string) - The user's ID on the external provider. - **linkedAt** (string) - The timestamp when the account was linked. #### Response Example ```json { "identities": [ { "provider": "google", "externalUserId": "google_user_abc", "linkedAt": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Set OAuth Button Prefix Text Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Customize the prefix text for OAuth provider buttons. This text is combined with the provider's name to form the complete button label. ```typescript buttonText: 'Continue with' // → "Continue with Google", "Continue with GitHub" ``` ```typescript buttonText: 'Sign in with' // → "Sign in with Google" ``` ```typescript buttonText: 'Login via' // → "Login via Google" ``` -------------------------------- ### Configure User Avatar Field Source: https://github.com/devforth/adminforth-oauth/blob/main/_autodocs/configuration.md Specify a column name to store user avatars. The avatar is automatically downloaded and stored via the upload plugin if the field is empty. This option is not supported with OpenID adapters. ```typescript userAvatarField?: string ``` ```typescript userAvatarField: 'profilePicture' ```