saas-platform-auth-client
Version:
Authentication client for SaaS platform auth-service with password reset support
288 lines (226 loc) • 6.44 kB
Markdown
# @saas-platform/auth-client
TypeScript/JavaScript client for SaaS platform authentication service.
## Features
- 🔐 **Complete Auth Flow** - Login, token refresh, validation, logout
- 🔄 **Password Recovery** - Forgot password and reset with email verification
- 🚀 **Automatic Token Management** - Built-in token storage and refresh
- 📦 **TypeScript Support** - Full type safety with Zod validation
- 🎯 **SaaS Isolation** - Automatic SaasId handling in JWT tokens
- 👤 **Admin Impersonation** - Admin login as other users
- 💾 **Persistent Sessions** - Token storage in localStorage
- 📧 **Email Integration** - Secure password reset with 15-minute expiration
## Installation
```bash
npm install @saas-platform/auth-client @saas-platform/core-client
```
## Basic Usage
```typescript
import { AuthClient } from '@saas-platform/auth-client';
const authClient = new AuthClient({
saasId: 'your-saas-id',
authServiceUrl: 'http://localhost:8000',
timeout: 30000
});
// Login
const loginResponse = await authClient.login({
email: 'user@example.com',
password: 'password123',
saasId: 'your-saas-id'
});
if (loginResponse.success) {
console.log('Logged in:', loginResponse.data?.user);
// Tokens are automatically stored and managed
console.log('Authenticated:', authClient.isAuthenticated());
}
```
## Authentication Methods
### Login
```typescript
const response = await authClient.login({
email: 'user@example.com',
password: 'password123',
saasId: 'your-saas-id'
});
if (response.success) {
const user = response.data?.user;
const tokens = {
accessToken: response.data?.accessToken,
refreshToken: response.data?.refreshToken,
expiresIn: response.data?.expiresIn
};
}
```
### Token Validation
```typescript
// Check if current token is valid
const validation = await authClient.validateToken();
if (validation.success) {
console.log('Token is valid:', validation.data?.isValid);
console.log('User info:', validation.data?.user);
}
```
### Logout
```typescript
// Clear all stored tokens
authClient.logout();
console.log('Logged out:', !authClient.isAuthenticated());
```
### Password Recovery
```typescript
// Request password reset
const forgotResponse = await authClient.forgotPassword({
email: 'user@example.com',
saasId: 'your-saas-id'
});
if (forgotResponse.success) {
console.log('Reset email sent:', forgotResponse.data?.message);
console.log('Code expires at:', forgotResponse.data?.expiresAt);
}
// Reset password with verification code
const resetResponse = await authClient.resetPassword({
email: 'user@example.com',
resetCode: '123456', // 6-digit code from email
newPassword: 'newSecurePassword123',
saasId: 'your-saas-id'
});
if (resetResponse.success) {
console.log('Password reset successful:', resetResponse.data?.message);
}
```
### Admin Impersonation
```typescript
// Login as another user (requires admin permissions)
const impersonation = await authClient.adminLogin({
userId: 'user-guid-to-impersonate',
saasId: 'target-saas-id'
});
if (impersonation.success) {
console.log('Impersonating user:', impersonation.data?.user);
}
```
## Token Management
The client automatically handles token lifecycle:
```typescript
// Check authentication status
const isAuth = authClient.isAuthenticated();
// Get current user from token
const currentUser = authClient.getCurrentUser();
// Returns: { id, email, saasId, role }
// Get token information
const accessToken = authClient.getAccessToken();
const refreshToken = authClient.getRefreshToken();
const isExpired = authClient.isTokenExpired();
// Get user/saas info from token
const userId = authClient.getUserId();
const saasId = authClient.getSaasId();
```
## Health Check
```typescript
const health = await authClient.getHealth();
if (health.success) {
console.log('Service status:', health.data?.status);
console.log('Uptime:', health.data?.uptime);
}
```
## Error Handling
All methods return a standardized response:
```typescript
const response = await authClient.login(credentials);
if (!response.success) {
console.error('Login failed:', response.error?.message);
switch (response.error?.code) {
case 'INVALID_CREDENTIALS':
// Handle wrong email/password
break;
case 'SAAS_ID_REQUIRED':
// Handle missing saasId
break;
case 'NETWORK_ERROR':
// Handle connection issues
break;
}
}
```
## Integration with React
```typescript
// React hook example
import { useState, useEffect } from 'react';
import { AuthClient } from '@saas-platform/auth-client';
const useAuth = () => {
const [authClient] = useState(() => new AuthClient(config));
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [user, setUser] = useState(null);
useEffect(() => {
setIsAuthenticated(authClient.isAuthenticated());
setUser(authClient.getCurrentUser());
}, [authClient]);
const login = async (credentials) => {
const response = await authClient.login(credentials);
if (response.success) {
setIsAuthenticated(true);
setUser(authClient.getCurrentUser());
}
return response;
};
const logout = () => {
authClient.logout();
setIsAuthenticated(false);
setUser(null);
};
return {
authClient,
isAuthenticated,
user,
login,
logout
};
};
```
## TypeScript Types
The client includes complete TypeScript definitions:
```typescript
interface LoginRequest {
email: string;
password: string;
saasId: string;
}
interface LoginResponse {
accessToken: string;
refreshToken: string;
expiresIn: number;
tokenType: 'Bearer';
user: {
id: string;
email: string;
name: string;
role: string;
saasId: string;
isActive: boolean;
};
}
interface ForgotPasswordRequest {
email: string;
saasId: string;
}
interface ResetPasswordRequest {
email: string;
resetCode: string; // 6-digit numeric code
newPassword: string;
saasId: string;
}
interface PasswordResetResponse {
success: boolean;
message: string;
expiresAt?: string; // ISO 8601 timestamp
}
```
## Configuration
```typescript
interface AuthClientConfig {
saasId: string; // Your SaaS identifier
authServiceUrl: string; // Auth service URL (e.g., 'http://localhost:8000')
timeout?: number; // Request timeout in milliseconds (default: 30000)
}
```
## License
MIT