File size: 6,724 Bytes
34e27fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Claude Agent Instructions - Backend

## Context

You are working in the **FastAPI backend** of a full-stack task management application.

**Parent Instructions**: See root `CLAUDE.md` for global rules.

## Technology Stack

- **FastAPI** 0.115+
- **SQLModel** 0.0.24+ (NOT raw SQLAlchemy)
- **Pydantic v2** for validation
- **PostgreSQL 16** via Neon
- **UV** package manager
- **Alembic** for migrations
- **Python 3.13+**

## Critical Requirements

### SQLModel (NOT SQLAlchemy)

**Correct** (SQLModel):
```python
from sqlmodel import SQLModel, Field, Relationship

class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    email: str = Field(unique=True, index=True)
    password_hash: str

    tasks: list["Task"] = Relationship(back_populates="owner")
```

**Forbidden** (raw SQLAlchemy):
```python
from sqlalchemy import Column, Integer, String  # NO!
```

### User Data Isolation (CRITICAL)

**ALWAYS filter by user_id**:
```python
from fastapi import Depends, HTTPException
from sqlmodel import select

async def get_user_tasks(
    user_id: int,
    current_user: User = Depends(get_current_user),
    session: Session = Depends(get_session)
):
    # Verify ownership
    if user_id != current_user.id:
        raise HTTPException(status_code=404)  # NOT 403!

    # Filter by user_id
    statement = select(Task).where(Task.user_id == user_id)
    tasks = session.exec(statement).all()
    return tasks
```

### JWT Authentication

**Token Validation**:
```python
from jose import jwt, JWTError
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer

security = HTTPBearer()

async def get_current_user(
    token: str = Depends(security)
) -> User:
    try:
        payload = jwt.decode(
            token.credentials,
            settings.BETTER_AUTH_SECRET,
            algorithms=[settings.JWT_ALGORITHM]
        )
        user_id: int = payload.get("sub")
        if user_id is None:
            raise HTTPException(status_code=401)
    except JWTError:
        raise HTTPException(status_code=401)

    user = get_user_from_db(user_id)
    if user is None:
        raise HTTPException(status_code=401)
    return user
```

### Password Security

```python
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)
```

## Project Structure

```
src/
β”œβ”€β”€ main.py              # FastAPI app, CORS, startup
β”œβ”€β”€ config.py            # Environment variables
β”œβ”€β”€ database.py          # SQLModel engine, session
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ user.py          # User SQLModel
β”‚   └── task.py          # Task SQLModel
β”œβ”€β”€ schemas/
β”‚   β”œβ”€β”€ auth.py          # Request/response schemas
β”‚   └── task.py          # Request/response schemas
β”œβ”€β”€ routers/
β”‚   β”œβ”€β”€ auth.py          # /api/auth/* endpoints
β”‚   └── tasks.py         # /api/{user_id}/tasks/* endpoints
β”œβ”€β”€ middleware/
β”‚   └── auth.py          # JWT validation
└── utils/
    β”œβ”€β”€ security.py      # bcrypt, JWT helpers
    └── deps.py          # Dependency injection
```

## API Patterns

### Endpoint Structure

```python
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session

router = APIRouter(prefix="/api/{user_id}/tasks", tags=["tasks"])

@router.get("/", response_model=list[TaskResponse])
async def list_tasks(
    user_id: int,
    current_user: User = Depends(get_current_user),
    session: Session = Depends(get_session)
):
    # Authorization check
    if user_id != current_user.id:
        raise HTTPException(status_code=404)

    # Query with user_id filter
    statement = select(Task).where(Task.user_id == user_id)
    tasks = session.exec(statement).all()
    return tasks
```

### Error Responses

```python
# 401 Unauthorized - Invalid/missing JWT
raise HTTPException(
    status_code=401,
    detail="Invalid authentication credentials"
)

# 404 Not Found - Resource doesn't exist OR unauthorized access
raise HTTPException(
    status_code=404,
    detail="Task not found"
)

# 400 Bad Request - Validation error
raise HTTPException(
    status_code=400,
    detail="Title must be between 1-200 characters"
)

# 409 Conflict - Duplicate resource
raise HTTPException(
    status_code=409,
    detail="An account with this email already exists"
)
```

## Database Migrations

**Creating Migrations**:
```bash
uv run alembic revision --autogenerate -m "Add users and tasks tables"
```

**Applying Migrations**:
```bash
uv run alembic upgrade head
```

**Migration File Structure**:
```python
def upgrade():
    op.create_table(
        'user',
        sa.Column('id', sa.Integer(), primary_key=True),
        sa.Column('email', sa.String(), unique=True),
        sa.Column('password_hash', sa.String()),
    )
    op.create_index('ix_user_email', 'user', ['email'])
```

## Testing

**Fixtures** (`tests/conftest.py`):
```python
import pytest
from sqlmodel import Session, create_engine
from fastapi.testclient import TestClient

@pytest.fixture
def session():
    engine = create_engine("sqlite:///:memory:")
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session

@pytest.fixture
def client(session):
    app.dependency_overrides[get_session] = lambda: session
    yield TestClient(app)
```

**Test Example**:
```python
def test_create_task(client, auth_headers):
    response = client.post(
        "/api/1/tasks",
        headers=auth_headers,
        json={"title": "Test Task", "description": "Test"}
    )
    assert response.status_code == 201
    assert response.json()["title"] == "Test Task"
```

## Environment Variables

Required in `.env`:
```
DATABASE_URL=postgresql://taskuser:taskpassword@db:5432/taskdb
BETTER_AUTH_SECRET=your-secret-key-change-in-production
JWT_SECRET_KEY=your-jwt-secret-change-in-production
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_DAYS=7
```

## Common Mistakes to Avoid

❌ Using raw SQLAlchemy instead of SQLModel
βœ… Use SQLModel for all database models

❌ Trusting user_id from request parameters
βœ… Always extract from validated JWT token

❌ Returning 403 for unauthorized access
βœ… Return 404 to prevent information leakage

❌ SQL string concatenation
βœ… SQLModel parameterized queries only

❌ Plaintext passwords
βœ… bcrypt hashing always

## References

- Root Instructions: `../CLAUDE.md`
- Feature Spec: `../specs/001-task-crud-auth/spec.md`
- Constitution: `../.specify/memory/constitution.md`