BOB Docs
APIApplication

User

API

The application is accessible under the path: /api/user/*

The API is divided into the following parts:

  • Registration, Authentication, and Authorization: auth_router.py
  • Organization Management: organization_router.py
  • Organization Invitations: invitation_router.py
  • User Management: user_router.py

Additionally, the API is responsible for setting cookies in certain responses:

@auth_router.post('/register', auth=None, response={201: AccessTokenOut, 400: ApiExceptionOut},
                  tags=["auth", "register"], summary="Register with email and password.")
async def register(request, body: RegisterByEmailIn, response: HttpResponse):
    """
    Authenticate user based on external Firebase token.
    """
 
    if not settings.ENABLE_SELF_AUTHENTICATION:
        raise ApiException("Authentication turned off.")
 
    access_token, refresh_token_to_set = await user_interactor.register_user_by_email(body.email, body.password)
 
    # Set server-side cookies for the refresh token only!
    set_server_side_cookie(response, settings.REFRESH_TOKEN_KEY, refresh_token_to_set)
    return 201, {"access_token": access_token}

UserInteractor

The UserInteractor class is responsible for executing all business processes in the user application.

The UserInteractor serves as the core business logic layer for managing user-related operations. It integrates multiple services to handle user registration, authentication, organization management, invitations, and permissions, ensuring a cohesive and consistent approach to user interactions.

Key Features:

  • User Management: Handles user registration (email-based or external), login, profile updates, and avatar management.
  • Organization Handling: Manages organization-related operations, including user invitations, membership changes, and organization deletion.
  • Permission and Group Management: Configures user permissions and groups, ensuring appropriate access control.
  • Email Notifications: Supports email-based notifications for actions like registration verification, password reset, and invitations.
  • Subscription Enforcement: Validates user limits based on subscription plans before adding users to organizations.

Methods:

  1. User Registration and Login:
  • register_user_external_auth: Registers users via external authentication providers.
  • register_user_by_email: Registers users using email and password.
  • login: Logs users in via email and password.
  • login_external: Handles login via external authentication services.
  1. Password Management:
  • reset_password_via_email: Sends a reset password link via email.
  1. Invitation Management:
  • invite: Sends invitations to join an organization, validating subscription limits.
  • accept_invitation: Accepts an invitation and moves the user to a new organization.
  1. Permission Management:
  • get_groups_manageable_by_users: Retrieves manageable permission groups.
  • set_permission_groups: Updates permission groups for a user.
  1. Organization Management:
  • wipe_out_organization: Deletes all data associated with an organization.
  • get_organization_details: Retrieves details about an organization, including users and invitations.
  1. User Profile:
  • update_profile_data: Updates a user's profile data (name, description).
  • update_avatar: Updates a user's avatar.
  • get_user_data: Retrieves detailed user data, including profile, organization, and invitations.

Example Workflow:

  1. Register a User:
tokens = await user_interactor.register_user_by_email(email="example@test.com", password="secure_password")
  1. Invite a User:
invitation = await user_interactor.invite(custom_user, email="invitee@test.com")
  1. Retrieve Organization Details:
organization_data = await user_interactor.get_organization_details(organization_id="org123")

Dependencies:

  • Services Used:
  • AuthService: Handles authentication and token management.
  • PermissionService: Manages user permissions and groups.
  • InvitationService: Handles user invitations.
  • OrganizationService: Manages organizations.
  • UserService: Performs user-related database operations.
  • MailerService: Sends email notifications.
  • SubscriptionService: Validates subscription limits.

This class ensures a seamless integration of user management with organizational policies and permissions, providing robust functionality for multi-user applications.

Commands

Contains commands for creating test users and setting up user groups based on preferences.

SetupDevUsers

The setupdevusers command is a Django management command designed to populate the project with initial development users. It automates the creation of an admin organization and an associated superuser account, streamlining the setup process for development environments.

Key Responsibilities:

  • Admin Organization Creation:
    • Creates an organization named "Admin Organization" in the database.
  • Superuser Setup:
    • Creates a superuser account with the following credentials:
      • Username: user
      • Email: user@example.com
      • Password: string
    • Associates the superuser with the newly created admin organization.

Usage:

Run the command from the terminal:

python manage.py setupdevusers

Purpose:

This command simplifies the initial development setup by providing a predefined superuser and admin organization, ensuring a consistent starting point for developers.

SetupGroups

The setupgroups command is a Django management command designed to populate the project with predefined permission groups. It organizes user permissions by creating groups for subscription plans, system roles, and user-manageable roles.

Key Responsibilities:

  • Create Permission Groups:
  • Subscription Groups: Adds groups corresponding to available subscription plans defined in SUBSCRIPTIONS_AVAILABLE.
  • System Groups: Adds system-level groups based on SystemGroupNames to manage core functionality for solution hosts.
  • User-Manageable Groups: Adds groups from GroupNameManageableByUsers for user-assigned permissions within organizations.

Usage:

Run the command from the terminal:

python manage.py setupgroups

Purpose:

This command standardizes permission group creation, ensuring consistent structures across environments and simplifying role and access management.


Signals

The custom_user_post_save signal triggers whenever a CustomUser instance is saved. It ensures the proper setup of many-to-many (m2m) relationships and executes post-creation logic for newly created users by calling the post_user_created method of the UserInteractor.


Models

Avatar

The Avatar model stores user-uploaded avatar images in the avatar_images/ directory. It dynamically generates a thumbnail URL using the thumb_url property and the get_thumbnail() function. By inheriting from Base, it includes common fields like created_at, and by using OwnedByUser, it associates avatars with specific users, allowing personalized avatar management.

CustomUser

The CustomUser model extends Django's AbstractUser, adding:

  • A globally unique identifier (GUID).
  • External IDs for third-party integrations.
  • Optional association with an Organization via a foreign key. If the organization is deleted, the relationship is set to NULL, supporting users without organizations while enabling group-based management.

Invitation

The Invitation model tracks user invitations to organizations, including:

  • The inviting user.
  • Associated organization.
  • Invitee's email and acceptance timestamp. If the organization is deleted, the invitation is also removed. It inherits fields like created_at and updated_at from Base, and ownership details from OwnedByUser.

Organization

The Organization model represents a system entity with:

  • A name field (max 70 characters).
  • Unique identifiers (GUID).
  • Metadata for creation and updates (created_at, updated_at).

ProfileData

The ProfileData model stores optional user profile details, including:

  • First and last names (max 50 characters).
  • A short description (max 140 characters). It inherits metadata fields from Base and associates profile data with specific users via OwnedByUser.

ResetPasswordToken

The ResetPasswordToken model facilitates password resets by associating tokens with users. Key features:

  • Auto-expiring expires_at field based on a configurable duration.
  • Unique token field (max 40 characters). It inherits metadata from Base and links tokens to users with OwnedByUser.

UserExternalAuthentication

This model links CustomUser to external authentication providers. Features include:

  • A unique external_id for users in external systems.
  • An auth_type field specifying the provider (default: Firebase). This setup supports multi-authentication providers while maintaining user associations.

VerificationToken

The VerificationToken model manages user verification processes with:

  • A unique token generated via generate_external_id.
  • An optional used_at field recording token usage. It inherits timestamping and user association features from Base and OwnedByUser, supporting robust verification workflows.

On this page