@mycuppa/auth
v0.0.0
Published
Authentication utilities and helpers for Cuppa framework
Downloads
14
Maintainers
Readme
@mycuppa/auth
Authentication utilities and helpers for Cuppa framework.
Features
- Login/logout functionality
- Token management (access + refresh tokens)
- Token refresh logic with auto-refresh support
- User session persistence (localStorage/sessionStorage)
- Authentication state observers
- Protected route helpers
- Role-based access control (RBAC) utilities
- React hooks for easy integration
- TypeScript support with full type definitions
Installation
pnpm add @mycuppa/authUsage
Basic Setup
import { createAuthManager, useAuth } from '@mycuppa/auth'
// Create auth manager instance
const authManager = createAuthManager({
storageKey: 'my_app_auth',
storageType: 'localStorage',
autoRefresh: true,
refreshThreshold: 300000, // 5 minutes
onTokenRefresh: async (tokens) => {
// Call your API to refresh tokens
const response = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken: tokens.refreshToken }),
})
return response.json()
},
onLogout: async () => {
// Optional cleanup on logout
console.log('User logged out')
},
onError: (error) => {
// Optional error handling
console.error('Auth error:', error)
},
})React Hook Usage
import { useAuth } from '@mycuppa/auth'
function MyComponent() {
const {
user,
isAuthenticated,
isLoading,
login,
logout,
hasRole,
hasPermission,
} = useAuth(authManager)
const handleLogin = async () => {
const user = { id: '1', email: '[email protected]', roles: ['user'] }
const tokens = { accessToken: 'xxx', refreshToken: 'yyy' }
await login(user, tokens)
}
if (isLoading) return <div>Loading...</div>
if (!isAuthenticated) {
return <button onClick={handleLogin}>Login</button>
}
return (
<div>
<p>Welcome, {user?.email}</p>
<button onClick={logout}>Logout</button>
{hasRole('admin') && <AdminPanel />}
</div>
)
}Role-Based Access Control
// Check single role
if (authManager.hasRole('admin')) {
// User is an admin
}
// Check any of multiple roles
if (authManager.hasAnyRole(['admin', 'moderator'])) {
// User has at least one of these roles
}
// Check all roles
if (authManager.hasAllRoles(['user', 'verified'])) {
// User has all these roles
}
// Check permissions
if (authManager.hasPermission('write')) {
// User has write permission
}
if (authManager.hasAllPermissions(['read', 'write', 'delete'])) {
// User has all these permissions
}Protected Routes
// Check if user can access a route
const canAccess = authManager.canAccessRoute({
requireAuth: true,
requiredRoles: ['admin'],
requiredPermissions: ['read'],
})
if (!canAccess) {
// Redirect to login or show error
}Direct Auth Manager Usage (without React)
import { AuthManager } from '@mycuppa/auth'
const authManager = new AuthManager({
storageType: 'sessionStorage',
})
// Subscribe to auth state changes
const unsubscribe = authManager.subscribe((state) => {
console.log('Auth state changed:', state)
})
// Login
await authManager.login(user, tokens)
// Get current state
const state = authManager.getState()
// Get access token
const token = authManager.getAccessToken()
// Update user
authManager.updateUser({ name: 'New Name' })
// Logout
await authManager.logout()
// Cleanup
unsubscribe()
authManager.destroy()API Reference
AuthManager
Constructor Options
storageKey?: string- Storage key for tokens (default: 'cuppa_auth_tokens')storageType?: 'localStorage' | 'sessionStorage'- Storage type (default: 'localStorage')autoRefresh?: boolean- Enable automatic token refresh (default: false)refreshThreshold?: number- Time in ms before token refresh (default: 300000)onTokenRefresh?: (tokens: TokenPair) => Promise<TokenPair>- Token refresh handleronLogout?: () => void | Promise<void>- Logout callbackonError?: (error: Error) => void- Error handler
Methods
login(user: User, tokens: TokenPair): Promise<void>- Login userlogout(): Promise<void>- Logout userrefreshTokens(): Promise<TokenPair | null>- Refresh access tokensgetTokens(): TokenPair | null- Get current tokensgetAccessToken(): string | null- Get access tokenupdateUser(user: Partial<User>): void- Update user datagetState(): AuthState- Get current auth statesubscribe(observer: AuthStateObserver): () => void- Subscribe to state changeshasRole(role: string): boolean- Check if user has rolehasAnyRole(roles: string[]): boolean- Check if user has any rolehasAllRoles(roles: string[]): boolean- Check if user has all roleshasPermission(permission: string): boolean- Check if user has permissionhasAnyPermission(permissions: string[]): boolean- Check if user has any permissionhasAllPermissions(permissions: string[]): boolean- Check if user has all permissionscanAccessRoute(config: ProtectedRouteConfig): boolean- Check route accessdestroy(): void- Clean up resources
TypeScript
The package is written in TypeScript and includes full type definitions.
import type {
User,
TokenPair,
AuthState,
AuthConfig,
ProtectedRouteConfig,
} from '@mycuppa/auth'License
MIT
