tab-authenticator
v1.0.2
Published
A universal authentication orchestrator that handles both online and offline authentication
Downloads
17
Maintainers
Readme
Tab Authenticator
A universal authentication orchestrator that handles both online and offline authentication, allowing users to create accounts and authenticate even when offline, with automatic synchronization when connectivity is restored.
Enhanced Features
- Real-time Synchronization Status: Detailed feedback about sync progress and status
- Conflict Resolution: Multiple strategies to resolve conflicts between offline and online data
- Enhanced Key Management: Sophisticated encryption key management for different users with rotation
- Migration Path: Clear transition from existing online accounts to offline capabilities
- Advanced Resource Caching: Configurable caching policies (cache-first, network-first, stale-while-revalidate)
- Offline Transaction Queue: Queue operations when offline and replay when connectivity is restored
- Enhanced Provider Support: Additional adapters for AWS Cognito, Okta, and Azure AD
- Performance Monitoring: Built-in analytics for tracking authentication performance and usage patterns
Features
- Universal Authentication: Works with various providers (Supabase, Firebase, Auth0, custom)
- Online/Offline Support: Automatic switching between online and offline modes
- Secure Encryption: AES encryption for sensitive data
- Local Storage: Caching with localforage for offline availability
- React Support: Context provider and hooks for React applications
- Vanilla JS Support: Works in any JavaScript environment
- Automatic Sync: Syncs authentication state when network is restored
Installation
npm install tab-authenticatorQuick Start
React Application
import React from 'react';
import { AuthProvider, useAuth } from 'tab-authenticator/react';
// Wrap your app with AuthProvider
const App = () => {
const authConfig = {
encryptionKey: 'choosen-encryption-key',
provider: 'supabase',
supabaseUrl: 'https://the-project.supabase.co',
supabaseKey: 'project-anon-key'
};
return (
<AuthProvider config={authConfig}>
<YourApp />
</AuthProvider>
);
};
// Use authentication in your components
const LoginComponent = () => {
const { login, isAuthenticated, getCurrentUser, loading, error } = useAuth();
const handleLogin = async () => {
const credentials = {
email: '[email protected]',
password: 'password123'
};
const result = await login(credentials);
if (!result.success) {
console.error('Login failed:', result.error);
}
};
if (loading) return <div>Loading...</div>;
return (
<div>
{error && <div>Error: {error}</div>}
{isAuthenticated() ? (
<div>Welcome, {getCurrentUser()?.email}!</div>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
};Vanilla JavaScript
import { TabAuth } from 'tab-authenticator';
// Initialize authentication
const auth = new TabAuth({
encryptionKey: 'the-encryption-key',
provider: 'supabase',
supabaseUrl: 'https://the-project.supabase.co',
supabaseKey: 'Project-anon-key'
});
// Set up event listeners
auth.on('login', (user) => {
console.log('User logged in:', user);
});
auth.on('networkChange', ({ isOnline }) => {
console.log(`Network status: ${isOnline ? 'Online' : 'Offline'}`);
});
// Perform authentication
const loginResult = await auth.login({
email: '[email protected]',
password: 'password123'
});
if (loginResult.success) {
console.log('Login successful');
console.log('Current user:', auth.getCurrentUser());
console.log('Is authenticated:', auth.isAuthenticated());
}Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| encryptionKey | string | 'default-encryption-key' | Key used for encrypting sensitive data |
| storagePrefix | string | 'tab_auth_' | Prefix for local storage keys |
| provider | string | 'default' | Authentication provider ('supabase', 'firebase', 'auth0', 'default') |
| syncInterval | number | 30000 | Interval (ms) for syncing authentication state |
| tokenExpiry | number | 3600 | Token expiry time in seconds |
Provider-Specific Options
Supabase
{
provider: 'supabase',
supabaseUrl: 'https://the-project.supabase.co',
supabaseKey: 'project-anon-key'
}Firebase
{
provider: 'firebase',
apiKey: 'the-api-key',
authDomain: 'your-project.firebaseapp.com'
}Auth0
{
provider: 'auth0',
domain: 'your-domain.auth0.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret'
}API Reference
AuthOrchestrator
The main authentication orchestrator class.
Methods
login(credentials)- Authenticate user with credentialssignup(credentials)- Create new user accountlogout()- Log out current userisAuthenticated()- Check if user is authenticatedgetCurrentUser()- Get current user objectisOffline()- Check if in offline modeauthenticateResource(resourceUrl)- Check access to resourcedestroy()- Clean up the orchestrator
React Hooks and Components
useAuth()
React hook that provides authentication state and methods.
Returns:
loading- Boolean indicating if auth state is loadingisAuthenticated- Function to check auth statusgetCurrentUser- Function to get current userisOffline- Function to check offline statuslogin(credentials)- Function to log in usersignup(credentials)- Function to sign up userlogout()- Function to log out userauthenticateResource(resourceUrl)- Function to authenticate resource access
<AuthProvider>
React context provider component.
Props:
config- Configuration object for the auth orchestrator
Vanilla JavaScript API
TabAuth class
The main class for vanilla JavaScript usage.
Methods are similar to AuthOrchestrator but with event system support.
Global window.TabAuth
When included via script tag, available as window.TabAuth.
Offline Functionality
The library provides seamless offline functionality:
- Automatic Mode Switching: When network is lost, automatically switches to offline mode
- Local Account Creation: Users can create accounts even when offline
- Local Authentication: Login works with locally stored credentials
- Sync on Reconnection: When network is restored, syncs with online provider
- Resource Access Control: Shows appropriate messages when resources require online access
Security Features
- AES encryption for sensitive authentication data
- PBKDF2 password hashing
- JWT-like tokens with expiration
- Secure random string generation
- Protection against common authentication vulnerabilities
Custom Providers
You can implement custom authentication providers by extending the BaseAdapter:
import { BaseAdapter } from 'tab-authenticator';
class CustomAuthProvider extends BaseAdapter {
constructor(config) {
super(config);
this.apiUrl = config.customApiUrl;
}
async login(credentials) {
// Implement custom login logic
}
async signup(credentials) {
// Implement custom signup logic
}
// ... implement other required methods
}Browser Support
- Modern browsers with ES6+ support
- Local storage support required for offline functionality
- Fetch API support for network requests
License
MIT
