@zytehub/auth-client
v1.3.0
Published
JavaScript API client for ZyteHub Authentication Service
Maintainers
Readme
@zytehub/auth-client
JavaScript API client for ZyteHub Authentication Service - a backend-as-a-service authentication solution.
Installation
npm install @zytehub/auth-clientQuick Start
const AuthClient = require('@zytehub/auth-client');
// Initialize the client
const client = new AuthClient({
apiUrl: 'https://api.example.com', // Your backend API URL
platformId: 'your-platform-id', // Your platform identifier (required for tracking)
timeout: 30000 // Request timeout in ms (default: 30000)
});
// Login
try {
const result = await client.login({
username: '[email protected]',
password: 'password123',
remember_device: true, // Optional: remember device for 30 days
device_fingerprint: '...', // Optional: device fingerprint
device_name: 'Chrome on Windows' // Optional: device name
});
// Tokens are automatically stored
console.log('Login successful!');
// Check if 2FA is required
if (result.requires_2fa) {
// Handle 2FA verification
}
} catch (error) {
console.error('Login failed:', error.message);
}Configuration
Constructor Options
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| apiUrl | string | Yes | - | Base URL of your authentication API (e.g., https://api.example.com) |
| platformId | string | No | - | Platform identifier for usage tracking. Required for proper analytics. |
| timeout | number | No | 30000 | Request timeout in milliseconds |
Platform ID
The platformId is crucial for:
- Usage Analytics: Track which platform users are logging in from
- Component Statistics: View platform-specific metrics in admin dashboard
- Security Auditing: Associate login events with specific platforms
Important: Always set platformId when initializing the client. This ensures your platform's usage is properly tracked.
Authentication Methods
Login
const result = await client.login({
username: '[email protected]', // Email or username
password: 'password123',
remember_device: true, // Optional: trust device for 30 days
device_fingerprint: '...', // Optional: device fingerprint
device_name: 'Chrome on Windows' // Optional: device name
});
// Response:
// {
// access: "jwt_access_token",
// refresh: "jwt_refresh_token",
// requires_2fa: false, // true if 2FA is enabled
// user: { ... }
// }Logout
// Clear tokens locally
client.logout();
// Logout all sessions (requires authentication)
await client.logoutAllSessions();
client.logout(); // Clear local tokensToken Management
// Get stored tokens
const tokens = client.getTokens();
// { access: "token", refresh: "refresh_token" }
// Set tokens manually (useful for SSR or custom flows)
client.setTokens(accessToken, refreshToken);
// Clear tokens
client.clearTokens();
// Refresh access token (automatically called on 401 errors)
await client.refreshAccessToken();Automatic Token Refresh: The client automatically refreshes expired access tokens when a 401 error occurs. Tokens are stored in localStorage (browser) or memory (Node.js).
Two-Factor Authentication (2FA)
Verify 2FA Code
const result = await client.verify2FA({
username: '[email protected]',
otp_token: '123456', // 6-digit code from authenticator app
remember_device: true, // Optional: trust device for 30 days
device_fingerprint: '...',
device_name: 'Chrome on Windows'
});
// Returns same structure as login() with access/refresh tokensSetup 2FA
// Get QR code and secret
const setup = await client.setup2FA();
// {
// qr_code: "data:image/png;base64,...",
// secret: "JBSWY3DPEHPK3PXP",
// provisioning_uri: "otpauth://totp/..."
// }
// Enable 2FA (after user scans QR code)
await client.enable2FA('123456'); // OTP code from authenticator appManage 2FA
// Disable 2FA (requires password)
await client.disable2FA('user_password');
// Generate backup codes
const codes = await client.generateBackupCodes();
// { backup_codes: ["code1", "code2", ...] }
// Login with backup code
const result = await client.verifyBackupCode({
username: '[email protected]',
backup_code: 'backup-code-here'
});Password Management
Request Password Reset
await client.requestPasswordReset('[email protected]');
// Sends reset email to userConfirm Password Reset
await client.confirmPasswordReset({
token: 'reset-token-from-email',
new_password: 'newSecurePassword123'
});Change Password (Authenticated)
await client.changePassword({
old_password: 'currentPassword',
new_password: 'newSecurePassword123'
});Email Verification
// Send verification email
await client.sendEmailVerification();
// Confirm email with token from email
await client.confirmEmailVerification('verification-token');User Management
Get Current User
const user = await client.getCurrentUser();
// {
// id: 1,
// username: "johndoe",
// email: "[email protected]",
// first_name: "John",
// last_name: "Doe",
// is_email_verified: true,
// has_2fa: false,
// ...
// }Update Profile
const updated = await client.updateProfile({
email: '[email protected]',
first_name: 'Jane',
last_name: 'Smith'
});Session Management
List Active Sessions
const sessions = await client.listSessions();
// [
// {
// id: "session-id",
// device_name: "Chrome on Windows",
// ip_address: "192.168.1.1",
// last_activity: "2024-01-15T10:30:00Z",
// is_current: true
// },
// ...
// ]Trusted Devices
// Get trusted devices
const devices = await client.getTrustedDevices();
// Remove trusted device
await client.removeTrustedDevice('device-id');Security & Compliance
Audit Logs
// Get user's security audit logs
const logs = await client.getAuditLogs({
limit: 50,
offset: 0,
event_type: 'login_success' // Optional filter
});
// [
// {
// id: 1,
// event_type: "login_success",
// timestamp: "2024-01-15T10:30:00Z",
// ip_address: "192.168.1.1",
// user_agent: "Mozilla/5.0...",
// metadata: { ... }
// },
// ...
// ]Account Deletion (GDPR)
await client.requestAccountDeletion('user_password');
// Initiates account deletion processError Handling
The client throws errors for failed requests. Always wrap API calls in try/catch:
try {
await client.login({ username, password });
} catch (error) {
if (error.message.includes('Invalid credentials')) {
// Handle invalid credentials
} else if (error.message.includes('Account locked')) {
// Handle locked account
} else if (error.code === 'TIMEOUT') {
// Handle timeout
} else {
// Handle other errors
console.error('Unexpected error:', error);
}
}Common Error Messages
"Invalid credentials"- Wrong username/password"Account locked"- Too many failed login attempts"2FA required"- User has 2FA enabled, need to verify"Request timeout after 30000ms"- Request took too long"No refresh token available"- Cannot refresh expired token
Advanced Usage
Custom Request Headers
The client automatically adds:
Authorization: Bearer <token>(if authenticated)X-Platform-ID: <platformId>(if provided)Content-Type: application/json
Request Timeout
const client = new AuthClient({
apiUrl: 'https://api.example.com',
timeout: 10000 // 10 seconds
});Server-Side Rendering (SSR)
For SSR, you may want to override token storage:
const client = new AuthClient({
apiUrl: 'https://api.example.com',
platformId: 'my-platform'
});
// Override setTokens to use cookies instead of localStorage
client.setTokens = function(access, refresh) {
this.token = access;
this.refreshToken = refresh;
// Set HTTP-only cookies via your server
};Platform Tracking
Critical: Always set platformId to ensure proper usage tracking:
// ✅ Correct - platform tracking enabled
const client = new AuthClient({
apiUrl: window.location.origin,
platformId: 'fireglue' // Your platform identifier
});
// ❌ Incorrect - no platform tracking
const client = new AuthClient({
apiUrl: window.location.origin
// Missing platformId!
});API Reference
Authentication
login(credentials)- Login with username/passwordlogout()- Clear local tokenslogoutAllSessions()- Logout all sessionsrefreshAccessToken()- Manually refresh access token
2FA
verify2FA(data)- Verify OTP codesetup2FA()- Get QR code for 2FA setupenable2FA(otpToken)- Enable 2FAdisable2FA(password)- Disable 2FAgenerateBackupCodes()- Generate backup codesverifyBackupCode(data)- Login with backup code
Password
requestPasswordReset(email)- Request password reset emailconfirmPasswordReset(data)- Confirm password resetchangePassword(data)- Change password (authenticated)
sendEmailVerification()- Send verification emailconfirmEmailVerification(token)- Confirm email
User
getCurrentUser()- Get current user profileupdateProfile(data)- Update user profile
Sessions
listSessions()- List active sessionsgetTrustedDevices()- Get trusted devicesremoveTrustedDevice(deviceId)- Remove trusted device
Security
getAuditLogs(filters)- Get security audit logsrequestAccountDeletion(password)- Request account deletion
Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
Node.js Support
Works in Node.js 14+ with node-fetch or similar fetch polyfill.
License
MIT
Support
For issues and questions:
- GitHub: https://github.com/zytehub/auth-client
- Documentation: https://docs.zytehub.com/auth
