Users Module
The Users module provides access to user profile information, preferences, and management within the EnterpriseAI platform. It supports retrieving current user context, managing user profiles, and accessing tenant-specific user data.
Basic Usage
import { PlatformClient } from '@enterpriseaigroup/platform-sdk';
const client = new PlatformClient({ /* config */ });
// Get current user
const currentUser = await client.users.getCurrent();
console.log(`Welcome, ${currentUser.name}!`);
// Get user by ID
const user = await client.users.getById('user_123');
// Update user profile
const updated = await client.users.update('user_123', {
preferences: { theme: 'dark', notifications: true }
});
// List users in tenant
const users = await client.users.list({ role: 'admin' });
Methods
getCurrent()
Get the profile of the currently authenticated user.
getCurrent(): Promise<User>
Returns
interface User {
id: string;
email: string;
name: string;
avatar?: string;
role: string;
permissions: string[];
tenantId: string;
preferences?: UserPreferences;
metadata?: Record<string, any>;
createdAt: string;
lastLoginAt: string;
}
Example
const user = await client.users.getCurrent();
console.log(`User ID: ${user.id}`);
console.log(`Email: ${user.email}`);
console.log(`Role: ${user.role}`);
console.log(`Permissions: ${user.permissions.join(', ')}`);
if (user.preferences?.theme) {
console.log(`Theme: ${user.preferences.theme}`);
}
getById()
Get a user profile by ID.
getById(userId: string): Promise<User>
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
userId | string | Yes | User ID |
Example
const user = await client.users.getById('user_456');
console.log(`${user.name} (${user.email})`);
list()
List users in the tenant with filtering.
list(options?: UserListOptions): Promise<UserList>
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
role | string | No | Filter by role |
status | 'active' | 'inactive' | No | Filter by status |
search | string | No | Search by name or email |
limit | number | No | Maximum results (default: 50) |
offset | number | No | Pagination offset |
Returns
interface UserList {
data: User[];
total: number;
hasMore: boolean;
}
Example
const admins = await client.users.list({
role: 'admin',
status: 'active',
limit: 100
});
console.log(`Found ${admins.total} active admins`);
admins.data.forEach(admin => {
console.log(`- ${admin.name} (${admin.email})`);
});
update()
Update a user's profile or preferences.
update(userId: string, updates: Partial<User>): Promise<User>
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
userId | string | Yes | User ID |
updates | Partial<User> | Yes | Fields to update |
Example
// Update preferences
const updated = await client.users.update('user_123', {
preferences: {
theme: 'dark',
language: 'en',
notifications: {
email: true,
push: false
}
}
});
// Update profile information
const profile = await client.users.update('user_123', {
name: 'Jane Smith',
avatar: 'https://example.com/avatar.jpg',
metadata: {
department: 'Engineering',
title: 'Senior Developer'
}
});
updateCurrent()
Update the current user's profile (convenience method).
updateCurrent(updates: Partial<User>): Promise<User>
Example
const updated = await client.users.updateCurrent({
preferences: {
theme: 'dark',
timezone: 'America/New_York'
}
});
User Interface
User Type
interface User {
id: string; // Unique user identifier
email: string; // Email address
name: string; // Display name
avatar?: string; // Avatar URL
role: string; // Primary role (admin, user, etc.)
permissions: string[]; // Specific permissions
tenantId: string; // Associated tenant
status: 'active' | 'inactive'; // Account status
preferences?: UserPreferences; // User preferences
metadata?: Record<string, any>; // Custom metadata
createdAt: string; // ISO 8601 timestamp
lastLoginAt: string; // ISO 8601 timestamp
updatedAt: string; // ISO 8601 timestamp
}
UserPreferences Type
interface UserPreferences {
theme?: 'light' | 'dark' | 'auto';
language?: string; // ISO 639-1 code (e.g., 'en', 'es')
timezone?: string; // IANA timezone (e.g., 'America/New_York')
notifications?: {
email?: boolean;
push?: boolean;
inApp?: boolean;
frequency?: 'realtime' | 'daily' | 'weekly';
};
display?: {
density?: 'compact' | 'normal' | 'comfortable';
sidebarCollapsed?: boolean;
defaultView?: string;
};
custom?: Record<string, any>; // Application-specific preferences
}
Permissions
Users have role-based permissions that control access to resources and operations:
const user = await client.users.getCurrent();
// Check specific permission
if (user.permissions.includes('resources.create')) {
console.log('User can create resources');
}
// Check multiple permissions
const hasAllPermissions = ['resources.read', 'resources.update'].every(
perm => user.permissions.includes(perm)
);
// Common permissions
const commonPermissions = [
'resources.read',
'resources.create',
'resources.update',
'resources.delete',
'documents.upload',
'chat.access',
'users.manage',
'admin.access'
];
User Context
The user context is automatically included in all API requests:
// Resources are filtered by user permissions
const projects = await client.resources.list({ type: 'project' });
// Returns only projects the user can access
// Chat responses are personalized
const response = await client.chat.sendMessage('Show my projects');
// AI understands "my" refers to the current user
Preferences Management
Getting Preferences
const user = await client.users.getCurrent();
const theme = user.preferences?.theme || 'light';
const language = user.preferences?.language || 'en';
Setting Preferences
await client.users.updateCurrent({
preferences: {
theme: 'dark',
language: 'es',
timezone: 'Europe/Madrid',
notifications: {
email: true,
push: false,
frequency: 'daily'
}
}
});
Custom Preferences
// Store application-specific preferences
await client.users.updateCurrent({
preferences: {
custom: {
dashboardLayout: 'grid',
defaultResourceType: 'project',
recentSearches: ['active projects', 'Q1 reports'],
favoriteViews: ['dashboard', 'reports', 'analytics']
}
}
});
// Retrieve custom preferences
const user = await client.users.getCurrent();
const dashboardLayout = user.preferences?.custom?.dashboardLayout || 'list';
Error Handling
try {
const user = await client.users.getById('user_999');
} catch (error) {
if (error.code === 'NOT_FOUND') {
console.error('User not found');
} else if (error.code === 'FORBIDDEN') {
console.error('Insufficient permissions to view this user');
} else {
console.error('Error fetching user:', error.message);
}
}
Complete Example
Full user management with preferences and permissions:
async function setupUserContext() {
// Get current user
const user = await client.users.getCurrent();
console.log(`Welcome, ${user.name}!`);
console.log(`Role: ${user.role}`);
console.log(`Last login: ${new Date(user.lastLoginAt).toLocaleString()}`);
// Apply user preferences
const theme = user.preferences?.theme || 'light';
const language = user.preferences?.language || 'en';
document.documentElement.setAttribute('data-theme', theme);
document.documentElement.setAttribute('lang', language);
// Check permissions for UI features
const canManageUsers = user.permissions.includes('users.manage');
const canUploadDocuments = user.permissions.includes('documents.upload');
return {
user,
theme,
language,
permissions: {
canManageUsers,
canUploadDocuments,
canCreateResources: user.permissions.includes('resources.create'),
canAccessChat: user.permissions.includes('chat.access')
}
};
}
// Usage
const context = await setupUserContext();
if (context.permissions.canManageUsers) {
// Show admin panel
const allUsers = await client.users.list({ limit: 100 });
console.log(`Managing ${allUsers.total} users`);
}
Multi-Tenant Support
Users belong to tenants and can only access resources within their tenant:
const user = await client.users.getCurrent();
console.log(`Tenant: ${user.tenantId}`);
// All operations are scoped to the user's tenant
const resources = await client.resources.list({ type: 'project' });
// Returns only projects in the user's tenant
User Search
// Search for users by name or email
const results = await client.users.list({
search: 'john',
limit: 10
});
results.data.forEach(user => {
console.log(`${user.name} (${user.email})`);
});
Next Steps
- Learn about Auth module for authentication
- Explore Resources module for user-scoped resources
- See Authorization guide
- Read Multi-tenancy guide