class AuthClient {
constructor(apiKey, baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.token = localStorage.getItem('authToken');
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const headers = {
'x-api-key': this.apiKey,
'Content-Type': 'application/json',
...options.headers,
};
if (this.token && !options.skipAuth) {
headers.Authorization = `Bearer ${this.token}`;
}
const response = await fetch(url, {
...options,
headers,
});
if (!response.ok) {
throw new Error(`API Error: ${response.statusText}`);
}
return response.json();
}
async register(userData) {
const result = await this.request('/api/auth/register', {
method: 'POST',
body: JSON.stringify(userData),
skipAuth: true,
});
return result;
}
async login(email, password, appId) {
const result = await this.request('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password, appId }),
skipAuth: true,
});
if (result.accessToken) {
this.token = result.accessToken;
localStorage.setItem('authToken', this.token);
}
return result;
}
async getProfile() {
return this.request('/api/user/profile');
}
async updateProfile(profileData) {
return this.request('/api/user/profile', {
method: 'PATCH',
body: JSON.stringify(profileData),
});
}
async changePassword(passwordData) {
return this.request('/api/user/change-password', {
method: 'POST',
body: JSON.stringify(passwordData),
});
}
async listUsers(options = {}) {
const params = new URLSearchParams(options);
return this.request(`/api/users?${params}`);
}
async updateUserRole(userId, role, appId) {
return this.request(`/api/user/${userId}/role`, {
method: 'PATCH',
body: JSON.stringify({ role, appId }),
});
}
logout() {
this.token = null;
localStorage.removeItem('authToken');
}
}
// Usage Examples
const auth = new AuthClient('your-api-key', 'https://your-auth-server.com');
// Register a new user
await auth.register({
email: 'user@example.com',
password: 'securepassword123',
confirmPassword: 'securepassword123',
firstName: 'John',
lastName: 'Doe',
appId: 'your-app-id'
});
// Login
await auth.login('user@example.com', 'securepassword123', 'your-app-id');
// Get user profile
const profile = await auth.getProfile();
// Update profile
await auth.updateProfile({ firstName: 'Jane' });
// Admin operations (requires admin role)
const users = await auth.listUsers({ page: 1, limit: 10 });
await auth.updateUserRole('user123', 'moderator', 'your-app-id');import requests
from typing import Optional, Dict, Any
class AuthClient:
def __init__(self, api_key: str, base_url: str):
self.api_key = api_key
self.base_url = base_url
self.token: Optional[str] = None
def _request(self, endpoint: str, method: str = 'GET',
data: Optional[Dict] = None, skip_auth: bool = False) -> Dict[str, Any]:
url = f"{self.base_url}{endpoint}"
headers = {
'x-api-key': self.api_key,
'Content-Type': 'application/json'
}
if self.token and not skip_auth:
headers['Authorization'] = f'Bearer {self.token}'
response = requests.request(method, url, headers=headers, json=data)
response.raise_for_status()
return response.json()
def register(self, user_data: Dict[str, str]) -> Dict[str, Any]:
return self._request('/api/auth/register', 'POST', user_data, skip_auth=True)
def login(self, email: str, password: str, app_id: str) -> Dict[str, Any]:
data = {'email': email, 'password': password, 'appId': app_id}
result = self._request('/api/auth/login', 'POST', data, skip_auth=True)
if 'accessToken' in result:
self.token = result['accessToken']
return result
def get_profile(self) -> Dict[str, Any]:
return self._request('/api/user/profile')
def update_profile(self, profile_data: Dict[str, str]) -> Dict[str, Any]:
return self._request('/api/user/profile', 'PATCH', profile_data)
def change_password(self, password_data: Dict[str, str]) -> Dict[str, Any]:
return self._request('/api/user/change-password', 'POST', password_data)
def list_users(self, **options) -> Dict[str, Any]:
params = '&'.join([f"{k}={v}" for k, v in options.items()])
endpoint = f'/api/users?{params}' if params else '/api/users'
return self._request(endpoint)
def update_user_role(self, user_id: str, role: str, app_id: str) -> Dict[str, Any]:
data = {'role': role, 'appId': app_id}
return self._request(f'/api/user/{user_id}/role', 'PATCH', data)
def logout(self):
self.token = None
# Usage Examples
auth = AuthClient('your-api-key', 'https://your-auth-server.com')
# Register a new user
auth.register({
'email': 'user@example.com',
'password': 'securepassword123',
'confirmPassword': 'securepassword123',
'firstName': 'John',
'lastName': 'Doe',
'appId': 'your-app-id'
})
# Login
auth.login('user@example.com', 'securepassword123', 'your-app-id')
# Get user profile
profile = auth.get_profile()
# Update profile
auth.update_profile({'firstName': 'Jane'})
# Admin operations (requires admin role)
users = auth.list_users(page=1, limit=10)
auth.update_user_role('user123', 'moderator', 'your-app-id'){
"error": "Invalid input",
"details": [
{
"code": "invalid_enum_value",
"expected": ["user", "admin", "moderator", "member"],
"received": "invalid_role",
"path": ["role"],
"message": "Invalid enum value. Expected 'user' | 'admin' | 'moderator' | 'member', received 'invalid_role'"
}
]
}try {
const result = await auth.updateUserRole('user123', 'invalid_role', 'app-id');
} catch (error) {
if (error.response?.status === 400) {
console.error('Validation error:', error.response.data.details);
} else if (error.response?.status === 403) {
console.error('Permission denied - admin role required');
} else {
console.error('Unexpected error:', error.message);
}
}