Metadata-Version: 2.3
Name: django-supabase
Version: 1.0.0
Summary: A lightweight django package designed to connect Django applications to Supabase Auth, Database Access, and Storage
Author: Lakan
Author-email: Lakan <leydotpy.dev@gmail.com>
Requires-Dist: celery>=5.6.3
Requires-Dist: django>=6.0.6
Requires-Dist: django-celery-beat>=2.9.0
Requires-Dist: django-celery-results>=2.6.0
Requires-Dist: django-guardian>=3.3.2
Requires-Dist: django-redis>=7.0.0
Requires-Dist: djangorestframework>=3.17.1
Requires-Dist: gunicorn>=26.0.0
Requires-Dist: pyjwt[crypto]>=2.10.0
Requires-Dist: redis>=8.0.0
Requires-Dist: supabase>=2.31.0
Requires-Python: >=3.14
Description-Content-Type: text/markdown

# Django Supabase 

Professional, production-ready Supabase integration for Django.

## Features

- 🔐 **Authentication**: Seamless Supabase Auth + Django User model sync
- 💾 **Database**: Direct PostgreSQL connection with Django ORM
- 📦 **Storage**: Django storage backends for Supabase Storage
- 🚀 **Production-Ready**: Connection pooling, caching, error handling
- 🔧 **Django-Native**: Uses Django's ecosystem and patterns

## Installation

```bash
pip install django-supabase
```

## Quick Setup
### Add to INSTALLED_APPS:

```python
INSTALLED_APPS = [
    # ...
    'django_supabase',
    'django_supabase.auth',
]
```

## Configure Settings

```python
SUPABASE_URL = 'https://your-project.supabase.co'
SUPABASE_KEY = 'your-publishable-or-anon-key'
SUPABASE_SECRET_KEY = 'your-secret-or-service-role-key'  # server-side only

# Recommended default: ask Supabase Auth to validate bearer tokens.
SUPABASE_JWT_VERIFICATION = 'auth_server'

# Optional for projects using asymmetric JWT signing keys:
# SUPABASE_JWT_VERIFICATION = 'jwks'
# SUPABASE_JWT_ALGORITHMS = ['RS256', 'ES256']

# Legacy/local-only fallback for HS256 shared-secret verification:
# SUPABASE_JWT_VERIFICATION = 'jwt_secret'
# SUPABASE_JWT_SECRET = 'your-jwt-secret'

AUTH_USER_MODEL = 'supabase_auth.SupabaseUser'

AUTHENTICATION_BACKENDS = [
    'django_supabase.auth.backends.SupabaseAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
]

DATABASES = {
    'default': {
        'ENGINE': 'django_supabase.db.engine.SupabasePostgreSQLEngine',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'your-password',
        'HOST': 'db.your-project.supabase.co',
        'PORT': 5432,
    }
}

STORAGES = {
    'default': {
        'BACKEND': 'django_supabase.storage.backends.SupabaseMediaStorage',
    },
    'staticfiles': {
        'BACKEND': 'django_supabase.storage.backends.SupabaseStaticStorage',
    },
}
```

## Run Migrations

```bash
python manage.py migrate
python manage.py create_storage_buckets
```

# Usage Example
## Authentication

```python
from django.contrib.auth import authenticate

# Email/Password login
user = authenticate(email='user@example.com', password='password')

# JWT Token authentication (in views)
# Token automatically extracted from Authorization: Bearer <token>
```

## Frontend OAuth

Use Supabase Auth in the frontend with a publishable key. After OAuth login,
send the Supabase session access token to Django:

```javascript
const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'google',
  options: { redirectTo: 'https://your-frontend.example.com/auth/callback' },
})

const { data: sessionData } = await supabase.auth.getSession()

await fetch('/api/me/', {
  headers: {
    Authorization: `Bearer ${sessionData.session.access_token}`,
  },
})
```

Django validates the bearer token through `SupabaseAuthMiddleware` and syncs the
local user by Supabase `sub` / `user.id`, not by email alone.

## File Upload

```python
from django_supabase.storage.utils import upload_file_to_supabase

file = ...

url = upload_file_to_supabase(file, 'media', path='uploads/')

```

## Direct Supabase Queries

```python
from django_supabase.db.client import get_supabase_client

supabase = get_supabase_client()
response = supabase.table('posts').select('*').execute()
```

### Test

```python
# supabase_integration/tests.py
from django.test import TestCase
from django.contrib.auth import get_user_model
from django_supabase.db.client import get_supabase_client

User = get_user_model()

class SupabaseIntegrationTestCase(TestCase):
    """Base test case with Supabase utilities"""
    
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.supabase = get_supabase_client()
    
    def create_test_user(self, email='test@example.com'):
        """Helper to create test users"""
        return User.objects.create_user(
            username=email,
            email=email,
            password='testpass123'
        )
```
