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.2.tar.gz (38.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.2-py3-none-any.whl (53.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: nai_integrations-0.1.2.tar.gz
  • Upload date:
  • Size: 38.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.2.tar.gz
Algorithm Hash digest
SHA256 01480b14ea02acb3d73af1d74936c4c3c69f2f64675ed73844af690d6bfb6855
MD5 2da31d8c58d7a587d5a4c22a8bf1ebdb
BLAKE2b-256 7292e418252298e047e5a5643d8696b40718d3a9959d233ca810e8475eea4020

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for nai_integrations-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 fc3ab407066fbe76d15a75191a05d661e326198bfb8d9b211ecbd7a31b2d6fea
MD5 1a547ec4ff693c62924d8f24dbf5409a
BLAKE2b-256 ee3d6e53b260671356b559efd129f7f3dfe0c8b8182c67b232a0409f8e76916c

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