| """ |
| Supabase client initialization and helpers. |
| Handles authentication and storage operations. |
| """ |
|
|
| from supabase import create_client, Client |
| from app.config import settings |
| from typing import Optional |
| import logging |
|
|
| logger = logging.getLogger(__name__) |
|
|
| |
| |
| supabase: Client = create_client(settings.supabase_url, settings.supabase_service_key) |
|
|
| |
| storage_client: Client = create_client(settings.supabase_url, settings.supabase_service_key) |
|
|
|
|
| def get_supabase_client() -> Client: |
| """ |
| Get the primary Supabase client. |
| Note: This client may have a user session attached after auth calls. |
| """ |
| return supabase |
|
|
|
|
| def get_storage_client() -> Client: |
| """ |
| Get the dedicated storage client. |
| This client is guaranteed to stay in service_role mode for bypassing RLS. |
| """ |
| return storage_client |
|
|
|
|
| |
| IMAGES_BUCKET = "cytosight-images" |
|
|
|
|
| def initialize_storage(): |
| """ |
| Initialize storage bucket if it doesn't exist. |
| Call this on application startup. |
| """ |
| try: |
| |
| buckets = supabase.storage.list_buckets() |
| bucket_names = [bucket.name for bucket in buckets] |
| |
| if IMAGES_BUCKET not in bucket_names: |
| |
| supabase.storage.create_bucket( |
| IMAGES_BUCKET, |
| options={"public": True} |
| ) |
| logger.info(f"Created public storage bucket: {IMAGES_BUCKET}") |
| else: |
| |
| supabase.storage.update_bucket( |
| IMAGES_BUCKET, |
| options={"public": True} |
| ) |
| logger.info(f"Updated storage bucket to public: {IMAGES_BUCKET}") |
| except Exception as e: |
| logger.error(f"Error initializing storage: {e}") |