npm package: @mycuppa/auth
Description: Authentication utilities and helpers for Cuppa framework
Author: Cuppa Platform Team
Latest version: 0.0.0

# @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

```bash
pnpm add @mycuppa/auth
```

## Usage

### Basic Setup

```typescript
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

```typescript
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: 'user@example.com', 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

```typescript
// 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

```typescript
// 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)

```typescript
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 handler
- `onLogout?: () => void | Promise<void>` - Logout callback
- `onError?: (error: Error) => void` - Error handler

#### Methods

- `login(user: User, tokens: TokenPair): Promise<void>` - Login user
- `logout(): Promise<void>` - Logout user
- `refreshTokens(): Promise<TokenPair | null>` - Refresh access tokens
- `getTokens(): TokenPair | null` - Get current tokens
- `getAccessToken(): string | null` - Get access token
- `updateUser(user: Partial<User>): void` - Update user data
- `getState(): AuthState` - Get current auth state
- `subscribe(observer: AuthStateObserver): () => void` - Subscribe to state changes
- `hasRole(role: string): boolean` - Check if user has role
- `hasAnyRole(roles: string[]): boolean` - Check if user has any role
- `hasAllRoles(roles: string[]): boolean` - Check if user has all roles
- `hasPermission(permission: string): boolean` - Check if user has permission
- `hasAnyPermission(permissions: string[]): boolean` - Check if user has any permission
- `hasAllPermissions(permissions: string[]): boolean` - Check if user has all permissions
- `canAccessRoute(config: ProtectedRouteConfig): boolean` - Check route access
- `destroy(): void` - Clean up resources

## TypeScript

The package is written in TypeScript and includes full type definitions.

```typescript
import type {
  User,
  TokenPair,
  AuthState,
  AuthConfig,
  ProtectedRouteConfig,
} from '@mycuppa/auth'
```

## License

MIT