OrgUser class for managing organization-user relationships

This class represents the relationship between a user and an organization in the Mosaia platform. It manages permissions, roles, and access control within organizational contexts, enabling fine-grained control over user access to organizational resources.

Features:

  • Permission management
  • Role-based access control
  • Session handling
  • User-org relationship lifecycle
  • Access control enforcement

Organization-user relationships are crucial for:

  • Multi-tenant access control
  • Team member management
  • Resource sharing
  • Activity tracking
  • Compliance and auditing

The class supports various permission levels:

  • Owner: Full control over organization
  • Admin: Administrative access
  • Member: Standard access
  • Guest: Limited access

Basic relationship setup:

import { OrgUser } from 'mosaia-node-sdk';

// Create a new team member relationship
const teamMember = new OrgUser({
org: 'acme-org',
user: 'john-doe',
permission: 'member',
metadata: {
department: 'engineering',
role: 'developer'
}
});

await teamMember.save();

Managing access and sessions:

// Get user and organization details
const user = teamMember.user;
const org = teamMember.org;

// Create an authenticated session
const config = await teamMember.session();
const mosaia = new Mosaia(config);

// Check access and permissions
if (teamMember.isActive()) {
console.log(`${user.name} is active in ${org.name}`);
console.log(`Permission level: ${teamMember.permission}`);
} else {
// Remove access if needed
await teamMember.disable();
console.log('Access removed');
}

Hierarchy (View Summary)

Constructors

  • Creates a new organization-user relationship

    Initializes a relationship between a user and an organization with specified permissions and metadata. This relationship controls the user's access and capabilities within the organization.

    Parameters

    • data: Partial<OrgUserInterface>

      Configuration data including: - org: Organization ID or data - user: User ID or data - permission: Access level ('owner', 'admin', 'member', 'guest') - metadata: Custom metadata object

    • Optionaluri: string

      Optional custom URI path for the relationship endpoint

    Returns OrgUser

    Basic member setup:

    const member = new OrgUser({
    org: 'acme-org',
    user: 'jane-doe',
    permission: 'member'
    });

    Admin with metadata:

    const admin = new OrgUser({
    org: 'tech-corp',
    user: 'admin-user',
    permission: 'admin',
    metadata: {
    department: 'IT',
    role: 'system-admin',
    access_level: 'full',
    joined_date: new Date().toISOString()
    }
    }, '/enterprise/org-user');

