VOOZH about

URL: https://deepwiki.com/auth0/wordpress/3.5-user-synchronization

⇱ User Synchronization | auth0/wordpress | DeepWiki


Loading...
Menu

User Synchronization

Purpose and Scope

This document describes the user synchronization system in the Auth0 WordPress plugin. The system maintains consistency between WordPress user accounts and Auth0 users by queuing user events and processing them asynchronously via WordPress cron jobs. This enables bidirectional synchronization where changes made in WordPress can be reflected in Auth0, and vice versa.

For information about user authentication and identity resolution during login, see Authentication Flow. For database schema details, see Database Schema.


System Overview

The synchronization system operates asynchronously using an event queue pattern. When WordPress user events occur (creation, update, deletion), the plugin queues these events in the auth0_sync database table. Background cron jobs periodically process the queue and synchronize changes to Auth0 via the Management API.


Sources: src/Actions/Authentication.php48-51 src/Actions/Sync.php14-283 src/Database.php29


Event Queue System

The auth0_sync Table

The auth0_sync table serves as the event queue for synchronization operations. Each row represents a pending synchronization event.

ColumnTypePurpose
idBIGINTAuto-increment primary key
siteTINYINTNetwork ID (for multisite)
blogBIGINTBlog ID (for multisite)
createdINT(11)Unix timestamp when event was queued
payloadTEXTJSON-encoded event data
hashsumVARCHAR(64)SHA-256 hash of payload (prevents duplicates)
lockedINT(1)Lock flag for processing

The table is created on-demand during plugin activation or when first accessed.

Sources: src/Database.php121-140

Event Payload Structure

Events are stored as JSON objects in the payload column with the following structure:


The connection field is only present for deletion events and contains the Auth0 sub claim.

Sources: src/Actions/Authentication.php283-286 src/Actions/Authentication.php604-607 src/Actions/Authentication.php323-327

Duplicate Prevention

The hashsum column contains a SHA-256 hash of the entire payload. Before inserting a new event, the system checks for existing rows with the same hash to prevent duplicate processing.


Sources: src/Actions/Authentication.php287-290 src/Actions/Authentication.php609-610 src/Actions/Authentication.php328-330


Event Generation

The Authentication action class registers WordPress hooks to capture user events and queue them for synchronization.

Registered Hooks

HookMethodArgumentsPurpose
edit_user_created_useronCreatedUser2User created via WordPress UI
profile_updateonUpdatedUser2User profile updated
deleted_useronDeletedUser1User deleted

Sources: src/Actions/Authentication.php48-50

User Creation Events

When a WordPress user is created (via the Admin → Users → Add New page), the onCreatedUser method queues a wp_user_created event. Note that this hook only fires for users created through WordPress's UI, not during authentication login.


Sources: src/Actions/Authentication.php264-308

User Update Events

The profile_update hook fires whenever a WordPress user is updated. The system queues a wp_user_updated event with the user ID.

Note that during authentication login, the plugin temporarily removes this hook when updating user email addresses to prevent circular synchronization:


Sources: src/Actions/Authentication.php525-527 src/Actions/Authentication.php591-628

User Deletion Events

When a WordPress user is deleted, the system first retrieves all associated Auth0 connections from the auth0_accounts table, then queues a wp_user_deleted event for each connection. Each event includes both the WordPress user ID and the Auth0 connection identifier.


Sources: src/Actions/Authentication.php310-350 src/Actions/Authentication.php90-109


Background Processing

Cron Schedule Configuration

The plugin registers two custom WordPress cron schedules:

Schedule NameConstantIntervalPurpose
AUTH0_SYNCCONST_SCHEDULE_BACKGROUND_SYNCConfigurable (default: 3600s)Process sync queue
AUTH0_MAINTENANCECONST_SCHEDULE_BACKGROUND_MAINTENANCE300s (5 minutes)Cleanup orphaned connections

The sync interval is configured via the auth0_sync[schedule] option in WordPress settings.

Sources: src/Actions/Sync.php29-34 src/Actions/Sync.php261-268

Cron Job Registration

The plugin uses the cron_schedules filter to register custom schedules and hooks into WordPress's cron system:

Cron HookMethodTrigger
AUTH0_CRON_SYNCSync::onBackgroundSyncEvery N minutes
AUTH0_CRON_MAINTENANCESync::onBackgroundMaintenanceEvery 5 minutes

Sources: src/Actions/Sync.php19-24 src/Actions/Sync.php39-43

Processing the Queue

The onBackgroundSync method processes events from the queue in batches:


The system processes up to 10 events per cron execution to avoid timeouts.

Sources: src/Actions/Sync.php214-254


Event Handlers

Configuration Gates

Each event type can be individually enabled or disabled via the auth0_sync_events configuration section:

OptionDatabase KeyDefaultPurpose
User Creationsync_events[user_creation]trueSync user creation events
User Deletionsync_events[user_deletion]trueSync user deletion events
User Updatessync_events[user_updates]trueSync user update events

Events are only processed if their corresponding option is enabled.

Sources: src/Actions/Configuration.php156-191 src/Actions/Sync.php225-229

User Creation Handler

The eventUserCreated method creates a corresponding Auth0 user when a WordPress user is created.

