Authentication
Lumenize provides flexible authentication options to secure your backend and manage user access across your applications.
Authentication Methods
Email/Password Authentication
The most common authentication method for web applications:
// Register a new userconst user = await client.auth.register({ email: 'user@example.com', password: 'securePassword123', name: 'John Doe'});
// Login existing userconst session = await client.auth.login({ email: 'user@example.com', password: 'securePassword123'});
// Access user dataconsole.log('Logged in as:', session.user.name);
OAuth Providers
Integrate with popular OAuth providers:
// Login with Googleconst session = await client.auth.loginWithProvider('google', { redirectTo: '/dashboard'});
// Login with GitHubconst session = await client.auth.loginWithProvider('github');
// Login with custom OAuth providerconst session = await client.auth.loginWithProvider('custom', { clientId: 'your-client-id', scope: 'email profile'});
Magic Links
Passwordless authentication via email:
// Send magic linkawait client.auth.sendMagicLink({ email: 'user@example.com', redirectTo: '/welcome'});
// Verify magic link (handled automatically on redirect)const session = await client.auth.verifyMagicLink(token);
API Key Authentication
For server-to-server communication:
const client = new LumenizeClient({ projectId: 'proj_abc123', apiKey: 'lum_live_xyz789', // Server API key authMode: 'api-key'});
// All requests authenticated with API keyconst users = await client.users.findMany();
Session Management
Session Lifecycle
// Check authentication statusconst isAuthenticated = client.auth.isAuthenticated();
// Get current sessionconst session = client.auth.getSession();
// Refresh session tokenawait client.auth.refreshToken();
// Logoutawait client.auth.logout();
Session Events
Listen for authentication state changes:
client.auth.onSessionChange((session) => { if (session) { console.log('User logged in:', session.user); // Redirect to dashboard window.location.href = '/dashboard'; } else { console.log('User logged out'); // Redirect to login window.location.href = '/login'; }});
// Listen for token refreshclient.auth.onTokenRefresh((newToken) => { console.log('Token refreshed');});
Token Storage
Configure how tokens are stored:
const client = new LumenizeClient({ projectId: 'proj_abc123', apiKey: 'lum_pub_xyz789', auth: { storage: 'localStorage', // 'localStorage', 'sessionStorage', 'memory' autoRefresh: true, // Automatically refresh tokens refreshThreshold: 300 // Refresh 5 minutes before expiry }});
User Management
User Registration
// Basic registrationconst user = await client.auth.register({ email: 'user@example.com', password: 'password123', name: 'John Doe'});
// Registration with custom fieldsconst user = await client.auth.register({ email: 'user@example.com', password: 'password123', profile: { firstName: 'John', lastName: 'Doe', company: 'Acme Corp', role: 'developer' }});
// Registration with email verificationconst user = await client.auth.register({ email: 'user@example.com', password: 'password123', requireEmailVerification: true});
Profile Management
// Get current user profileconst user = await client.auth.getCurrentUser();
// Update user profileconst updatedUser = await client.auth.updateProfile({ name: 'Jane Doe', avatar: 'https://example.com/avatar.jpg'});
// Change passwordawait client.auth.changePassword({ currentPassword: 'oldPassword', newPassword: 'newPassword123'});
// Change emailawait client.auth.changeEmail({ newEmail: 'newemail@example.com', password: 'currentPassword'});
Account Verification
// Send email verificationawait client.auth.sendEmailVerification();
// Verify email with tokenawait client.auth.verifyEmail(token);
// Check verification statusconst user = await client.auth.getCurrentUser();console.log('Email verified:', user.emailVerified);
Password Reset
Reset Flow
// Send reset password emailawait client.auth.sendPasswordReset({ email: 'user@example.com'});
// Reset password with tokenawait client.auth.resetPassword({ token: 'reset-token-from-email', newPassword: 'newSecurePassword123'});
Custom Reset Templates
Configure custom email templates:
// Configure in dashboard or via APIawait client.auth.updateEmailTemplates({ passwordReset: { subject: 'Reset your password', template: 'custom-reset-template', redirectUrl: 'https://myapp.com/reset-password' }});
Multi-Factor Authentication
TOTP (Time-based One-Time Passwords)
// Enable TOTP for userconst totpSetup = await client.auth.enableTOTP();console.log('QR Code URL:', totpSetup.qrCode);console.log('Manual entry key:', totpSetup.secret);
// Verify TOTP setupawait client.auth.verifyTOTP({ token: '123456' // 6-digit code from authenticator app});
// Login with TOTPconst session = await client.auth.login({ email: 'user@example.com', password: 'password123', totpToken: '123456'});
// Disable TOTPawait client.auth.disableTOTP({ password: 'currentPassword', totpToken: '123456'});
SMS Authentication
// Send SMS codeawait client.auth.sendSMSCode({ phoneNumber: '+1234567890'});
// Verify SMS codeconst session = await client.auth.verifySMSCode({ phoneNumber: '+1234567890', code: '123456'});
Role-Based Access Control
User Roles
// Assign role during registrationconst user = await client.auth.register({ email: 'admin@example.com', password: 'password123', role: 'admin'});
// Update user role (admin only)await client.auth.updateUserRole({ userId: 'user_123', role: 'moderator'});
// Check user permissionsconst user = await client.auth.getCurrentUser();const canManageUsers = user.permissions.includes('manage_users');
Permission Checks
// Client-side permission checkconst hasPermission = await client.auth.hasPermission('create_posts');
// Server-side middlewareconst requirePermission = (permission) => { return async (req, res, next) => { const user = await client.auth.getCurrentUser(); if (!user.permissions.includes(permission)) { return res.status(403).json({ error: 'Insufficient permissions' }); } next(); };};
Custom Authentication
Custom User Schema
Extend the default user schema:
{ "name": "User", "extends": "LumenizeUser", "fields": { "employeeId": { "type": "string", "unique": true }, "department": { "type": "reference", "entity": "Department" }, "preferences": { "type": "json" } }}
Custom Authentication Provider
Integrate with external identity providers:
// Custom JWT verificationconst client = new LumenizeClient({ projectId: 'proj_abc123', auth: { custom: { verifyToken: async (token) => { // Verify token with your identity provider const payload = await verifyJWT(token); return { userId: payload.sub, email: payload.email, permissions: payload.permissions }; } } }});
// Use custom tokenawait client.auth.setCustomToken(yourJWTToken);
Security Best Practices
Password Requirements
// Configure password policyawait client.auth.updatePasswordPolicy({ minLength: 8, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSymbols: true, maxAge: 90 // days});
Rate Limiting
// Configure auth rate limitsawait client.auth.updateRateLimits({ login: { attempts: 5, window: 900 // 15 minutes }, registration: { attempts: 3, window: 3600 // 1 hour }});
Session Security
const client = new LumenizeClient({ projectId: 'proj_abc123', auth: { session: { duration: 86400, // 24 hours refreshThreshold: 300, // 5 minutes secureCookies: true, // HTTPS only sameSite: 'strict' // CSRF protection } }});
Integration Examples
React Hook
import { useLumenizeAuth } from '@lumenize/react';
function LoginForm() { const { login, loading, error } = useLumenizeAuth();
const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(e.target);
try { await login({ email: formData.get('email'), password: formData.get('password') }); } catch (err) { console.error('Login failed:', err); } };
return ( <form onSubmit={handleSubmit}> <input name="email" type="email" required /> <input name="password" type="password" required /> <button type="submit" disabled={loading}> {loading ? 'Logging in...' : 'Login'} </button> {error && <p className="error">{error.message}</p>} </form> );}
Express.js Middleware
const { LumenizeClient } = require('@lumenize/node');
const client = new LumenizeClient({ projectId: process.env.LUMENIZE_PROJECT_ID, apiKey: process.env.LUMENIZE_API_KEY});
// Authentication middlewareconst authenticate = async (req, res, next) => { try { const token = req.headers.authorization?.replace('Bearer ', ''); const user = await client.auth.verifyToken(token); req.user = user; next(); } catch (error) { res.status(401).json({ error: 'Unauthorized' }); }};
// Protected routeapp.get('/api/profile', authenticate, (req, res) => { res.json({ user: req.user });});
Troubleshooting
Common Issues
Invalid credentials error:
try { await client.auth.login({ email, password });} catch (error) { if (error.code === 'INVALID_CREDENTIALS') { console.log('Email or password is incorrect'); }}
Token expired error:
client.auth.onError((error) => { if (error.code === 'TOKEN_EXPIRED') { // Redirect to login window.location.href = '/login'; }});
Rate limit exceeded:
try { await client.auth.login({ email, password });} catch (error) { if (error.code === 'RATE_LIMIT_EXCEEDED') { console.log('Too many attempts. Please try again later.'); }}
Next Steps
- Access Control - Learn about permissions and roles
- Real-time Features - Add live updates to your app
- Client Libraries - Explore client integrations