|
| 1 | +/** |
| 2 | + * Example 1: Basic Authentication |
| 3 | + * |
| 4 | + * This example shows how to use the auth extension with AgentOS for basic |
| 5 | + * JWT authentication and subscription management. |
| 6 | + */ |
| 7 | + |
| 8 | +import { AgentOS } from '@framers/agentos'; |
| 9 | +import { createAuthExtension } from '@framers/agentos-extensions/auth'; |
| 10 | + |
| 11 | +async function main() { |
| 12 | + console.log('=== Example 1: Basic Authentication ===\n'); |
| 13 | + |
| 14 | + // 1. Create auth extension with configuration |
| 15 | + const { authService, subscriptionService } = createAuthExtension({ |
| 16 | + auth: { |
| 17 | + jwtSecret: process.env.JWT_SECRET || 'demo-secret-change-in-production', |
| 18 | + jwtExpiresIn: '7d', |
| 19 | + bcryptSaltRounds: 12, |
| 20 | + }, |
| 21 | + subscription: { |
| 22 | + defaultTier: 'free', |
| 23 | + tiers: [ |
| 24 | + { name: 'free', level: 0, features: [], isActive: true }, |
| 25 | + { name: 'pro', level: 1, features: ['FEATURE_ADVANCED_SEARCH'], isActive: true }, |
| 26 | + ], |
| 27 | + }, |
| 28 | + }); |
| 29 | + |
| 30 | + // 2. Initialize AgentOS with auth services |
| 31 | + const agentos = new AgentOS(); |
| 32 | + await agentos.initialize({ |
| 33 | + authService, |
| 34 | + subscriptionService, |
| 35 | + // ... other AgentOS config |
| 36 | + }); |
| 37 | + |
| 38 | + console.log('✓ AgentOS initialized with auth extension\n'); |
| 39 | + |
| 40 | + // 3. User Registration Flow |
| 41 | + console.log('--- User Registration ---'); |
| 42 | + const userId = 'user-123'; |
| 43 | + const email = 'user@example.com'; |
| 44 | + const password = 'secure-password-123'; |
| 45 | + |
| 46 | + // Hash password for storage |
| 47 | + const passwordHash = await authService.hashPassword!(password); |
| 48 | + console.log(`✓ Password hashed for user: ${email}`); |
| 49 | + |
| 50 | + // 4. User Login Flow |
| 51 | + console.log('\n--- User Login ---'); |
| 52 | + |
| 53 | + // Verify password |
| 54 | + const isPasswordValid = await authService.verifyPassword!(password, passwordHash); |
| 55 | + if (!isPasswordValid) { |
| 56 | + throw new Error('Invalid password'); |
| 57 | + } |
| 58 | + console.log('✓ Password verified'); |
| 59 | + |
| 60 | + // Generate JWT token |
| 61 | + const token = authService.generateToken!(userId, { |
| 62 | + email, |
| 63 | + roles: ['user'], |
| 64 | + tier: 'pro', |
| 65 | + }); |
| 66 | + console.log('✓ JWT token generated:', token.substring(0, 20) + '...'); |
| 67 | + |
| 68 | + // 5. Token Validation (on subsequent requests) |
| 69 | + console.log('\n--- Token Validation ---'); |
| 70 | + const authenticatedUser = await authService.validateToken(token); |
| 71 | + if (!authenticatedUser) { |
| 72 | + throw new Error('Token validation failed'); |
| 73 | + } |
| 74 | + |
| 75 | + console.log('✓ User authenticated:'); |
| 76 | + console.log(' - ID:', authenticatedUser.id); |
| 77 | + console.log(' - Email:', authenticatedUser.email); |
| 78 | + console.log(' - Tier:', authenticatedUser.tier); |
| 79 | + |
| 80 | + // 6. Check Subscription Tier |
| 81 | + console.log('\n--- Subscription Check ---'); |
| 82 | + subscriptionService.setUserTier!(userId, 'pro'); |
| 83 | + const tier = await subscriptionService.getUserSubscription(userId); |
| 84 | + |
| 85 | + console.log('✓ User subscription tier:'); |
| 86 | + console.log(' - Name:', tier?.name); |
| 87 | + console.log(' - Level:', tier?.level); |
| 88 | + console.log(' - Features:', tier?.features?.join(', ') || 'none'); |
| 89 | + |
| 90 | + // 7. Feature Access Check |
| 91 | + const hasAdvancedSearch = await subscriptionService.validateAccess( |
| 92 | + userId, |
| 93 | + 'FEATURE_ADVANCED_SEARCH' |
| 94 | + ); |
| 95 | + console.log(' - Advanced Search:', hasAdvancedSearch ? '✓ Allowed' : '✗ Denied'); |
| 96 | + |
| 97 | + // 8. Token Refresh |
| 98 | + console.log('\n--- Token Refresh ---'); |
| 99 | + const refreshedToken = await authService.refreshToken!(token); |
| 100 | + if (refreshedToken) { |
| 101 | + console.log('✓ Token refreshed:', refreshedToken.substring(0, 20) + '...'); |
| 102 | + } else { |
| 103 | + console.log('ℹ Token not yet in refresh window'); |
| 104 | + } |
| 105 | + |
| 106 | + // 9. Token Revocation (logout) |
| 107 | + console.log('\n--- Logout ---'); |
| 108 | + await authService.revokeToken!(token); |
| 109 | + const afterRevocation = await authService.validateToken(token); |
| 110 | + console.log('✓ Token revoked:', afterRevocation === null ? 'success' : 'failed'); |
| 111 | + |
| 112 | + console.log('\n✅ Basic auth example complete!'); |
| 113 | +} |
| 114 | + |
| 115 | +main().catch((error) => { |
| 116 | + console.error('Error:', error); |
| 117 | + process.exit(1); |
| 118 | +}); |
| 119 | + |
0 commit comments