Privy Module
The privy module handles Privy authentication integration for Web3 and social login capabilities. Supports seamless user onboarding, multi-method authentication, and wallet address management.
Import
const privy = await brdzSDK.privy;
Methods Overview
| Method | Description | Auth Required | HTTP Endpoint |
|---|---|---|---|
loginWithPrivy | Login with Privy token | ❌ | POST /privy/auth/login |
linkPrivyAccount | Link Privy to existing user | ✅ | POST /privy/auth/link |
getPrivyProfile | Get current user's Privy profile | ✅ | GET /privy/auth/profile |
getUserPrivyProfile | Get specific user's Privy profile | ✅ | GET /privy/auth/profile/:user_id |
linkWalletAddress | Link wallet via Privy | ✅ | POST /privy/auth/link-wallet |
disconnectPrivyAuth | Disconnect Privy auth method | ✅ | DELETE /privy/auth/disconnect |
getHealthStatus | Check Privy service health | ✅ | GET /privy/health |
getStats | Get Privy usage statistics | ✅ | GET /privy/stats |
Method Details
loginWithPrivy
Authenticate user using Privy access token. Supports both new user registration and existing user login.
const loginResult = await privy.loginWithPrivy({
privy_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'
});
console.log('User ID:', loginResult.data.user.user_id);
console.log('Is new user:', loginResult.data.auth.is_new_user);
console.log('Auth method:', loginResult.data.auth.method);
Parameters:
privy_token(string, required): Privy access token from frontend authentication
Returns: User data, authentication info, and session data
Note: No BRDZ authentication required - this is the entry point for Privy users
linkPrivyAccount
Connect Privy authentication method to existing BRDZ user account.
const linkResult = await privy.linkPrivyAccount({
privy_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'
});
console.log('Linked provider:', linkResult.data.privy_mapping.auth_provider);
Parameters:
privy_token(string, required): Privy access token for the authentication method to link
Returns: User data and privy mapping information
Authentication: Requires valid BRDZ JWT token
getPrivyProfile
Get all connected Privy authentication methods for current authenticated user.
const profile = await privy.getPrivyProfile();
console.log('Total accounts:', profile.data.total_connected_accounts);
console.log('Connected methods:', profile.data.connected_accounts);
console.log('Primary auth:', profile.data.primary_auth);
Parameters: None (uses authenticated user context)
Returns: Complete Privy profile with all connected authentication methods
Authentication: Requires valid BRDZ JWT token
getUserPrivyProfile
Get Privy authentication methods for specific user (admin access or own profile).
const userProfile = await privy.getUserPrivyProfile("123");
console.log('User accounts:', userProfile.data.connected_accounts);
Parameters:
userId(string, required): User ID to get profile for
Returns: Privy profile for specified user
Authentication: Requires admin role or accessing own profile
linkWalletAddress
Connect crypto wallet address through Privy authentication.
const walletResult = await privy.linkWalletAddress({
privy_token: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...',
wallet_address: '0x1234567890123456789012345678901234567890'
});
console.log('Linked wallet:', walletResult.data.wallet_address);
Parameters:
privy_token(string, required): Privy access token containing wallet informationwallet_address(string, optional): Specific wallet address (uses first from token if not provided)
Returns: Wallet linking confirmation and details
Authentication: Requires valid BRDZ JWT token
disconnectPrivyAuth
Remove specific Privy authentication method from user account.
const disconnectResult = await privy.disconnectPrivyAuth({
privy_user_id: 'did:privy:987654321',
confirmation: 'disconnect'
});
console.log('Disconnected:', disconnectResult.data.disconnected_provider);
Parameters:
privy_user_id(string, required): Privy user ID of authentication method to removeconfirmation(string, required): Must be exactly "disconnect" for security
Returns: Disconnection confirmation and details
Authentication: Requires valid BRDZ JWT token
Security Note: Cannot disconnect primary/only authentication method
getHealthStatus
Check Privy service health and configuration status.
const health = await privy.getHealthStatus();
console.log('Service status:', health.data.status);
console.log('Configuration:', health.data.configuration);
Parameters: None
Returns: Service health, configuration status, and available endpoints
Authentication: Requires valid BRDZ JWT token
getStats
Get comprehensive Privy usage statistics and analytics.
const stats = await privy.getStats();
console.log('Total users:', stats.data.overview.total_privy_accounts);
console.log('Auth methods:', stats.data.auth_methods);
console.log('Recent activity:', stats.data.activity);
Parameters: None
Returns: Usage statistics, authentication method breakdown, and activity metrics
Authentication: Requires valid BRDZ JWT token (typically admin access)
Complete Integration Examples
New User Onboarding Flow
// Frontend: User completes Privy authentication
const privyToken = await privyAuth.authenticate();
// Backend: Login/register with Privy token
const loginResult = await privy.loginWithPrivy({
privy_token: privyToken
});
if (loginResult.data.auth.is_new_user) {
console.log('Welcome new user!');
// Handle new user onboarding
} else {
console.log('Welcome back!');
// Handle returning user flow
}
// Save session data for subsequent requests
const sessionData = loginResult.data.session;
Multi-Method Authentication Setup
// User already logged in with email, wants to add Google
const googleToken = await privyAuth.linkGoogle();
const linkResult = await privy.linkPrivyAccount({
privy_token: googleToken
});
console.log(`${linkResult.data.privy_mapping.auth_provider} linked successfully`);
// Check updated profile
const profile = await privy.getPrivyProfile();
console.log(`Total methods: ${profile.data.total_connected_accounts}`);
Wallet Integration Workflow
// Connect wallet for Web3 features
const walletToken = await privyAuth.connectWallet();
const walletResult = await privy.linkWalletAddress({
privy_token: walletToken
});
console.log('Wallet connected:', walletResult.data.wallet_address);
// Wallet can now be used for:
// - Web3 authentication
// - Crypto transactions
// - NFT operations
// - DeFi interactions
Profile Management
// View all connected authentication methods
const profile = await privy.getPrivyProfile();
profile.data.connected_accounts.forEach(account => {
console.log(`${account.provider}: ${account.status}`);
if (account.wallet_address) {
console.log(` Wallet: ${account.wallet_address}`);
}
});
// Remove unwanted authentication method
if (profile.data.total_connected_accounts > 1) {
await privy.disconnectPrivyAuth({
privy_user_id: 'did:privy:unwanted123',
confirmation: 'disconnect'
});
}
Admin Monitoring
// Check service health
const health = await privy.getHealthStatus();
if (health.data.status === 'degraded') {
console.log('Configuration issues:', health.data.issues);
}
// Get usage statistics
const stats = await privy.getStats();
console.log('Service metrics:');
console.log(`- Total accounts: ${stats.data.overview.total_privy_accounts}`);
console.log(`- Active 24h: ${stats.data.activity.active_last_24h}`);
console.log(`- New accounts 30d: ${stats.data.activity.new_accounts_30d}`);
// Auth method popularity
Object.entries(stats.data.auth_methods).forEach(([method, count]) => {
console.log(`- ${method}: ${count} users`);
});
Authentication Methods Supported
Via Privy integration:
- Email/Password: Traditional email authentication
- Social Logins: Google, Twitter, Discord
- Crypto Wallets: MetaMask, WalletConnect, other Web3 wallets
- Multi-Method: Users can connect multiple methods
- Primary/Secondary: One method designated as primary
Error Handling
try {
const result = await privy.loginWithPrivy({
privy_token: 'invalid_token'
});
} catch (error) {
if (error.message.includes('AUTHENTICATION_FAILED')) {
console.error('Invalid Privy token');
} else if (error.message.includes('MISSING_TOKEN')) {
console.error('Privy token required');
}
}
// Profile access control
try {
const profile = await privy.getUserPrivyProfile("999");
} catch (error) {
if (error.message.includes('FORBIDDEN')) {
console.error('Admin access required or accessing own profile only');
}
}
// Disconnection security
try {
await privy.disconnectPrivyAuth({
privy_user_id: 'did:privy:123',
confirmation: 'wrong'
});
} catch (error) {
if (error.message.includes('CONFIRMATION_REQUIRED')) {
console.error('Must provide exact confirmation: "disconnect"');
}
}
Security Features
- Token Validation: All Privy tokens verified before creating sessions
- Access Control: Users can only manage their own authentication methods
- Confirmation Required: Explicit confirmation needed for method removal
- Admin Oversight: Administrators can view user authentication profiles
- Primary Method Protection: Cannot remove only/primary authentication method
Authentication Requirements
// Configure SDK before using authenticated methods
const config = await brdzSDK.config;
config.setToken('your-brdz-jwt-token');
config.setApiKey('your-api-key');
// Public methods (no auth required)
await privy.loginWithPrivy({ privy_token: 'token' });
// Authenticated methods (JWT token required)
await privy.linkPrivyAccount({ privy_token: 'token' });
await privy.getPrivyProfile();
await privy.linkWalletAddress({ privy_token: 'token' });
await privy.disconnectPrivyAuth({ privy_user_id: 'id', confirmation: 'disconnect' });
await privy.getHealthStatus();
await privy.getStats(); // Admin access typically required