saas-platform-auth-client
v1.5.1
Published
Authentication client for SaaS platform auth-service with password reset support
Maintainers
Readme
@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
npm install @saas-platform/auth-client @saas-platform/core-clientBasic Usage
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: '[email protected]',
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
const response = await authClient.login({
email: '[email protected]',
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
// 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
// Clear all stored tokens
authClient.logout();
console.log('Logged out:', !authClient.isAuthenticated());Password Recovery
// Request password reset
const forgotResponse = await authClient.forgotPassword({
email: '[email protected]',
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: '[email protected]',
resetCode: '123456', // 6-digit code from email
newPassword: 'newSecurePassword123',
saasId: 'your-saas-id'
});
if (resetResponse.success) {
console.log('Password reset successful:', resetResponse.data?.message);
}User Creation
Raw Password (Default)
const createUserResponse = await authClient.createUser({
name: 'João Silva',
email: '[email protected]',
password: 'minhasenha123', // Raw password - will be hashed automatically
isPasswordHashed: false, // Default, can be omitted
role: 'User',
phone: '11999999999',
documentNumber: '12345678900',
saasId: 'your-saas-id',
isActive: true
});
if (createUserResponse.success) {
console.log('User created:', createUserResponse.data?.userId);
}Pre-hashed Password
const createUserResponse = await authClient.createUser({
name: 'Maria Santos',
email: '[email protected]',
password: '$2a$11$...', // BCrypt hash already calculated
isPasswordHashed: true, // Indicates password is already hashed
role: 'Admin',
saasId: 'your-saas-id'
});
if (createUserResponse.success) {
console.log('User created with pre-hashed password:', createUserResponse.data?.userId);
}⚠️ Important: When
isPasswordHashed: true, ensure the password hash was generated using BCrypt with the same parameters as AuthService to guarantee compatibility during validation.
Admin Impersonation
// 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:
// 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
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:
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
// 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:
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
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