Accessors

  • get user(): User

    Get the associated user details

    This getter provides access to the user's details within the context of the organization relationship. It returns a User instance that can be used to access and manage user-specific data.

    Returns User

    User instance with full user details

    When user data is not available in the relationship

    Basic user access:

    const user = orgUser.user;
    console.log(`Member: ${user.name} (${user.email})`);

    Detailed user information:

    try {
    const user = orgUser.user;
    console.log('User Details:');
    console.log(`Name: ${user.name}`);
    console.log(`Email: ${user.email}`);
    console.log(`Status: ${user.isActive() ? 'Active' : 'Inactive'}`);
    console.log(`Last Login: ${user.last_login_at}`);
    } catch (error) {
    console.error('User data not available:', error.message);
    }
  • set user(data: UserInterface): void

    Set the associated user details

    This setter updates the user details within the organization relationship. It's typically used when reassigning the relationship to a different user or updating user details in bulk.

    Parameters

    • data: UserInterface

      Complete user data including: - id: User's unique identifier - name: User's full name - email: User's email address - metadata: Additional user data

    Returns void

    Basic user update:

    orgUser.user = {
    id: 'user-123',
    name: 'Jane Smith',
    email: 'jane.smith@example.com'
    };

    Detailed user update:

    orgUser.user = {
    id: 'user-456',
    name: 'John Developer',
    email: 'john@example.com',
    metadata: {
    title: 'Senior Developer',
    skills: ['typescript', 'node.js'],
    start_date: '2024-01-01'
    }
    };

    // Save changes
    await orgUser.save();
  • get org(): Organization

    Get the associated organization details

    This getter provides access to the organization's details within the context of the user relationship. It returns an Organization instance that can be used to access and manage organization-specific data.

    Returns Organization

    Organization instance with full organization details

    When organization data is not available in the relationship

    Basic organization access:

    const org = orgUser.org;
    console.log(`Organization: ${org.name}`);
    console.log(`Description: ${org.short_description}`);

    Detailed organization information:

    try {
    const org = orgUser.org;
    console.log('Organization Details:');
    console.log(`Name: ${org.name}`);
    console.log(`Description: ${org.short_description}`);
    console.log(`Status: ${org.isActive() ? 'Active' : 'Inactive'}`);
    console.log(`Members: ${org.member_count}`);

    if (org.metadata?.industry) {
    console.log(`Industry: ${org.metadata.industry}`);
    }
    } catch (error) {
    console.error('Organization data not available:', error.message);
    }
  • set org(data: OrganizationInterface): void

    Set the associated organization details

    This setter updates the organization details within the user relationship. It's typically used when reassigning the relationship to a different organization or updating organization details in bulk.

    Parameters

    • data: OrganizationInterface

      Complete organization data including: - id: Organization's unique identifier - name: Organization name - short_description: Brief description - metadata: Additional organization data

    Returns void

    Basic organization update:

    orgUser.org = {
    id: 'org-123',
    name: 'Acme Corporation',
    short_description: 'Leading tech company'
    };

    Detailed organization update:

    orgUser.org = {
    id: 'org-456',
    name: 'Tech Innovators',
    short_description: 'AI and ML solutions',
    long_description: 'Cutting-edge AI/ML solutions for enterprises',
    metadata: {
    industry: 'technology',
    size: 'enterprise',
    founded: '2020',
    locations: ['San Francisco', 'London']
    }
    };

    // Save changes
    await orgUser.save();

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns OrgUserInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<OrgUserInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<OrgUserInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }
  • Create an authenticated session for the organization user

    This method creates a new authenticated session for the user within the organization context. The session includes access tokens and configuration needed to interact with organization resources.

    The method:

    1. Validates the relationship is active
    2. Requests new access tokens
    3. Creates a configured session

    Returns Promise<MosaiaConfig>

    Promise resolving to MosaiaConfig with session details

    When session creation fails

    When relationship is inactive

    When network errors occur

    Basic session creation:

    try {
    const config = await orgUser.session();
    const mosaia = new Mosaia(config);

    // Use the authenticated session
    const agents = await mosaia.agents.get();
    console.log(`Found ${agents.length} agents`);
    } catch (error) {
    console.error('Session failed:', error.message);
    }

    Advanced session usage:

    try {
    // Create authenticated session
    const config = await orgUser.session();
    const mosaia = new Mosaia(config);

    // Access organization resources
    const [agents, models, apps] = await Promise.all([
    mosaia.agents.get(),
    mosaia.models.get(),
    mosaia.apps.get()
    ]);

    console.log('Organization Resources:');
    console.log(`- ${agents.length} AI agents`);
    console.log(`- ${models.length} models`);
    console.log(`- ${apps.length} applications`);
    } catch (error) {
    if (error.message.includes('inactive')) {
    console.error('User access is inactive');
    } else if (error.message.includes('unauthorized')) {
    console.error('Invalid permissions');
    } else {
    console.error('Session error:', error.message);
    }
    }
  • Disable the organization-user relationship

    This method deactivates the relationship between the user and organization, effectively revoking the user's access to organization resources. This is useful for:

    • Removing team members
    • Revoking access temporarily
    • Managing user offboarding

    The method:

    1. Validates the relationship exists
    2. Sends deactivation request
    3. Clears local session data

    Returns Promise<void>

    Promise resolving when relationship is disabled

    When disable operation fails

    When relationship doesn't exist

    When network errors occur

    Basic deactivation:

    try {
    await orgUser.disable();
    console.log('User access revoked successfully');
    } catch (error) {
    console.error('Failed to revoke access:', error.message);
    }

    Managed offboarding:

    async function offboardUser(orgUser: OrgUser): Promise<void> {
    try {
    // Get user details for logging
    const user = orgUser.user;
    const org = orgUser.org;

    // Revoke access
    await orgUser.disable();

    console.log('User offboarded successfully:');
    console.log(`- User: ${user.name} (${user.email})`);
    console.log(`- From: ${org.name}`);
    console.log(`- Time: ${new Date().toISOString()}`);
    } catch (error) {
    console.error('Offboarding failed:', error.message);
    throw error; // Re-throw for handling by caller
    }
    }