Skip to main content

Cloud storage integrations for Django (Box, Dropbox, Google Drive, OneDrive)

Project description

NAI Integrations

A Django package providing unified OAuth 2.0 integrations for cloud storage providers: Box, Dropbox, Google Drive, and OneDrive.

Python 3.10+ Django 4.2+ License: MIT

Features

  • Unified API: Consistent interface across all providers
  • Encrypted Token Storage: Fernet encryption for tokens at rest
  • Automatic Token Refresh: Proactive refresh before expiration
  • Celery Tasks: Background token refresh (optional)
  • Pluggable Authentication: Adapter pattern for custom auth systems
  • Django Admin Integration: Built-in admin interfaces (supports django-unfold)

Installation

# From GitHub (production)
pip install git+https://github.com/nematiai/nai-integrations.git@production

# From GitHub (latest)
pip install git+https://github.com/nematiai/nai-integrations.git

# With optional dependencies
pip install "nai-integrations[celery] @ git+https://github.com/nematiai/nai-integrations.git@production"

Quick Start

1. Add to INSTALLED_APPS

# settings.py
INSTALLED_APPS = [
    # Django apps...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    
    # NAI Integrations (add only what you need)
    'nai_integrations.box',
    'nai_integrations.dropbox',
    'nai_integrations.google',
    'nai_integrations.onedrive',
]

2. Run Migrations

python manage.py migrate

3. Configure Environment Variables

# Token Encryption (REQUIRED)
# Generate: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
TOKEN_ENCRYPTION_KEY=your-fernet-key-here

# Box
BOX_CLIENT_ID=your_client_id
BOX_CLIENT_SECRET=your_client_secret
BOX_REDIRECT_URI=https://yourapp.com/api/v1/integrations/box/callback

# Dropbox
DROPBOX_CLIENT_ID=your_client_id
DROPBOX_CLIENT_SECRET=your_client_secret
DROPBOX_REDIRECT_URI=https://yourapp.com/api/v1/integrations/dropbox/callback

# Google Drive
GOOGLE_OAUTH2_CLIENT_ID=your_client_id
GOOGLE_OAUTH2_CLIENT_SECRET=your_client_secret
GOOGLE_DRIVE_REDIRECT_URI=https://yourapp.com/api/v1/integrations/google/callback

# OneDrive
ONEDRIVE_CLIENT_ID=your_client_id
ONEDRIVE_CLIENT_SECRET=your_client_secret
ONEDRIVE_REDIRECT_URI=https://yourapp.com/api/v1/integrations/onedrive/callback

4. Configure Authentication Adapter

Create an adapter to bridge your auth system:

# your_project/integrations_auth.py
from nai_integrations.contrib.auth import BaseAuthAdapter


class IntegrationsAuthAdapter(BaseAuthAdapter):
    """Adapter for your authentication system."""

    def get_user_from_request(self, request):
        # Session-based auth
        if hasattr(request, 'user') and request.user.is_authenticated:
            return request.user
        
        # Or token-based auth
        auth_header = request.headers.get('Authorization', '')
        if auth_header.startswith('Bearer '):
            token = auth_header[7:]
            # Validate token and return user
            # ...
        
        return None

    def get_ninja_auth(self):
        # Return your django-ninja auth class
        from ninja.security import django_auth
        return django_auth

Register in settings:

# settings.py
NAI_INTEGRATIONS = {
    'AUTH_ADAPTER': 'your_project.integrations_auth.IntegrationsAuthAdapter',
}

5. Register API Routes

# urls.py or api.py
from ninja import NinjaAPI
from nai_integrations.box.views import router as box_router
from nai_integrations.dropbox.views import router as dropbox_router
from nai_integrations.google.views import router as google_router
from nai_integrations.onedrive.views import router as onedrive_router

api = NinjaAPI()

api.add_router("/integrations/box/", box_router)
api.add_router("/integrations/dropbox/", dropbox_router)
api.add_router("/integrations/google/", google_router)
api.add_router("/integrations/onedrive/", onedrive_router)

API Endpoints

Each integration provides these endpoints:

Endpoint Method Description
/status/ GET Check connection status
/authorize/ POST Get OAuth authorization URL
/disconnect/ DELETE Revoke tokens and disconnect
/contents/ GET List folder contents
/callback GET OAuth callback (internal)

Using Services Directly

from nai_integrations.google.services import GoogleDriveService
from nai_integrations.box.services import BoxService
from nai_integrations.dropbox.services import DropboxService
from nai_integrations.onedrive.services import OneDriveService


def list_user_files(user):
    # Google Drive
    service = GoogleDriveService(user)
    if service.is_connected():
        files = service.list_all_files(page_size=100)
        for f in files.get('files', []):
            print(f"Google: {f['name']}")

    # Box
    service = BoxService(user)
    if service.is_connected():
        folder = service.list_folder(folder_id='0')
        for entry in folder.get('entries', []):
            print(f"Box: {entry['name']}")

    # Dropbox
    service = DropboxService(user)
    if service.is_connected():
        folder = service.list_folder(path='')
        for entry in folder.get('entries', []):
            print(f"Dropbox: {entry['name']}")

    # OneDrive
    service = OneDriveService(user)
    if service.is_connected():
        folder = service.list_folder(folder_id='root')
        for entry in folder.get('value', []):
            print(f"OneDrive: {entry['name']}")

Celery Tasks (Optional)

Enable background token refresh:

# settings.py
CELERY_BEAT_SCHEDULE = {
    'refresh-box-tokens': {
        'task': 'nai-integrations-refresh-box-tokens',
        'schedule': 3600,  # Every hour
    },
    'refresh-dropbox-tokens': {
        'task': 'nai-integrations-refresh-dropbox-tokens',
        'schedule': 3600,
    },
    'refresh-google-tokens': {
        'task': 'nai-integrations-refresh-google-tokens',
        'schedule': 3600,
    },
    'refresh-onedrive-tokens': {
        'task': 'nai-integrations-refresh-onedrive-tokens',
        'schedule': 3600,
    },
}

Database Tables

Each provider creates a table:

  • nai_box_auth
  • nai_dropbox_auth
  • nai_google_auth
  • nai_onedrive_auth

Requirements

  • Python 3.10+
  • Django 4.2+
  • django-ninja 1.0+
  • requests 2.28+
  • cryptography 41.0+

License

MIT License - see LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nai_integrations-0.1.1.tar.gz (35.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nai_integrations-0.1.1-py3-none-any.whl (49.2 kB view details)

Uploaded Python 3

File details

Details for the file nai_integrations-0.1.1.tar.gz.

File metadata

  • Download URL: nai_integrations-0.1.1.tar.gz
  • Upload date:
  • Size: 35.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for nai_integrations-0.1.1.tar.gz
Algorithm Hash digest
SHA256 0a7f859f506d8620d14dfa0fe94d9bb4daa4821373eb3e800d0347e4a41ffa56
MD5 dbfbdc21dae5132de49f06d846d86e0f
BLAKE2b-256 2e858c643231581eeec3dcb68cf337dceb7d0243869ce3facb72be0ffaafb5d3

See more details on using hashes here.

File details

Details for the file nai_integrations-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for nai_integrations-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7c6944df9ec91b5ed2836c0373b6943fbcc5e6903a96b98e55ae549c7396c406
MD5 9c661b63d5d77f7ecea0aca351d76885
BLAKE2b-256 6c28d2659dbc01b651e05af21103c4f7cb3db0f7164a81e6a2983eec8c39be5f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page