Flow:

  1. Retrieve WordPress user by ID
  2. Check if Auth0 user already exists (by email via management().usersByEmail().get())
  3. If not exists, create new Auth0 user with management().users().create()
  4. Generate random password for Auth0 user
  5. Trigger password change email via management().tickets().createPasswordChange()
  6. Store connection mapping in auth0_accounts table

Fields Synchronized:

  • namedisplay_name
  • nicknamenickname
  • given_nameuser_firstname
  • family_nameuser_lastname
  • emailuser_email
  • password ← randomly generated

Sources: src/Actions/Sync.php76-115

User Update Handler

The eventUserUpdated method synchronizes WordPress user changes to Auth0.

Flow:

  1. Retrieve WordPress user by ID
  2. Get all Auth0 connections for the user from auth0_accounts
  3. For each connection:
    • Fetch current Auth0 user data via management().users().get()
    • Update Auth0 user with management().users().update()
    • If email changed, trigger email verification via management().tickets().createEmailVerification()

Sources: src/Actions/Sync.php140-186

User Deletion Handler

The eventUserDeleted method deletes the Auth0 user when a WordPress user is deleted.

Flow:

  1. Verify the Auth0 connection has not been claimed by another WordPress user (check auth0_accounts)
  2. If connection is unclaimed, check if Auth0 user still exists via management().users().get()
  3. If exists, delete via management().users().delete()

This verification step prevents accidental deletion if the connection was reassigned to another user between event queueing and processing.

Sources: src/Actions/Sync.php117-138


Database Connection Requirement

All synchronization operations require a configured database connection ID. This is stored in the auth0_sync[database] option and must begin with the prefix con_.

The getDatabaseName method resolves the connection ID to its human-readable name via the Management API:


If no database connection is configured, synchronization is skipped but events remain in the queue.

Sources: src/Actions/Configuration.php117-123 src/Actions/Sync.php188-207 src/Actions/Sync.php231-232


Maintenance Tasks

Orphaned Connection Cleanup

The onBackgroundMaintenance method runs every 5 minutes to clean up orphaned connections in the auth0_accounts table. These occur when WordPress user deletion hooks fail to execute properly (e.g., due to errors or plugin conflicts).

Process:

  1. Query all distinct user IDs from auth0_accounts for current site/blog
  2. For each user ID, check if WordPress user exists via get_user_by('ID', $userId)
  3. If user doesn't exist, delete all connections via Authentication::deleteAccountConnections()

This prevents the auth0_accounts table from accumulating stale references that could interfere with future authentication flows.

Sources: src/Actions/Sync.php209-212 src/Actions/Sync.php49-74


Configuration Options

Sync Configuration Page

The sync settings are exposed in the WordPress admin under Auth0 → Sync. The configuration is stored in the auth0_sync and auth0_sync_events options.

SectionFieldDatabase KeyOptionsPurpose
syncDatabase Connectionsync[database]Text (must start with con_)Target Auth0 database connection
syncSync Frequencysync[schedule]0 (disabled) to 604800 (1 week)Cron interval in seconds
syncOn-Demand Changessync[push]disable / enable_email / enableReal-time push (degrades performance)
sync_eventsUser Creationsync_events[user_creation]true / falseEnable creation sync
sync_eventsUser Deletionsync_events[user_deletion]true / falseEnable deletion sync
sync_eventsUser Updatessync_events[user_updates]true / falseEnable update sync

Sources: src/Actions/Configuration.php110-192

On-Demand Push Mode

The sync[push] option allows real-time synchronization instead of background processing. This is not recommended as it degrades WordPress performance by making synchronous Auth0 API calls during user operations.

Values:

  • disable - Queue events only (recommended)
  • enable_email - Push email changes immediately
  • enable - Push all changes immediately

Sources: src/Actions/Configuration.php143-153


Integration with Authentication Flow

The synchronization system works in conjunction with the authentication flow to maintain account connections:

  1. During authentication callback (Authentication::onLogin), the plugin resolves the user identity and stores the Auth0 sub in auth0_accounts via createAccountConnection()
  2. When WordPress user events occur, the plugin uses getAccountConnections() to retrieve Auth0 identifiers for synchronization
  3. During deletion, deleteAccountConnections() removes mappings and queues deletion events

Sources: src/Actions/Authentication.php520-522 src/Actions/Authentication.php53-88 src/Actions/Authentication.php90-109 src/Actions/Authentication.php156-172


Error Handling

The synchronization system includes error handling at multiple levels:

  1. Duplicate Prevention: The hashsum column prevents duplicate event processing
  2. API Response Validation: The getResults() helper checks HTTP status codes before processing responses
  3. Null Checks: All event handlers verify data existence before API calls
  4. Connection Verification: Deletion events verify connections haven't been reassigned before deleting Auth0 users

If an error occurs during processing, the event is deleted from the queue without retry. This prevents infinite loops but means failed synchronizations require manual intervention.

Sources: src/Actions/Sync.php275-282 src/Actions/Sync.php123-127


SDK Configuration for Cron

When WordPress cron jobs execute, the plugin uses a minimal SDK configuration that excludes session management. This is detected via the DOING_CRON constant:


This prevents session-related overhead during background processing.

Sources: src/Plugin.php285-298