Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 9 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,18 @@ cd inpact
#### 2. Frontend Setup

1. Navigate to the frontend directory:

```sh
cd frontend
```

2. Install dependencies:

```sh
npm install
```


3. Create a `.env` file using `.env-example` file:


3. Create a `.env` file using `.env.example` at the frontend root:

4. Get your Supabase credentials:
- Go to [Supabase](https://supabase.com/)
Expand All @@ -115,25 +114,26 @@ npm install
#### 3. Backend Setup

1. Navigate to the backend directory:

```sh
cd ../backend
```

2. Install dependencies:

```sh
pip install -r requirements.txt
```


3. Navigate to the app directory:

```sh
cd app
```

4. Create a `.env` file using `.env-example` as a reference.
4. Create a `.env` file using `.env.example` as a reference.

5. Obtain Supabase credentials:

- Go to [Supabase](https://supabase.com/)
- Log in and create a new project
- Click on the project and remember the project password
Expand All @@ -160,20 +160,20 @@ cd app
dbname=postgres
```


6. Get the Groq API key:
- Visit [Groq Console](https://console.groq.com/)
- Create an API key and paste it into the `.env` file

#### 4. Start Development Servers


1. Start the frontend server (from the frontend directory):

```sh
npm run dev
```

2. Start the backend server (from the backend/app directory):

```sh
uvicorn main:app --reload
```
Expand All @@ -183,12 +183,10 @@ uvicorn main:app --reload
To populate the database with initial data, follow these steps:

1. **Open Supabase Dashboard**

- Go to [Supabase](https://supabase.com/) and log in.
- Select your created project.

2. **Access the SQL Editor**

- In the left sidebar, click on **SQL Editor**.

3. **Run the SQL Script**
Expand Down Expand Up @@ -266,6 +264,4 @@ graph TD;

For queries, issues, or feature requests, please raise an issue or reach out on our Discord server.


Happy Coding!

164 changes: 164 additions & 0 deletions SUPABASE_SETUP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Supabase Integration Setup

This project uses Supabase for authentication, database, and backend services.

## πŸš€ Quick Start

### Frontend Setup (Next.js)

1. **Install dependencies** (already done):

```bash
cd frontend
npm install
```

2. **Configure environment variables**:
- Copy `.env.example` to `.env.local`:
```bash
cp .env.example .env.local
```
- Update with your Supabase credentials:
```env
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key-here
```

3. **Use the Supabase client**:

```typescript
import { supabase } from "@/lib/supabaseClient";

// Example: Fetch data
const { data, error } = await supabase.from("your_table").select("*");
```

### Backend Setup (FastAPI)

1. **Install dependencies**:

```bash
cd backend
pip install -r requirements.txt
```

2. **Configure environment variables**:
- Copy `env_example` to `.env`:
```bash
cp env_example .env
```
- Update with your Supabase credentials:
```env
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key-here
```
> **Note:** Use the public Supabase Anon Key (`SUPABASE_KEY`) for backend configuration. Do **not** use or store the Service Role key in your backend `.env` file.

3. **Use the Supabase client**:

```python
from app.services.supabase_client import supabase

# Example: Fetch data
response = supabase.table('your_table').select('*').execute()
```

## πŸ” Health Check

Test your Supabase connection:

```bash
# Start the backend server
cd backend
uvicorn app.main:app --reload

# Check Supabase connection
curl http://localhost:8000/health/supabase
```

Expected response:

```json
{
"connected": true,
"message": "Supabase client initialized",
"status": "ready"
}
```

## πŸ“ Project Structure

### Frontend

```
frontend/
β”œβ”€β”€ lib/
β”‚ └── supabaseClient.ts # Supabase client initialization
β”œβ”€β”€ types/
β”‚ └── supabase.ts # TypeScript types for database
└── .env.example # Environment variables template
```

### Backend

```
backend/
β”œβ”€β”€ app/
β”‚ β”œβ”€β”€ core/
β”‚ β”‚ └── config.py # Configuration settings
β”‚ β”œβ”€β”€ services/
β”‚ β”‚ └── supabase_client.py # Supabase client initialization
β”‚ └── api/
β”‚ └── routes/
β”‚ └── health.py # Health check endpoints
└── env_example # Environment variables template
```

## πŸ”‘ Environment Variables

### Frontend (Next.js)

- `NEXT_PUBLIC_SUPABASE_URL`: Your Supabase project URL
- `NEXT_PUBLIC_SUPABASE_ANON_KEY`: Supabase anon/public key (safe for client-side)

### Backend (FastAPI)

- `SUPABASE_URL`: Your Supabase project URL
- `SUPABASE_KEY`: Supabase anon/public key (safe for backend, matches config.py)
- `DATABASE_URL`: (Optional) Direct PostgreSQL connection string
- `ALLOWED_ORIGINS`: CORS allowed origins (comma-separated)

## πŸ”’ Security Notes

1. **Never commit `.env` files** - they are in `.gitignore`
2. **Frontend uses anon key** - safe for browser, limited permissions
3. **Backend uses anon key** - safe for backend, never expose service role key or store it in backend environment files
4. **Rotate keys if exposed** - generate new keys in Supabase dashboard
5. **Use environment-specific keys** - different keys for dev/staging/prod

## πŸ“š Next Steps

1. Create your database tables in Supabase Dashboard
2. Update `frontend/types/supabase.ts` with your table types
3. Implement authentication flows
4. Add Row Level Security (RLS) policies in Supabase

## πŸ› οΈ Useful Commands

```bash
# Frontend development
cd frontend && npm run dev

# Backend development
cd backend && uvicorn app.main:app --reload

# Install new dependencies
cd frontend && npm install <package>
cd backend && pip install <package> && pip freeze > requirements.txt
```

## πŸ“– Documentation

- [Supabase Documentation](https://supabase.com/docs)
- [Next.js + Supabase Guide](https://supabase.com/docs/guides/getting-started/quickstarts/nextjs)
- [Python + Supabase Guide](https://supabase.com/docs/reference/python/introduction)
51 changes: 51 additions & 0 deletions backend/app/api/routes/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Health check routes for monitoring service status
"""
from fastapi import APIRouter, HTTPException

router = APIRouter(prefix="/health", tags=["health"])

@router.get("/")
def health_check():
"""Basic health check endpoint"""
return {"status": "healthy", "message": "Backend is running"}

@router.get("/supabase")
def check_supabase():
"""
Check Supabase connection status.
This endpoint attempts to query Supabase to verify the connection.
"""
try:
from app.services.supabase_client import supabase

# Attempt a simple query to verify connection
response = supabase.table("_supabase_test").select("*").limit(1).execute()

return {
"connected": True,
"message": "Supabase connection is working!",
"status": "healthy"
}
except Exception as e:
error_msg = str(e)
# Detect table-not-found error (Supabase/PostgREST or DB error)
if (
"does not exist" in error_msg or
"relation" in error_msg and "does not exist" in error_msg or
"Could not find the table" in error_msg or
"PGRST205" in error_msg
):
return {
"connected": True,
"message": "Supabase client initialized (no tables queried yet)",
"status": "ready",
"note": error_msg
}
# For any other error, treat as unhealthy
return {
"connected": False,
"message": "Supabase connection failed",
"status": "unhealthy",
"note": error_msg
}
23 changes: 21 additions & 2 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
# Configuration settings for FastAPI app
from pydantic_settings import BaseSettings
from typing import Optional

class Settings(BaseSettings):
database_url: str
ai_api_key: str
# Supabase Configuration
supabase_url: str
supabase_key: str # Use the public Anon Key instead of the Service Key

# Database Configuration
database_url: Optional[str] = None

# AI Configuration
ai_api_key: Optional[str] = None
groq_api_key: Optional[str] = None

# CORS Configuration
allowed_origins: str = "http://localhost:3000"

# Server Configuration
host: str = "0.0.0.0"
port: int = 8000

# Application Settings
app_name: Optional[str] = None

model_config = {
"env_file": ".env"
Expand Down
18 changes: 17 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import os
from app.api.routes import health
from app.services.supabase_client import supabase

app = FastAPI(title="Inpact Backend", version="0.1.0")

# --- CORS Setup (so frontend can talk to backend) ---
# Verify Supabase client initialization on startup
try:
# Try a lightweight query
response = supabase.table("_supabase_test").select("*").limit(1).execute()
print("βœ… Supabase client initialized successfully.")
except Exception as e:
error_msg = str(e)
if "Could not find the table" in error_msg:
print("⚠️ Supabase client connected, but test table does not exist. Connection is working.")
else:
print(f"❌ Failed to verify Supabase connection: {e}")

# --- CORS Setup ---
app.add_middleware(
CORSMiddleware,
allow_origins=os.getenv("ALLOWED_ORIGINS", "http://localhost:3000").split(","),
Expand All @@ -13,6 +27,8 @@
allow_headers=["*"],
)

app.include_router(health.router)

@app.get("/")
def root():
return {"message": "Welcome to Inpact Backend πŸš€"}
3 changes: 3 additions & 0 deletions backend/app/services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Services module for backend application
"""
5 changes: 5 additions & 0 deletions backend/app/services/supabase_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from supabase import create_client, Client
from app.core.config import settings

# Initialize Supabase client with anon key (public)
supabase: Client = create_client(settings.supabase_url, settings.supabase_key)
Loading