Spaces:
Sleeping
Sleeping
pushing code
Browse files- .agents/skills/neon-postgres/SKILL.md +129 -0
- .agents/skills/neon-postgres/references/connection-methods.md +179 -0
- .agents/skills/neon-postgres/references/devtools.md +109 -0
- .agents/skills/neon-postgres/references/features.md +64 -0
- .agents/skills/neon-postgres/references/getting-started.md +111 -0
- .agents/skills/neon-postgres/references/neon-auth.md +413 -0
- .agents/skills/neon-postgres/references/neon-cli.md +154 -0
- .agents/skills/neon-postgres/references/neon-drizzle.md +241 -0
- .agents/skills/neon-postgres/references/neon-js.md +451 -0
- .agents/skills/neon-postgres/references/neon-python-sdk.md +101 -0
- .agents/skills/neon-postgres/references/neon-rest-api.md +73 -0
- .agents/skills/neon-postgres/references/neon-serverless.md +250 -0
- .agents/skills/neon-postgres/references/neon-typescript-sdk.md +135 -0
- .agents/skills/neon-postgres/references/what-is-neon.md +40 -0
- Dockerfile +13 -0
- Procfile +1 -0
- backend.log +417 -0
- curl +0 -0
- logs/app_20260221.log +0 -0
- logs/error_20260221.log +0 -0
- migrations/convert-user-id-to-text.sql +37 -0
- render.yaml +19 -0
- requirements.txt +23 -0
- run-migration.py +67 -0
- src/api/auth_router.py +177 -0
- src/api/task_router.py +225 -0
- src/auth/better_auth.py +92 -0
- src/database.py +37 -0
- src/main.py +112 -0
- src/middleware/auth.py +34 -0
- src/models/task.py +41 -0
- src/models/user.py +39 -0
- src/services/auth_service.py +75 -0
- src/services/task_service.py +60 -0
- src/services/user_service.py +109 -0
- src/utils/logger.py +57 -0
- src/utils/performance.py +169 -0
- src/utils/security.py +183 -0
- test_api.py +120 -0
- test_jwt.py +52 -0
- tests/integration/test_api_endpoints.py +438 -0
- tests/unit/test_task_service.py +245 -0
- tests/unit/test_user_service.py +288 -0
.agents/skills/neon-postgres/SKILL.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: neon-postgres
|
| 3 |
+
description: Guides and best practices for working with Neon Serverless Postgres. Covers getting started, local development with Neon, choosing a connection method, Neon features, authentication (@neondatabase/auth), PostgREST-style data API (@neondatabase/neon-js), Neon CLI, and Neon's Platform API/SDKs. Use for any Neon-related questions.
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
# Neon Serverless Postgres
|
| 7 |
+
|
| 8 |
+
Neon is a serverless Postgres platform that separates compute and storage to offer autoscaling, branching, instant restore, and scale-to-zero. It's fully compatible with Postgres and works with any language, framework, or ORM that supports Postgres.
|
| 9 |
+
|
| 10 |
+
## Neon Documentation
|
| 11 |
+
|
| 12 |
+
The Neon documentation is the source of truth for all Neon-related information. Always verify claims against the official docs before responding. Neon features and APIs evolve, so prefer fetching current docs over relying on training data.
|
| 13 |
+
|
| 14 |
+
### Fetching docs as markdown
|
| 15 |
+
|
| 16 |
+
Any Neon doc page can be fetched as markdown in two ways:
|
| 17 |
+
|
| 18 |
+
1. **Append `.md` to the URL** (simplest): `https://neon.com/docs/introduction/branching.md`
|
| 19 |
+
2. **Request `text/markdown`** on the standard URL: `curl -H "Accept: text/markdown" https://neon.com/docs/introduction/branching`
|
| 20 |
+
|
| 21 |
+
Both return the same markdown content. Use whichever method your tools support.
|
| 22 |
+
|
| 23 |
+
### Finding the right page
|
| 24 |
+
|
| 25 |
+
The docs index lists every available page with its URL and a short description:
|
| 26 |
+
|
| 27 |
+
```
|
| 28 |
+
https://neon.com/docs/llms.txt
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Common doc URLs are listed in the tables below. If you need a page not listed here, search the [docs index](https://neon.com/docs/llms.txt) — don't guess URLs.
|
| 32 |
+
|
| 33 |
+
### Common Documentation Paths
|
| 34 |
+
|
| 35 |
+
| Topic | URL |
|
| 36 |
+
| ------------------- | --------------------------------------------------------- |
|
| 37 |
+
| Introduction | https://neon.com/docs/introduction.md |
|
| 38 |
+
| Branching | https://neon.com/docs/introduction/branching.md |
|
| 39 |
+
| Autoscaling | https://neon.com/docs/introduction/autoscaling.md |
|
| 40 |
+
| Scale to Zero | https://neon.com/docs/introduction/scale-to-zero.md |
|
| 41 |
+
| Instant Restore | https://neon.com/docs/introduction/branch-restore.md |
|
| 42 |
+
| Read Replicas | https://neon.com/docs/introduction/read-replicas.md |
|
| 43 |
+
| Connection Pooling | https://neon.com/docs/connect/connection-pooling.md |
|
| 44 |
+
| IP Allow Lists | https://neon.com/docs/introduction/ip-allow.md |
|
| 45 |
+
| Neon Auth | https://neon.com/docs/auth/overview.md |
|
| 46 |
+
| Data API | https://neon.com/docs/data-api/overview.md |
|
| 47 |
+
| Serverless Driver | https://neon.com/docs/serverless/serverless-driver.md |
|
| 48 |
+
| JavaScript SDK | https://neon.com/docs/reference/javascript-sdk.md |
|
| 49 |
+
| API Reference | https://neon.com/docs/reference/api-reference.md |
|
| 50 |
+
| TypeScript SDK | https://neon.com/docs/reference/typescript-sdk.md |
|
| 51 |
+
| Python SDK | https://neon.com/docs/reference/python-sdk.md |
|
| 52 |
+
| Neon CLI | https://neon.com/docs/reference/neon-cli.md |
|
| 53 |
+
| Logical Replication | https://neon.com/docs/guides/logical-replication-guide.md |
|
| 54 |
+
|
| 55 |
+
### Framework & Language Guides
|
| 56 |
+
|
| 57 |
+
| Framework/Language | URL |
|
| 58 |
+
| ------------------ | ----------------------------------------- |
|
| 59 |
+
| Next.js | https://neon.com/docs/guides/nextjs.md |
|
| 60 |
+
| Django | https://neon.com/docs/guides/django.md |
|
| 61 |
+
| Drizzle ORM | https://neon.com/docs/guides/drizzle.md |
|
| 62 |
+
| Prisma | https://neon.com/docs/guides/prisma.md |
|
| 63 |
+
| ORMs Guide | https://neon.com/docs/get-started/orms.md |
|
| 64 |
+
|
| 65 |
+
### Platform API
|
| 66 |
+
|
| 67 |
+
For managing Neon resources programmatically (projects, branches, endpoints, databases, roles):
|
| 68 |
+
|
| 69 |
+
| Method | Documentation |
|
| 70 |
+
| --------------- | ------------------------------------------------------------------ |
|
| 71 |
+
| REST API | https://neon.com/docs/reference/api-reference.md |
|
| 72 |
+
| Interactive API | https://api-docs.neon.tech/reference/getting-started-with-neon-api |
|
| 73 |
+
| OpenAPI Spec | https://neon.com/api_spec/release/v2.json |
|
| 74 |
+
| TypeScript SDK | https://neon.com/docs/reference/typescript-sdk.md |
|
| 75 |
+
| Python SDK | https://neon.com/docs/reference/python-sdk.md |
|
| 76 |
+
| CLI | https://neon.com/docs/reference/neon-cli.md |
|
| 77 |
+
|
| 78 |
+
**Quick cross-reference** (common operations across interfaces):
|
| 79 |
+
|
| 80 |
+
| Operation | REST API | TypeScript SDK | Python SDK |
|
| 81 |
+
| ------------------ | ------------------------------ | --------------------------- | ---------------------- |
|
| 82 |
+
| List projects | `GET /projects?org_id=...` | `listProjects({ org_id })` | `projects(org_id=...)` |
|
| 83 |
+
| Create project | `POST /projects` | `createProject({...})` | `project_create(...)` |
|
| 84 |
+
| Get connection URI | `GET .../connection_uri` | `getConnectionUri({...})` | `connection_uri(...)` |
|
| 85 |
+
| Create branch | `POST .../branches` | `createProjectBranch(...)` | `branch_create(...)` |
|
| 86 |
+
| Start endpoint | `POST .../endpoints/.../start` | `startProjectEndpoint(...)` | `endpoint_start(...)` |
|
| 87 |
+
|
| 88 |
+
## Overview of Resources
|
| 89 |
+
|
| 90 |
+
Reference the appropriate resource file based on the user's needs:
|
| 91 |
+
|
| 92 |
+
### Core Guides
|
| 93 |
+
|
| 94 |
+
| Area | Resource | When to Use |
|
| 95 |
+
| ------------------ | ---------------------------------- | -------------------------------------------------------------- |
|
| 96 |
+
| What is Neon | `references/what-is-neon.md` | Understanding Neon concepts, architecture, core resources |
|
| 97 |
+
| Features | `references/features.md` | Branching, autoscaling, scale-to-zero, connection pooling |
|
| 98 |
+
| Getting Started | `references/getting-started.md` | Setting up a project, connection strings, dependencies, schema |
|
| 99 |
+
| Connection Methods | `references/connection-methods.md` | Choosing drivers based on platform and runtime |
|
| 100 |
+
| Developer Tools | `references/devtools.md` | VSCode extension, MCP server, Neon CLI (`neon init`) |
|
| 101 |
+
|
| 102 |
+
### Database Drivers & ORMs
|
| 103 |
+
|
| 104 |
+
HTTP/WebSocket queries for serverless/edge functions.
|
| 105 |
+
|
| 106 |
+
| Area | Resource | When to Use |
|
| 107 |
+
| ----------------- | ------------------------------- | --------------------------------------------------- |
|
| 108 |
+
| Serverless Driver | `references/neon-serverless.md` | `@neondatabase/serverless` - HTTP/WebSocket queries |
|
| 109 |
+
| Drizzle ORM | `references/neon-drizzle.md` | Drizzle ORM integration with Neon |
|
| 110 |
+
|
| 111 |
+
### Auth & Data API SDKs
|
| 112 |
+
|
| 113 |
+
Authentication and PostgREST-style data API for Neon.
|
| 114 |
+
|
| 115 |
+
| Area | Resource | When to Use |
|
| 116 |
+
| ----------- | ------------------------- | ----------------------------------------------------------------------------------------------------- |
|
| 117 |
+
| Neon Auth | `references/neon-auth.md` | `@neondatabase/auth` or `@neondatabase/neon-js` - Setup, UI components, auth methods, common mistakes |
|
| 118 |
+
| Neon JS SDK | `references/neon-js.md` | `@neondatabase/neon-js` - Auth + Data API (PostgREST-style queries) |
|
| 119 |
+
|
| 120 |
+
### Neon Platform API & CLI
|
| 121 |
+
|
| 122 |
+
Managing Neon resources programmatically via REST API, SDKs, or CLI.
|
| 123 |
+
|
| 124 |
+
| Area | Resource | When to Use |
|
| 125 |
+
| -------------- | ----------------------------------- | ------------------------------------------------ |
|
| 126 |
+
| REST API | `references/neon-rest-api.md` | Direct HTTP calls - auth, endpoints, rate limits |
|
| 127 |
+
| Neon CLI | `references/neon-cli.md` | Terminal workflows, scripts, CI/CD pipelines |
|
| 128 |
+
| TypeScript SDK | `references/neon-typescript-sdk.md` | `@neondatabase/api-client` |
|
| 129 |
+
| Python SDK | `references/neon-python-sdk.md` | `neon-api` package |
|
.agents/skills/neon-postgres/references/connection-methods.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connection Methods
|
| 2 |
+
|
| 3 |
+
Guide to selecting the optimal connection method for your Neon Postgres database based on deployment platform and runtime environment.
|
| 4 |
+
|
| 5 |
+
See the [official connection guide](https://neon.com/docs/connect/choose-connection.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Decision Tree
|
| 8 |
+
|
| 9 |
+
Follow this flow to determine the right connection approach:
|
| 10 |
+
|
| 11 |
+
### 1. What Language Are You Using?
|
| 12 |
+
|
| 13 |
+
**Not TypeScript/JavaScript** → Use **TCP with connection pooling** from a secure server.
|
| 14 |
+
|
| 15 |
+
For non-TypeScript languages, connect from a secure backend server using your language's native Postgres driver with connection pooling enabled.
|
| 16 |
+
|
| 17 |
+
| Language/Framework | Documentation |
|
| 18 |
+
| ------------------- | --------------------------------------------- |
|
| 19 |
+
| Django (Python) | https://neon.com/docs/guides/django.md |
|
| 20 |
+
| SQLAlchemy (Python) | https://neon.com/docs/guides/sqlalchemy.md |
|
| 21 |
+
| Elixir Ecto | https://neon.com/docs/guides/elixir-ecto.md |
|
| 22 |
+
| Laravel (PHP) | https://neon.com/docs/guides/laravel.md |
|
| 23 |
+
| Ruby on Rails | https://neon.com/docs/guides/ruby-on-rails.md |
|
| 24 |
+
| Go | https://neon.com/docs/guides/go.md |
|
| 25 |
+
| Rust | https://neon.com/docs/guides/rust.md |
|
| 26 |
+
| Java | https://neon.com/docs/guides/java.md |
|
| 27 |
+
|
| 28 |
+
**TypeScript/JavaScript** → Continue to step 2.
|
| 29 |
+
|
| 30 |
+
---
|
| 31 |
+
|
| 32 |
+
### 2. Client-Side App Without Backend?
|
| 33 |
+
|
| 34 |
+
**Yes** → Use **Neon Data API** via `@neondatabase/neon-js`
|
| 35 |
+
|
| 36 |
+
This is the only option for client-side apps since browsers cannot make direct TCP connections to Postgres. See `neon-js.md` for setup and the [JavaScript SDK docs](https://neon.com/docs/reference/javascript-sdk.md) for the full reference.
|
| 37 |
+
|
| 38 |
+
**No** → Continue to step 3.
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
### 3. Long-Running Server? (Railway, Render, traditional VPS)
|
| 43 |
+
|
| 44 |
+
**Yes** → Use **TCP with connection pooling** via `node-postgres`, `postgres.js`, or `bun:pg`
|
| 45 |
+
|
| 46 |
+
Long-running servers maintain persistent connections, so standard TCP drivers with pooling are optimal.
|
| 47 |
+
|
| 48 |
+
**No** → Continue to step 4.
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
### 4. Edge Environment Without TCP Support?
|
| 53 |
+
|
| 54 |
+
Some edge runtimes don't support TCP connections. Rarely the case anymore.
|
| 55 |
+
|
| 56 |
+
**Yes** → Continue to step 5 to check transaction requirements.
|
| 57 |
+
|
| 58 |
+
**No** → Continue to step 6 to check pooling support.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
### 5. Does Your App Use SQL Transactions?
|
| 63 |
+
|
| 64 |
+
**Yes** → Use **WebSocket transport** via `@neondatabase/serverless` with `Pool`
|
| 65 |
+
|
| 66 |
+
WebSocket maintains connection state needed for transactions. See `neon-serverless.md` for setup.
|
| 67 |
+
|
| 68 |
+
**No** → Use **HTTP transport** via `@neondatabase/serverless`
|
| 69 |
+
|
| 70 |
+
HTTP is faster for single queries (~3 roundtrips vs ~8 for TCP). See `neon-serverless.md` for setup and the [serverless driver docs](https://neon.com/docs/serverless/serverless-driver.md) for the full reference.
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
|
| 74 |
+
### 6. Serverless Environment With Connection Pooling Support?
|
| 75 |
+
|
| 76 |
+
**Vercel (Fluid Compute)** → Use **TCP with `@vercel/functions`**
|
| 77 |
+
|
| 78 |
+
Vercel's Fluid compute supports connection pooling. Use `attachDatabasePool` for optimal connection management. See the [Vercel connection methods guide](https://neon.com/docs/guides/vercel-connection-methods.md) for details.
|
| 79 |
+
|
| 80 |
+
**Cloudflare (with Hyperdrive)** → Use **TCP via Hyperdrive**
|
| 81 |
+
|
| 82 |
+
Cloudflare Hyperdrive provides connection pooling for Workers. Use `node-postgres` or any native TCP driver.
|
| 83 |
+
|
| 84 |
+
See the [Cloudflare Hyperdrive guide](https://neon.com/docs/guides/cloudflare-hyperdrive.md) for connecting with Cloudflare Workers and Hyperdrive.
|
| 85 |
+
|
| 86 |
+
Also consider Placement Hints to ensure your Workers are deployed as close as possible to your Neon database - read the [Placement Configuration docs](https://developers.cloudflare.com/workers/configuration/placement/) for details.
|
| 87 |
+
|
| 88 |
+
**No pooling support (Netlify, Deno Deploy)** → Use `@neondatabase/serverless`
|
| 89 |
+
|
| 90 |
+
Fall back to the decision in step 5 based on transaction requirements.
|
| 91 |
+
|
| 92 |
+
---
|
| 93 |
+
|
| 94 |
+
## Quick Reference Table
|
| 95 |
+
|
| 96 |
+
| Platform | TCP Support | Pooling | Recommended Driver |
|
| 97 |
+
| ----------------------- | ----------- | ------------------- | -------------------------- |
|
| 98 |
+
| Vercel (Fluid) | Yes | `@vercel/functions` | `pg` (node-postgres) |
|
| 99 |
+
| Cloudflare (Hyperdrive) | Yes | Hyperdrive | `pg` (node-postgres) |
|
| 100 |
+
| Cloudflare Workers | No | No | `@neondatabase/serverless` |
|
| 101 |
+
| Netlify Functions | No | No | `@neondatabase/serverless` |
|
| 102 |
+
| Deno Deploy | No | No | `@neondatabase/serverless` |
|
| 103 |
+
| Railway / Render | Yes | Built-in | `pg` (node-postgres) |
|
| 104 |
+
| Client-side (browser) | No | N/A | `@neondatabase/neon-js` |
|
| 105 |
+
|
| 106 |
+
---
|
| 107 |
+
|
| 108 |
+
## ORM Support
|
| 109 |
+
|
| 110 |
+
Popular TypeScript/JavaScript ORMs all work with Neon:
|
| 111 |
+
|
| 112 |
+
| ORM | Drivers Supported | Documentation |
|
| 113 |
+
| ------- | ----------------------------------------------- | --------------------------------------- |
|
| 114 |
+
| Drizzle | `pg`, `postgres.js`, `@neondatabase/serverless` | https://neon.com/docs/guides/drizzle.md |
|
| 115 |
+
| Kysely | `pg`, `postgres.js`, `@neondatabase/serverless` | https://neon.com/docs/guides/kysely.md |
|
| 116 |
+
| Prisma | `pg`, `@neondatabase/serverless` | https://neon.com/docs/guides/prisma.md |
|
| 117 |
+
| TypeORM | `pg` | https://neon.com/docs/guides/typeorm.md |
|
| 118 |
+
|
| 119 |
+
All ORMs support both TCP drivers and Neon's serverless driver depending on your platform.
|
| 120 |
+
|
| 121 |
+
For Drizzle ORM integration with Neon, see `neon-drizzle.md`.
|
| 122 |
+
|
| 123 |
+
---
|
| 124 |
+
|
| 125 |
+
## Vercel Fluid + Drizzle Example
|
| 126 |
+
|
| 127 |
+
Complete database client setup for Vercel with Drizzle ORM and connection pooling. See `neon-drizzle.md` for more examples.
|
| 128 |
+
|
| 129 |
+
```typescript
|
| 130 |
+
// src/lib/db/client.ts
|
| 131 |
+
import { attachDatabasePool } from "@vercel/functions";
|
| 132 |
+
import { drizzle } from "drizzle-orm/node-postgres";
|
| 133 |
+
import { Pool } from "pg";
|
| 134 |
+
|
| 135 |
+
import * as schema from "./schema";
|
| 136 |
+
|
| 137 |
+
const pool = new Pool({
|
| 138 |
+
connectionString: process.env.DATABASE_URL,
|
| 139 |
+
});
|
| 140 |
+
attachDatabasePool(pool);
|
| 141 |
+
|
| 142 |
+
export const db = drizzle({ client: pool, schema });
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
**Why `attachDatabasePool`?**
|
| 146 |
+
|
| 147 |
+
- First request establishes the TCP connection (~8 roundtrips)
|
| 148 |
+
- Subsequent requests reuse the connection instantly
|
| 149 |
+
- Ensures idle connections close gracefully before function suspension
|
| 150 |
+
- Prevents connection leaks in serverless environments
|
| 151 |
+
|
| 152 |
+
---
|
| 153 |
+
|
| 154 |
+
## Gathering Requirements
|
| 155 |
+
|
| 156 |
+
When helping a user choose their connection method, gather this information:
|
| 157 |
+
|
| 158 |
+
1. **Deployment platform**: Where will the app run? (Vercel, Cloudflare, Netlify, Railway, browser, etc.)
|
| 159 |
+
2. **Runtime type**: Serverless functions, edge functions, or long-running server?
|
| 160 |
+
3. **Transaction requirements**: Does the app need SQL transactions?
|
| 161 |
+
4. **ORM preference**: Using Drizzle, Kysely, Prisma, or raw SQL?
|
| 162 |
+
|
| 163 |
+
Then provide:
|
| 164 |
+
|
| 165 |
+
- The recommended driver/package
|
| 166 |
+
- A working code example for their setup
|
| 167 |
+
- The correct npm install command
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## Documentation Resources
|
| 172 |
+
|
| 173 |
+
| Topic | URL |
|
| 174 |
+
| -------------------------- | --------------------------------------------------------- |
|
| 175 |
+
| Choosing Connection Method | https://neon.com/docs/connect/choose-connection.md |
|
| 176 |
+
| Serverless Driver | https://neon.com/docs/serverless/serverless-driver.md |
|
| 177 |
+
| JavaScript SDK | https://neon.com/docs/reference/javascript-sdk.md |
|
| 178 |
+
| Connection Pooling | https://neon.com/docs/connect/connection-pooling.md |
|
| 179 |
+
| Vercel Connection Methods | https://neon.com/docs/guides/vercel-connection-methods.md |
|
.agents/skills/neon-postgres/references/devtools.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon Developer Tools
|
| 2 |
+
|
| 3 |
+
Neon provides developer tools to enhance your local development workflow, including a VSCode extension and MCP server for AI-assisted development.
|
| 4 |
+
|
| 5 |
+
## Quick Setup with neon init
|
| 6 |
+
|
| 7 |
+
The fastest way to set up all Neon developer tools:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
npx neon init
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
This command:
|
| 14 |
+
|
| 15 |
+
- Installs the Neon VSCode extension
|
| 16 |
+
- Configures the Neon MCP server for AI assistants
|
| 17 |
+
- Sets up your local environment for Neon development
|
| 18 |
+
|
| 19 |
+
See the [full CLI init reference](https://neon.com/docs/reference/cli-init.md) for all options.
|
| 20 |
+
|
| 21 |
+
## VSCode Extension
|
| 22 |
+
|
| 23 |
+
The Neon VSCode extension provides:
|
| 24 |
+
|
| 25 |
+
- **Database Explorer**: Browse projects, branches, tables, and data
|
| 26 |
+
- **SQL Editor**: Write and execute queries with IntelliSense
|
| 27 |
+
- **Branch Management**: Create, switch, and manage database branches
|
| 28 |
+
- **Connection String Access**: Quick copy of connection strings
|
| 29 |
+
|
| 30 |
+
**Install from VSCode:**
|
| 31 |
+
|
| 32 |
+
1. Open Extensions (Cmd/Ctrl+Shift+X)
|
| 33 |
+
2. Search "Neon"
|
| 34 |
+
3. Install "Neon" by Neon
|
| 35 |
+
|
| 36 |
+
**Or via command line:**
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
code --install-extension neon.neon-vscode
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
See the [full VSCode extension docs](https://neon.com/docs/local/vscode-extension.md) for all features.
|
| 43 |
+
|
| 44 |
+
## Neon MCP Server
|
| 45 |
+
|
| 46 |
+
The Neon MCP (Model Context Protocol) server enables AI assistants like Claude, Cursor, and GitHub Copilot to interact with your Neon databases directly.
|
| 47 |
+
|
| 48 |
+
### Capabilities
|
| 49 |
+
|
| 50 |
+
The MCP server provides AI assistants with:
|
| 51 |
+
|
| 52 |
+
- **Project Management**: List, create, describe, and delete projects
|
| 53 |
+
- **Branch Operations**: Create branches, compare schemas, reset from parent
|
| 54 |
+
- **SQL Execution**: Run queries and transactions
|
| 55 |
+
- **Schema Operations**: Describe tables, get database structure
|
| 56 |
+
- **Migrations**: Prepare and complete database migrations with safety checks
|
| 57 |
+
- **Query Tuning**: Analyze and optimize slow queries
|
| 58 |
+
- **Neon Auth**: Provision authentication for your branches
|
| 59 |
+
|
| 60 |
+
### Setup
|
| 61 |
+
|
| 62 |
+
**Option 1: Via neon init (Recommended)**
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
npx neon init
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
**Option 2: Manual Configuration**
|
| 69 |
+
|
| 70 |
+
Add to your AI assistant's MCP configuration:
|
| 71 |
+
|
| 72 |
+
```json
|
| 73 |
+
{
|
| 74 |
+
"mcpServers": {
|
| 75 |
+
"neon": {
|
| 76 |
+
"command": "npx",
|
| 77 |
+
"args": ["-y", "@neondatabase/mcp-server-neon"],
|
| 78 |
+
"env": {
|
| 79 |
+
"NEON_API_KEY": "your-api-key"
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
Get your API key from: https://console.neon.tech/app/settings/api-keys
|
| 87 |
+
|
| 88 |
+
### Common MCP Operations
|
| 89 |
+
|
| 90 |
+
| Operation | What It Does |
|
| 91 |
+
| ---------------------------- | ----------------------------- |
|
| 92 |
+
| `list_projects` | Show all Neon projects |
|
| 93 |
+
| `create_project` | Create a new project |
|
| 94 |
+
| `run_sql` | Execute SQL queries |
|
| 95 |
+
| `get_connection_string` | Get database connection URL |
|
| 96 |
+
| `create_branch` | Create a database branch |
|
| 97 |
+
| `prepare_database_migration` | Safely prepare schema changes |
|
| 98 |
+
| `provision_neon_auth` | Set up Neon Auth |
|
| 99 |
+
|
| 100 |
+
See the [full MCP server docs](https://neon.com/docs/ai/neon-mcp-server.md) for all available operations.
|
| 101 |
+
|
| 102 |
+
## Documentation Resources
|
| 103 |
+
|
| 104 |
+
| Topic | URL |
|
| 105 |
+
| ------------------ | ----------------------------------------------- |
|
| 106 |
+
| CLI Init Command | https://neon.com/docs/reference/cli-init.md |
|
| 107 |
+
| VSCode Extension | https://neon.com/docs/local/vscode-extension.md |
|
| 108 |
+
| MCP Server | https://neon.com/docs/ai/neon-mcp-server.md |
|
| 109 |
+
| Neon CLI Reference | https://neon.com/docs/reference/neon-cli.md |
|
.agents/skills/neon-postgres/references/features.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon Features
|
| 2 |
+
|
| 3 |
+
Quick-reference summaries of Neon's key platform features. Fetch the linked docs for full details.
|
| 4 |
+
|
| 5 |
+
## Branching
|
| 6 |
+
|
| 7 |
+
Instant, copy-on-write database clones at any point in time. Branches only store changes from parent -- no data duplication.
|
| 8 |
+
|
| 9 |
+
- Branches are instant (no data copying)
|
| 10 |
+
- Use for: dev environments, staging, preview deployments, testing migrations
|
| 11 |
+
- Each branch can have its own compute endpoint
|
| 12 |
+
- If the Neon MCP server is available, use it to list and create branches. Otherwise, use the CLI or Platform API.
|
| 13 |
+
|
| 14 |
+
[Branching docs](https://neon.com/docs/introduction/branching.md)
|
| 15 |
+
|
| 16 |
+
## Autoscaling
|
| 17 |
+
|
| 18 |
+
Compute scales automatically between configured min and max Compute Units (CUs) based on CPU and memory pressure. No manual intervention required.
|
| 19 |
+
|
| 20 |
+
[Autoscaling docs](https://neon.com/docs/introduction/autoscaling.md)
|
| 21 |
+
|
| 22 |
+
## Scale to Zero
|
| 23 |
+
|
| 24 |
+
Computes suspend after inactivity (default: 5 minutes, configurable). First query after suspend has ~500ms cold start. Storage is always maintained.
|
| 25 |
+
|
| 26 |
+
[Scale to zero docs](https://neon.com/docs/introduction/scale-to-zero.md)
|
| 27 |
+
|
| 28 |
+
## Instant Restore
|
| 29 |
+
|
| 30 |
+
Point-in-time recovery without pre-configured backups. Restore window depends on plan (7-30 days). Can also create branches from any historical point, or use Time Travel queries.
|
| 31 |
+
|
| 32 |
+
[Instant restore docs](https://neon.com/docs/introduction/branch-restore.md)
|
| 33 |
+
|
| 34 |
+
## Read Replicas
|
| 35 |
+
|
| 36 |
+
Read-only compute endpoints that share storage with the primary (no data duplication). Instant creation, independent scaling. Use for analytics, reporting, and read-heavy workloads.
|
| 37 |
+
|
| 38 |
+
[Read replicas docs](https://neon.com/docs/introduction/read-replicas.md)
|
| 39 |
+
|
| 40 |
+
## Connection Pooling
|
| 41 |
+
|
| 42 |
+
Built-in PgBouncer. Enable by adding `-pooler` to the endpoint hostname. Transaction mode by default. Supports up to 10,000 concurrent connections. Essential for serverless environments.
|
| 43 |
+
|
| 44 |
+
[Connection pooling docs](https://neon.com/docs/connect/connection-pooling.md)
|
| 45 |
+
|
| 46 |
+
## Neon Auth
|
| 47 |
+
|
| 48 |
+
Managed authentication that branches with your database. Supports email, social providers (Google, GitHub), session management, and UI components.
|
| 49 |
+
|
| 50 |
+
For setup, see `neon-auth.md`. For auth + Data API, see `neon-js.md`.
|
| 51 |
+
|
| 52 |
+
[Neon Auth docs](https://neon.com/docs/auth/overview.md)
|
| 53 |
+
|
| 54 |
+
## IP Allow Lists
|
| 55 |
+
|
| 56 |
+
Restrict database access to specific IP addresses or CIDR ranges. Can be scoped to protected branches only.
|
| 57 |
+
|
| 58 |
+
[IP Allow docs](https://neon.com/docs/introduction/ip-allow.md)
|
| 59 |
+
|
| 60 |
+
## Logical Replication
|
| 61 |
+
|
| 62 |
+
Replicate data to/from external Postgres databases using native logical replication.
|
| 63 |
+
|
| 64 |
+
[Logical replication docs](https://neon.com/docs/guides/logical-replication-guide.md)
|
.agents/skills/neon-postgres/references/getting-started.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Getting Started with Neon
|
| 2 |
+
|
| 3 |
+
Interactive guide for setting up a Neon project and connecting it to code.
|
| 4 |
+
|
| 5 |
+
See the [official getting started guide](https://neon.com/docs/get-started/signing-up.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Setup Flow
|
| 8 |
+
|
| 9 |
+
### 1. Select Organization and Project
|
| 10 |
+
|
| 11 |
+
- Check existing organizations and projects (via MCP server or CLI)
|
| 12 |
+
- **1 organization**: default to it
|
| 13 |
+
- **Multiple organizations**: list all and ask which to use
|
| 14 |
+
- **No projects**: ask if they want to create a new project
|
| 15 |
+
- **1 project**: ask "Would you like to use '{project_name}' or create a new one?"
|
| 16 |
+
- **Multiple projects (<6)**: list all and let them choose
|
| 17 |
+
- **Many projects (6+)**: list recent projects, offer to create new or specify by name/ID
|
| 18 |
+
|
| 19 |
+
### 2. Get Connection String
|
| 20 |
+
|
| 21 |
+
- Use MCP server or CLI to get the connection string
|
| 22 |
+
- Store it in `.env` as `DATABASE_URL`:
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
DATABASE_URL=postgresql://user:password@host/database
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
**Before modifying `.env`:**
|
| 29 |
+
|
| 30 |
+
1. Try to read the `.env` file first
|
| 31 |
+
2. If readable: use search/replace to update or append `DATABASE_URL`
|
| 32 |
+
3. If unreadable (permissions): use append command or show the line to add manually
|
| 33 |
+
4. Never overwrite an existing `.env` — always append or update in place
|
| 34 |
+
|
| 35 |
+
### 3. Install Driver
|
| 36 |
+
|
| 37 |
+
Choose based on deployment platform. For detailed guidance, see `connection-methods.md`.
|
| 38 |
+
|
| 39 |
+
| Environment | Driver | Install |
|
| 40 |
+
| ------------------------ | -------------------------- | -------------------------------------- |
|
| 41 |
+
| Vercel (Edge/Serverless) | `@neondatabase/serverless` | `npm install @neondatabase/serverless` |
|
| 42 |
+
| Cloudflare Workers | `@neondatabase/serverless` | `npm install @neondatabase/serverless` |
|
| 43 |
+
| AWS Lambda | `@neondatabase/serverless` | `npm install @neondatabase/serverless` |
|
| 44 |
+
| Traditional Node.js | `pg` | `npm install pg` |
|
| 45 |
+
| Long-running servers | `pg` with pooling | `npm install pg` |
|
| 46 |
+
|
| 47 |
+
For serverless driver patterns, see `neon-serverless.md`. For complex scenarios (multiple runtimes, hybrid architectures), see `connection-methods.md`.
|
| 48 |
+
|
| 49 |
+
### 4. Authentication (if needed)
|
| 50 |
+
|
| 51 |
+
Skip for CLI tools, scripts, or apps without user accounts.
|
| 52 |
+
|
| 53 |
+
If the app needs auth: use MCP server `provision_neon_auth` tool, then see `neon-auth.md` for setup. For auth + database queries, see `neon-js.md`.
|
| 54 |
+
|
| 55 |
+
### 5. ORM Setup (optional)
|
| 56 |
+
|
| 57 |
+
Check for existing ORM (Prisma, Drizzle, TypeORM). If none, ask if they want one. For Drizzle integration, see `neon-drizzle.md`.
|
| 58 |
+
|
| 59 |
+
### 6. Schema Setup
|
| 60 |
+
|
| 61 |
+
- Check for existing migration files or ORM schemas
|
| 62 |
+
- If none: offer to create an example schema or design one together
|
| 63 |
+
|
| 64 |
+
### 7. Developer Tools
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
npx neon init
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
Installs the VSCode extension and configures the MCP server. See `devtools.md` for details.
|
| 71 |
+
|
| 72 |
+
## What's Next
|
| 73 |
+
|
| 74 |
+
After setup is complete, offer to help with:
|
| 75 |
+
|
| 76 |
+
- Neon-specific features (branching, autoscaling, scale-to-zero) — see `features.md`
|
| 77 |
+
- Connection pooling for production
|
| 78 |
+
- Writing queries or building API endpoints
|
| 79 |
+
- Database migrations and schema changes
|
| 80 |
+
- Performance optimization
|
| 81 |
+
|
| 82 |
+
## Resume Support
|
| 83 |
+
|
| 84 |
+
If the user says "Continue with Neon setup", check what's already configured:
|
| 85 |
+
|
| 86 |
+
- MCP server connection
|
| 87 |
+
- `.env` file with `DATABASE_URL`
|
| 88 |
+
- Dependencies installed
|
| 89 |
+
- Schema created
|
| 90 |
+
|
| 91 |
+
Then resume from where they left off.
|
| 92 |
+
|
| 93 |
+
## Security Reminders
|
| 94 |
+
|
| 95 |
+
- Never commit connection strings to version control
|
| 96 |
+
- Use environment variables for all credentials
|
| 97 |
+
- Prefer SSL connections (default in Neon)
|
| 98 |
+
- Use least-privilege database roles
|
| 99 |
+
- Rotate API keys and passwords regularly
|
| 100 |
+
|
| 101 |
+
## Documentation
|
| 102 |
+
|
| 103 |
+
| Topic | URL |
|
| 104 |
+
| ------------------ | ----------------------------------------------------- |
|
| 105 |
+
| Getting Started | https://neon.com/docs/get-started/signing-up.md |
|
| 106 |
+
| Connecting to Neon | https://neon.com/docs/connect/connect-intro.md |
|
| 107 |
+
| Connection String | https://neon.com/docs/connect/connect-from-any-app.md |
|
| 108 |
+
| Frameworks Guide | https://neon.com/docs/get-started/frameworks.md |
|
| 109 |
+
| ORMs Guide | https://neon.com/docs/get-started/orms.md |
|
| 110 |
+
| VSCode Extension | https://neon.com/docs/local/vscode-extension.md |
|
| 111 |
+
| MCP Server | https://neon.com/docs/ai/neon-mcp-server.md |
|
.agents/skills/neon-postgres/references/neon-auth.md
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon Auth
|
| 2 |
+
|
| 3 |
+
Neon Auth provides managed authentication that stores users, sessions, and auth configuration directly in your Neon database. When you branch your database, your entire auth state branches with it.
|
| 4 |
+
|
| 5 |
+
See the [official Neon Auth docs](https://neon.com/docs/auth/overview.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Package Selection
|
| 8 |
+
|
| 9 |
+
| Framework / Use Case | Package | Notes |
|
| 10 |
+
| ----------------------- | ----------------------- | ------------------------------ |
|
| 11 |
+
| Next.js | `@neondatabase/auth` | Server + client SDK |
|
| 12 |
+
| React SPA (Vite, etc) | `@neondatabase/neon-js` | Client SDK + optional Data API |
|
| 13 |
+
| Auth + Database queries | `@neondatabase/neon-js` | Full SDK |
|
| 14 |
+
|
| 15 |
+
Both packages share auth exports (`@neondatabase/neon-js/auth/*` re-exports `@neondatabase/auth/*`).
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
# Next.js
|
| 19 |
+
npm install @neondatabase/auth@latest
|
| 20 |
+
|
| 21 |
+
# React SPA / Full SDK
|
| 22 |
+
npm install @neondatabase/neon-js@latest
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
> **Note:** While these packages are in pre-release (beta), you must use `@latest` with npm. Without it, npm may install an older version. This is not needed with pnpm or yarn.
|
| 26 |
+
|
| 27 |
+
## Next.js Setup
|
| 28 |
+
|
| 29 |
+
**1. Server auth instance** (`lib/auth/server.ts`):
|
| 30 |
+
|
| 31 |
+
```typescript
|
| 32 |
+
import { createNeonAuth } from "@neondatabase/auth/next/server";
|
| 33 |
+
|
| 34 |
+
export const auth = createNeonAuth({
|
| 35 |
+
baseUrl: process.env.NEON_AUTH_BASE_URL!,
|
| 36 |
+
cookies: {
|
| 37 |
+
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
|
| 38 |
+
},
|
| 39 |
+
});
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
**2. API route handler** (`app/api/auth/[...path]/route.ts`):
|
| 43 |
+
|
| 44 |
+
```typescript
|
| 45 |
+
import { auth } from "@/lib/auth/server";
|
| 46 |
+
export const { GET, POST } = auth.handler();
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
**3. Middleware** (`middleware.ts`):
|
| 50 |
+
|
| 51 |
+
```typescript
|
| 52 |
+
import { auth } from "@/lib/auth/server";
|
| 53 |
+
|
| 54 |
+
export default auth.middleware({
|
| 55 |
+
loginUrl: "/auth/sign-in",
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
export const config = {
|
| 59 |
+
matcher: ["/account/:path*"],
|
| 60 |
+
};
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
**4. Client** (`lib/auth/client.ts`):
|
| 64 |
+
|
| 65 |
+
```typescript
|
| 66 |
+
"use client";
|
| 67 |
+
import { createAuthClient } from "@neondatabase/auth/next";
|
| 68 |
+
export const authClient = createAuthClient();
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
**5. Server component access** (must set `force-dynamic`):
|
| 72 |
+
|
| 73 |
+
```typescript
|
| 74 |
+
import { auth } from "@/lib/auth/server";
|
| 75 |
+
|
| 76 |
+
export const dynamic = "force-dynamic";
|
| 77 |
+
|
| 78 |
+
export default async function DashboardPage() {
|
| 79 |
+
const { data: session } = await auth.getSession();
|
| 80 |
+
if (!session?.user) return <div>Not logged in</div>;
|
| 81 |
+
return <div>Hello {session.user.name}</div>;
|
| 82 |
+
}
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
**6. UI setup** — Add the provider, CSS, and page components. See [UI Components](#ui-components) below for `NeonAuthUIProvider`, CSS imports, `AuthView`, and `AccountView` setup.
|
| 86 |
+
|
| 87 |
+
See the [Next.js quickstart](https://neon.com/docs/auth/quick-start/nextjs.md) and [server SDK reference](https://neon.com/docs/auth/reference/nextjs-server.md) for the full setup.
|
| 88 |
+
|
| 89 |
+
### Environment Variables (Next.js)
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
NEON_AUTH_BASE_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
|
| 93 |
+
NEON_AUTH_COOKIE_SECRET=your-secret-at-least-32-characters-long
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Get your Auth URL from the Neon Console: Project -> Branch -> Auth -> Configuration.
|
| 97 |
+
|
| 98 |
+
Generate a cookie secret: `openssl rand -base64 32`
|
| 99 |
+
|
| 100 |
+
## React SPA Setup
|
| 101 |
+
|
| 102 |
+
**1. Auth client** (`lib/auth.ts`):
|
| 103 |
+
|
| 104 |
+
```typescript
|
| 105 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth";
|
| 106 |
+
|
| 107 |
+
export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL);
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
If you need `useSession()` in custom components, pass an adapter:
|
| 111 |
+
|
| 112 |
+
```typescript
|
| 113 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react";
|
| 114 |
+
|
| 115 |
+
const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL, {
|
| 116 |
+
adapter: BetterAuthReactAdapter(),
|
| 117 |
+
});
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
UI components (`AuthView`, `SignedIn`, etc.) work without an adapter.
|
| 121 |
+
|
| 122 |
+
**2. UI setup** — Wrap your app with `NeonAuthUIProvider` and import CSS. See [UI Components](#ui-components) below. In a SPA, the provider and CSS go in your root component (e.g., `App.tsx` or your router layout).
|
| 123 |
+
|
| 124 |
+
**3. Routing** — Map `AuthView` and `AccountView` to routes in your router (React Router, TanStack Router, etc.). For example, with React Router:
|
| 125 |
+
|
| 126 |
+
```tsx
|
| 127 |
+
<Route path="/auth/:path" element={<AuthView />} />
|
| 128 |
+
<Route path="/account/:path" element={<AccountView />} />
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
### Environment Variables (React SPA)
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
VITE_NEON_AUTH_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
See the [React quickstart with UI components](https://neon.com/docs/auth/quick-start/react-router-components.md) and [React API-only quickstart](https://neon.com/docs/auth/quick-start/react.md) for the full setup.
|
| 138 |
+
|
| 139 |
+
## UI Components
|
| 140 |
+
|
| 141 |
+
Use pre-built components instead of building custom auth forms.
|
| 142 |
+
|
| 143 |
+
| Component | Purpose |
|
| 144 |
+
| ------------------------ | ----------------------------------------- |
|
| 145 |
+
| `AuthView` | Sign-in, sign-up, forgot-password pages |
|
| 146 |
+
| `AccountView` | Account settings, security pages |
|
| 147 |
+
| `UserButton` | User avatar with dropdown menu |
|
| 148 |
+
| `SignedIn` / `SignedOut` | Conditional rendering based on auth state |
|
| 149 |
+
| `RedirectToSignIn` | Redirect unauthenticated users |
|
| 150 |
+
| `RedirectToSignUp` | Redirect to sign-up page |
|
| 151 |
+
|
| 152 |
+
See the [UI components reference](https://neon.com/docs/auth/reference/ui-components.md) for full props and customization.
|
| 153 |
+
|
| 154 |
+
### CSS (choose one, never both)
|
| 155 |
+
|
| 156 |
+
The CSS import path depends on which package you installed:
|
| 157 |
+
|
| 158 |
+
```typescript
|
| 159 |
+
// Next.js (@neondatabase/auth)
|
| 160 |
+
import "@neondatabase/auth/ui/css";
|
| 161 |
+
|
| 162 |
+
// React SPA (@neondatabase/neon-js)
|
| 163 |
+
import "@neondatabase/neon-js/ui/css";
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
```css
|
| 167 |
+
/* With Tailwind v4 — Next.js */
|
| 168 |
+
@import "tailwindcss";
|
| 169 |
+
@import "@neondatabase/auth/ui/tailwind";
|
| 170 |
+
|
| 171 |
+
/* With Tailwind v4 — React SPA */
|
| 172 |
+
@import "tailwindcss";
|
| 173 |
+
@import "@neondatabase/neon-js/ui/tailwind";
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
### Provider Setup
|
| 177 |
+
|
| 178 |
+
Wrap your app with `NeonAuthUIProvider`. Only `authClient` is required.
|
| 179 |
+
|
| 180 |
+
In Next.js, add `suppressHydrationWarning` to the `<html>` tag in your root layout — the provider injects theme attributes (`className="light"`, `color-scheme`) client-side that don't exist in the server render:
|
| 181 |
+
|
| 182 |
+
```tsx
|
| 183 |
+
// app/layout.tsx
|
| 184 |
+
import { NeonAuthUIProvider, UserButton } from "@neondatabase/auth/react";
|
| 185 |
+
import { authClient } from "@/lib/auth/client";
|
| 186 |
+
|
| 187 |
+
export default function RootLayout({ children }) {
|
| 188 |
+
return (
|
| 189 |
+
<html lang="en" suppressHydrationWarning>
|
| 190 |
+
<body>
|
| 191 |
+
<NeonAuthUIProvider
|
| 192 |
+
authClient={authClient}
|
| 193 |
+
social={{ providers: ["google", "github", "vercel"] }} // optional
|
| 194 |
+
>
|
| 195 |
+
{children}
|
| 196 |
+
</NeonAuthUIProvider>
|
| 197 |
+
</body>
|
| 198 |
+
</html>
|
| 199 |
+
);
|
| 200 |
+
}
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
**Social login** requires TWO configurations: enable in Neon Console AND add `social` prop to provider.
|
| 204 |
+
|
| 205 |
+
### AuthView (Next.js)
|
| 206 |
+
|
| 207 |
+
Create `app/auth/[path]/page.tsx`:
|
| 208 |
+
|
| 209 |
+
```tsx
|
| 210 |
+
import { AuthView } from "@neondatabase/auth/react";
|
| 211 |
+
|
| 212 |
+
export const dynamicParams = false;
|
| 213 |
+
|
| 214 |
+
export default async function AuthPage({
|
| 215 |
+
params,
|
| 216 |
+
}: {
|
| 217 |
+
params: Promise<{ path: string }>;
|
| 218 |
+
}) {
|
| 219 |
+
const { path } = await params;
|
| 220 |
+
return <AuthView path={path} />;
|
| 221 |
+
}
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
Auth paths: `sign-in`, `sign-up`, `forgot-password`, `reset-password`, `magic-link`, `two-factor`, `callback`, `sign-out`
|
| 225 |
+
|
| 226 |
+
### AccountView (Next.js)
|
| 227 |
+
|
| 228 |
+
Create `app/account/[path]/page.tsx`:
|
| 229 |
+
|
| 230 |
+
```tsx
|
| 231 |
+
import { AccountView } from "@neondatabase/auth/react";
|
| 232 |
+
import { accountViewPaths } from "@neondatabase/auth/react/ui/server";
|
| 233 |
+
|
| 234 |
+
export const dynamicParams = false;
|
| 235 |
+
|
| 236 |
+
export function generateStaticParams() {
|
| 237 |
+
return Object.values(accountViewPaths).map((path) => ({ path }));
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
export default async function AccountPage({
|
| 241 |
+
params,
|
| 242 |
+
}: {
|
| 243 |
+
params: Promise<{ path: string }>;
|
| 244 |
+
}) {
|
| 245 |
+
const { path } = await params;
|
| 246 |
+
return <AccountView path={path} />;
|
| 247 |
+
}
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
Account paths: `settings`, `security`
|
| 251 |
+
|
| 252 |
+
### Conditional Rendering
|
| 253 |
+
|
| 254 |
+
```tsx
|
| 255 |
+
import { SignedIn, SignedOut, UserButton } from "@neondatabase/auth/react";
|
| 256 |
+
|
| 257 |
+
<SignedOut>
|
| 258 |
+
<a href="/auth/sign-in">Sign In</a>
|
| 259 |
+
</SignedOut>
|
| 260 |
+
<SignedIn>
|
| 261 |
+
<UserButton />
|
| 262 |
+
</SignedIn>
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
## Auth Methods Quick Reference
|
| 266 |
+
|
| 267 |
+
| Method | Usage |
|
| 268 |
+
| ----------------------------------------------- | ---------------------------------------------- |
|
| 269 |
+
| `auth.signUp.email({ email, password, name })` | Create account (server) |
|
| 270 |
+
| `auth.signIn.email({ email, password })` | Sign in (server) |
|
| 271 |
+
| `auth.signIn.social({ provider, callbackURL })` | OAuth sign-in (server) |
|
| 272 |
+
| `auth.signOut()` | Sign out (server) |
|
| 273 |
+
| `auth.getSession()` | Get session (server, requires `force-dynamic`) |
|
| 274 |
+
| `authClient.useSession()` | Session hook (client, needs React adapter) |
|
| 275 |
+
| `authClient.getSession()` | Get session (client, no adapter needed) |
|
| 276 |
+
| `authClient.signIn.email(...)` | Sign in (client) |
|
| 277 |
+
| `authClient.signUp.email(...)` | Create account (client) |
|
| 278 |
+
|
| 279 |
+
### Session Data
|
| 280 |
+
|
| 281 |
+
```typescript
|
| 282 |
+
const { data: session } = await auth.getSession();
|
| 283 |
+
// session.user: { id, name, email, image, emailVerified, createdAt, updatedAt }
|
| 284 |
+
// session.session: { id, expiresAt, token, createdAt, updatedAt, userId }
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
### Error Handling
|
| 288 |
+
|
| 289 |
+
```typescript
|
| 290 |
+
const { error } = await auth.signIn.email({ email, password });
|
| 291 |
+
if (error) {
|
| 292 |
+
// error.code: "INVALID_EMAIL_OR_PASSWORD", "EMAIL_NOT_VERIFIED",
|
| 293 |
+
// "USER_NOT_FOUND", "TOO_MANY_REQUESTS"
|
| 294 |
+
console.error(error.message);
|
| 295 |
+
}
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
## Key Imports
|
| 299 |
+
|
| 300 |
+
```typescript
|
| 301 |
+
// Server (Next.js)
|
| 302 |
+
import { createNeonAuth } from "@neondatabase/auth/next/server";
|
| 303 |
+
|
| 304 |
+
// Client (Next.js) -- includes React adapter automatically
|
| 305 |
+
import { createAuthClient } from "@neondatabase/auth/next";
|
| 306 |
+
|
| 307 |
+
// Client (React SPA)
|
| 308 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth";
|
| 309 |
+
|
| 310 |
+
// React adapter (only needed for useSession() in React SPA)
|
| 311 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react";
|
| 312 |
+
|
| 313 |
+
// UI components
|
| 314 |
+
import {
|
| 315 |
+
NeonAuthUIProvider,
|
| 316 |
+
AuthView,
|
| 317 |
+
AccountView,
|
| 318 |
+
SignedIn,
|
| 319 |
+
SignedOut,
|
| 320 |
+
UserButton,
|
| 321 |
+
} from "@neondatabase/auth/react";
|
| 322 |
+
import { accountViewPaths } from "@neondatabase/auth/react/ui/server";
|
| 323 |
+
|
| 324 |
+
// CSS (choose one, never both; path matches your package)
|
| 325 |
+
import "@neondatabase/auth/ui/css"; // Next.js
|
| 326 |
+
import "@neondatabase/neon-js/ui/css"; // React SPA
|
| 327 |
+
// or in CSS: @import "@neondatabase/auth/ui/tailwind"; (Next.js)
|
| 328 |
+
// or in CSS: @import "@neondatabase/neon-js/ui/tailwind"; (React SPA)
|
| 329 |
+
```
|
| 330 |
+
|
| 331 |
+
## Common Mistakes
|
| 332 |
+
|
| 333 |
+
### Missing NEON_AUTH_COOKIE_SECRET
|
| 334 |
+
|
| 335 |
+
Required for Next.js, must be 32+ characters for HMAC-SHA256. Generate with `openssl rand -base64 32`.
|
| 336 |
+
|
| 337 |
+
### Missing force-dynamic on server components
|
| 338 |
+
|
| 339 |
+
```typescript
|
| 340 |
+
// WRONG -- will error
|
| 341 |
+
export default async function Page() {
|
| 342 |
+
const { data: session } = await auth.getSession();
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
// CORRECT
|
| 346 |
+
export const dynamic = "force-dynamic";
|
| 347 |
+
export default async function Page() {
|
| 348 |
+
const { data: session } = await auth.getSession();
|
| 349 |
+
}
|
| 350 |
+
```
|
| 351 |
+
|
| 352 |
+
### Using v0.1 API patterns
|
| 353 |
+
|
| 354 |
+
Use `createNeonAuth()` + `auth.handler()`, not the old standalone `authApiHandler()`. See the [migration guide](https://neon.com/docs/auth/migrate/from-auth-v0.1.md).
|
| 355 |
+
|
| 356 |
+
### Using useSession() without adapter in React SPA
|
| 357 |
+
|
| 358 |
+
`createAuthClient(url)` without an adapter returns a vanilla client with no React hooks. Either pass `BetterAuthReactAdapter()` or use UI components (`SignedIn`, etc.) which don't require an adapter.
|
| 359 |
+
|
| 360 |
+
### Wrong BetterAuthReactAdapter import
|
| 361 |
+
|
| 362 |
+
Must use subpath import and call as function:
|
| 363 |
+
|
| 364 |
+
```typescript
|
| 365 |
+
// WRONG
|
| 366 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js";
|
| 367 |
+
|
| 368 |
+
// CORRECT
|
| 369 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react";
|
| 370 |
+
const client = createAuthClient(url, { adapter: BetterAuthReactAdapter() });
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
### CSS import conflicts
|
| 374 |
+
|
| 375 |
+
Choose ONE: `ui/css` (without Tailwind) or `ui/tailwind` (with Tailwind v4). Never import both -- causes ~94KB of duplicate styles.
|
| 376 |
+
|
| 377 |
+
### Missing "use client" directive
|
| 378 |
+
|
| 379 |
+
Required for any component using `useSession()` or other React hooks.
|
| 380 |
+
|
| 381 |
+
### Wrong createAuthClient signature
|
| 382 |
+
|
| 383 |
+
URL is the first argument, not a property in an options object:
|
| 384 |
+
|
| 385 |
+
```typescript
|
| 386 |
+
// WRONG
|
| 387 |
+
createAuthClient({ url: myUrl });
|
| 388 |
+
|
| 389 |
+
// CORRECT (React SPA)
|
| 390 |
+
createAuthClient(url);
|
| 391 |
+
createAuthClient(url, { adapter: BetterAuthReactAdapter() });
|
| 392 |
+
|
| 393 |
+
// CORRECT (Next.js) -- no arguments, uses proxy
|
| 394 |
+
createAuthClient();
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
## Documentation
|
| 398 |
+
|
| 399 |
+
| Topic | URL |
|
| 400 |
+
| -------------------- | ----------------------------------------------------------------- |
|
| 401 |
+
| Auth Overview | https://neon.com/docs/auth/overview.md |
|
| 402 |
+
| Next.js Quickstart | https://neon.com/docs/auth/quick-start/nextjs.md |
|
| 403 |
+
| Next.js API-only | https://neon.com/docs/auth/quick-start/nextjs-api-only.md |
|
| 404 |
+
| React with UI | https://neon.com/docs/auth/quick-start/react-router-components.md |
|
| 405 |
+
| React API Methods | https://neon.com/docs/auth/quick-start/react.md |
|
| 406 |
+
| TanStack Router | https://neon.com/docs/auth/quick-start/tanstack-router.md |
|
| 407 |
+
| Server SDK Reference | https://neon.com/docs/auth/reference/nextjs-server.md |
|
| 408 |
+
| UI Components Ref | https://neon.com/docs/auth/reference/ui-components.md |
|
| 409 |
+
| Client SDK Reference | https://neon.com/docs/reference/javascript-sdk.md |
|
| 410 |
+
| v0.1 Migration Guide | https://neon.com/docs/auth/migrate/from-auth-v0.1.md |
|
| 411 |
+
| OAuth Setup | https://neon.com/docs/auth/guides/setup-oauth.md |
|
| 412 |
+
| Email Verification | https://neon.com/docs/auth/guides/email-verification.md |
|
| 413 |
+
| Branching Auth | https://neon.com/docs/auth/branching-authentication.md |
|
.agents/skills/neon-postgres/references/neon-cli.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon CLI
|
| 2 |
+
|
| 3 |
+
The Neon CLI is a command-line interface for managing Neon Serverless Postgres directly from your terminal. It provides the same capabilities as the Neon Platform API and is ideal for scripting, CI/CD pipelines, and developers who prefer terminal workflows.
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
**macOS (Homebrew):**
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
brew install neonctl
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
**npm (cross-platform):**
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
npm install -g neonctl
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## Authentication
|
| 20 |
+
|
| 21 |
+
Authenticate with your Neon account:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
neonctl auth
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
This opens a browser for OAuth authentication and stores credentials locally.
|
| 28 |
+
|
| 29 |
+
For CI/CD or non-interactive environments, use an API key:
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
export NEON_API_KEY=your-api-key
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Get your API key from: https://console.neon.tech/app/settings/api-keys
|
| 36 |
+
|
| 37 |
+
## Common Commands
|
| 38 |
+
|
| 39 |
+
### Project Management
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
# List all projects (org-scoped)
|
| 43 |
+
neonctl projects list --org-id <org-id>
|
| 44 |
+
|
| 45 |
+
# Create a new project
|
| 46 |
+
neonctl projects create --name my-project --org-id <org-id>
|
| 47 |
+
|
| 48 |
+
# Get project details
|
| 49 |
+
neonctl projects get <project-id>
|
| 50 |
+
|
| 51 |
+
# Delete a project
|
| 52 |
+
neonctl projects delete <project-id>
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Branch Operations
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
# List branches
|
| 59 |
+
neonctl branches list --project-id <project-id>
|
| 60 |
+
|
| 61 |
+
# Create a branch
|
| 62 |
+
neonctl branches create --project-id <project-id> --name dev
|
| 63 |
+
|
| 64 |
+
# Delete a branch
|
| 65 |
+
neonctl branches delete <branch-id> --project-id <project-id>
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### Connection Strings
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
# Get connection string
|
| 72 |
+
neonctl connection-string --project-id <project-id>
|
| 73 |
+
|
| 74 |
+
# Get connection string for specific branch
|
| 75 |
+
neonctl connection-string --project-id <project-id> --branch-id <branch-id>
|
| 76 |
+
|
| 77 |
+
# Get pooled connection string
|
| 78 |
+
neonctl connection-string --project-id <project-id> --pooled
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
### SQL Execution
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
# Run SQL query
|
| 85 |
+
neonctl sql "SELECT * FROM users LIMIT 10" --project-id <project-id>
|
| 86 |
+
|
| 87 |
+
# Run SQL from file
|
| 88 |
+
neonctl sql --file schema.sql --project-id <project-id>
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
### Database Management
|
| 92 |
+
|
| 93 |
+
```bash
|
| 94 |
+
# List databases
|
| 95 |
+
neonctl databases list --project-id <project-id> --branch-id <branch-id>
|
| 96 |
+
|
| 97 |
+
# Create database
|
| 98 |
+
neonctl databases create --project-id <project-id> --name mydb
|
| 99 |
+
|
| 100 |
+
# List roles
|
| 101 |
+
neonctl roles list --project-id <project-id> --branch-id <branch-id>
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## Output Formats
|
| 105 |
+
|
| 106 |
+
The CLI supports multiple output formats:
|
| 107 |
+
|
| 108 |
+
```bash
|
| 109 |
+
# JSON output (default for scripting)
|
| 110 |
+
neonctl projects list --output json
|
| 111 |
+
|
| 112 |
+
# Table output (human-readable)
|
| 113 |
+
neonctl projects list --output table
|
| 114 |
+
|
| 115 |
+
# YAML output
|
| 116 |
+
neonctl projects list --output yaml
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
## CI/CD Integration
|
| 120 |
+
|
| 121 |
+
Example GitHub Actions workflow:
|
| 122 |
+
|
| 123 |
+
```yaml
|
| 124 |
+
- name: Create preview branch
|
| 125 |
+
env:
|
| 126 |
+
NEON_API_KEY: ${{ secrets.NEON_API_KEY }}
|
| 127 |
+
run: |
|
| 128 |
+
neonctl branches create \
|
| 129 |
+
--project-id ${{ vars.NEON_PROJECT_ID }} \
|
| 130 |
+
--name preview-${{ github.event.pull_request.number }}
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
## CLI vs MCP Server vs SDKs
|
| 134 |
+
|
| 135 |
+
| Tool | Best For |
|
| 136 |
+
| -------------- | ------------------------------------------------- |
|
| 137 |
+
| Neon CLI | Terminal workflows, scripts, CI/CD pipelines |
|
| 138 |
+
| MCP Server | AI-assisted development with Claude, Cursor, etc. |
|
| 139 |
+
| TypeScript SDK | Programmatic access in Node.js/TypeScript apps |
|
| 140 |
+
| Python SDK | Programmatic access in Python applications |
|
| 141 |
+
| REST API | Direct HTTP integration in any language |
|
| 142 |
+
|
| 143 |
+
## Documentation Resources
|
| 144 |
+
|
| 145 |
+
| Topic | URL |
|
| 146 |
+
| -------------- | -------------------------------------------------------- |
|
| 147 |
+
| CLI Reference | https://neon.com/docs/reference/neon-cli.md |
|
| 148 |
+
| CLI Install | https://neon.com/docs/reference/cli-install.md |
|
| 149 |
+
| CLI Auth | https://neon.com/docs/reference/cli-auth.md |
|
| 150 |
+
| CLI Projects | https://neon.com/docs/reference/cli-projects.md |
|
| 151 |
+
| CLI Branches | https://neon.com/docs/reference/cli-branches.md |
|
| 152 |
+
| CLI Connection | https://neon.com/docs/reference/cli-connection-string.md |
|
| 153 |
+
|
| 154 |
+
See the [full CLI docs](https://neon.com/docs/reference/neon-cli.md) for the complete command reference.
|
.agents/skills/neon-postgres/references/neon-drizzle.md
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon and Drizzle Integration
|
| 2 |
+
|
| 3 |
+
Integration patterns, configurations, and optimizations for using **Drizzle ORM** with **Neon** Postgres.
|
| 4 |
+
|
| 5 |
+
See the [official Drizzle guide](https://neon.com/docs/guides/drizzle.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Choosing the Right Driver
|
| 8 |
+
|
| 9 |
+
Drizzle ORM works with multiple Postgres drivers. See `connection-methods.md` for the full decision tree.
|
| 10 |
+
|
| 11 |
+
| Platform | TCP Support | Pooling | Recommended Driver |
|
| 12 |
+
| ----------------------- | ----------- | ------------------- | -------------------------- |
|
| 13 |
+
| Vercel (Fluid) | Yes | `@vercel/functions` | `pg` (node-postgres) |
|
| 14 |
+
| Cloudflare (Hyperdrive) | Yes | Hyperdrive | `pg` (node-postgres) |
|
| 15 |
+
| Cloudflare Workers | No | No | `@neondatabase/serverless` |
|
| 16 |
+
| Netlify Functions | No | No | `@neondatabase/serverless` |
|
| 17 |
+
| Deno Deploy | No | No | `@neondatabase/serverless` |
|
| 18 |
+
| Railway / Render | Yes | Built-in | `pg` (node-postgres) |
|
| 19 |
+
|
| 20 |
+
## Connection Setup
|
| 21 |
+
|
| 22 |
+
### 1. TCP with node-postgres (Long-Running Servers)
|
| 23 |
+
|
| 24 |
+
Best for Railway, Render, traditional VPS.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
npm install drizzle-orm pg
|
| 28 |
+
npm install -D drizzle-kit @types/pg dotenv
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
```typescript
|
| 32 |
+
// src/db.ts
|
| 33 |
+
import { drizzle } from "drizzle-orm/node-postgres";
|
| 34 |
+
import { Pool } from "pg";
|
| 35 |
+
|
| 36 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
| 37 |
+
export const db = drizzle({ client: pool });
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
### 2. Vercel Fluid Compute with Connection Pooling
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
npm install drizzle-orm pg @vercel/functions
|
| 44 |
+
npm install -D drizzle-kit @types/pg
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
```typescript
|
| 48 |
+
// src/db.ts
|
| 49 |
+
import { attachDatabasePool } from "@vercel/functions";
|
| 50 |
+
import { drizzle } from "drizzle-orm/node-postgres";
|
| 51 |
+
import { Pool } from "pg";
|
| 52 |
+
import * as schema from "./schema";
|
| 53 |
+
|
| 54 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
| 55 |
+
attachDatabasePool(pool);
|
| 56 |
+
|
| 57 |
+
export const db = drizzle({ client: pool, schema });
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
### 3. HTTP Adapter (Edge Without TCP)
|
| 61 |
+
|
| 62 |
+
For Cloudflare Workers, Netlify Edge, Deno Deploy. Does NOT support interactive transactions.
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
npm install drizzle-orm @neondatabase/serverless
|
| 66 |
+
npm install -D drizzle-kit dotenv
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
```typescript
|
| 70 |
+
// src/db.ts
|
| 71 |
+
import { drizzle } from "drizzle-orm/neon-http";
|
| 72 |
+
import { neon } from "@neondatabase/serverless";
|
| 73 |
+
|
| 74 |
+
const sql = neon(process.env.DATABASE_URL!);
|
| 75 |
+
export const db = drizzle(sql);
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
### 4. WebSocket Adapter (Edge with Transactions)
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
npm install drizzle-orm @neondatabase/serverless ws
|
| 82 |
+
npm install -D drizzle-kit dotenv @types/ws
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
```typescript
|
| 86 |
+
// src/db.ts
|
| 87 |
+
import { drizzle } from "drizzle-orm/neon-serverless";
|
| 88 |
+
import { Pool, neonConfig } from "@neondatabase/serverless";
|
| 89 |
+
import ws from "ws";
|
| 90 |
+
|
| 91 |
+
neonConfig.webSocketConstructor = ws; // Required for Node.js < v22
|
| 92 |
+
|
| 93 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
| 94 |
+
export const db = drizzle(pool);
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
## Drizzle Config
|
| 98 |
+
|
| 99 |
+
```typescript
|
| 100 |
+
// drizzle.config.ts
|
| 101 |
+
import { config } from "dotenv";
|
| 102 |
+
import { defineConfig } from "drizzle-kit";
|
| 103 |
+
|
| 104 |
+
config({ path: ".env.local" });
|
| 105 |
+
|
| 106 |
+
export default defineConfig({
|
| 107 |
+
schema: "./src/schema.ts",
|
| 108 |
+
out: "./drizzle",
|
| 109 |
+
dialect: "postgresql",
|
| 110 |
+
dbCredentials: {
|
| 111 |
+
url: process.env.DATABASE_URL!,
|
| 112 |
+
},
|
| 113 |
+
});
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
## Migrations
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
# Generate migrations
|
| 120 |
+
npx drizzle-kit generate
|
| 121 |
+
|
| 122 |
+
# Apply migrations
|
| 123 |
+
npx drizzle-kit migrate
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
## Schema Definition
|
| 127 |
+
|
| 128 |
+
```typescript
|
| 129 |
+
// src/schema.ts
|
| 130 |
+
import { pgTable, serial, text, integer, timestamp } from "drizzle-orm/pg-core";
|
| 131 |
+
|
| 132 |
+
export const usersTable = pgTable("users", {
|
| 133 |
+
id: serial("id").primaryKey(),
|
| 134 |
+
name: text("name").notNull(),
|
| 135 |
+
email: text("email").notNull().unique(),
|
| 136 |
+
role: text("role").default("user").notNull(),
|
| 137 |
+
createdAt: timestamp("created_at").defaultNow().notNull(),
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
export type User = typeof usersTable.$inferSelect;
|
| 141 |
+
export type NewUser = typeof usersTable.$inferInsert;
|
| 142 |
+
|
| 143 |
+
export const postsTable = pgTable("posts", {
|
| 144 |
+
id: serial("id").primaryKey(),
|
| 145 |
+
title: text("title").notNull(),
|
| 146 |
+
content: text("content").notNull(),
|
| 147 |
+
userId: integer("user_id")
|
| 148 |
+
.notNull()
|
| 149 |
+
.references(() => usersTable.id, { onDelete: "cascade" }),
|
| 150 |
+
createdAt: timestamp("created_at").defaultNow().notNull(),
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
export type Post = typeof postsTable.$inferSelect;
|
| 154 |
+
export type NewPost = typeof postsTable.$inferInsert;
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
## Query Patterns
|
| 158 |
+
|
| 159 |
+
### Batch Inserts
|
| 160 |
+
|
| 161 |
+
```typescript
|
| 162 |
+
export async function batchInsertUsers(users: NewUser[]) {
|
| 163 |
+
return db.insert(usersTable).values(users).returning();
|
| 164 |
+
}
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
### Prepared Statements
|
| 168 |
+
|
| 169 |
+
```typescript
|
| 170 |
+
import { sql } from "drizzle-orm";
|
| 171 |
+
|
| 172 |
+
export const getUsersByRolePrepared = db
|
| 173 |
+
.select()
|
| 174 |
+
.from(usersTable)
|
| 175 |
+
.where(sql`${usersTable.role} = $1`)
|
| 176 |
+
.prepare("get_users_by_role");
|
| 177 |
+
|
| 178 |
+
// Usage: getUsersByRolePrepared.execute(['admin'])
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
### Transactions
|
| 182 |
+
|
| 183 |
+
```typescript
|
| 184 |
+
export async function createUserWithPosts(user: NewUser, posts: NewPost[]) {
|
| 185 |
+
return await db.transaction(async (tx) => {
|
| 186 |
+
const [newUser] = await tx.insert(usersTable).values(user).returning();
|
| 187 |
+
|
| 188 |
+
if (posts.length > 0) {
|
| 189 |
+
await tx.insert(postsTable).values(
|
| 190 |
+
posts.map((post) => ({
|
| 191 |
+
...post,
|
| 192 |
+
userId: newUser.id,
|
| 193 |
+
})),
|
| 194 |
+
);
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
return newUser;
|
| 198 |
+
});
|
| 199 |
+
}
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
## Working with Neon Branches
|
| 203 |
+
|
| 204 |
+
```typescript
|
| 205 |
+
import { drizzle } from "drizzle-orm/neon-http";
|
| 206 |
+
import { neon } from "@neondatabase/serverless";
|
| 207 |
+
|
| 208 |
+
const getBranchUrl = () => {
|
| 209 |
+
const env = process.env.NODE_ENV;
|
| 210 |
+
if (env === "development") return process.env.DEV_DATABASE_URL;
|
| 211 |
+
if (env === "test") return process.env.TEST_DATABASE_URL;
|
| 212 |
+
return process.env.DATABASE_URL;
|
| 213 |
+
};
|
| 214 |
+
|
| 215 |
+
const sql = neon(getBranchUrl()!);
|
| 216 |
+
export const db = drizzle({ client: sql });
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
## Error Handling
|
| 220 |
+
|
| 221 |
+
```typescript
|
| 222 |
+
export async function safeNeonOperation<T>(
|
| 223 |
+
operation: () => Promise<T>,
|
| 224 |
+
): Promise<T> {
|
| 225 |
+
try {
|
| 226 |
+
return await operation();
|
| 227 |
+
} catch (error: any) {
|
| 228 |
+
if (error.message?.includes("connection pool timeout")) {
|
| 229 |
+
console.error("Neon connection pool timeout");
|
| 230 |
+
}
|
| 231 |
+
throw error;
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
## Best Practices
|
| 237 |
+
|
| 238 |
+
1. **Connection Management** - See `connection-methods.md` for platform-specific guidance
|
| 239 |
+
2. **Neon Features** - Utilize branching for development/testing (see `features.md`)
|
| 240 |
+
3. **Query Optimization** - Batch operations, use prepared statements
|
| 241 |
+
4. **Schema Design** - Leverage Postgres-specific features, use appropriate indexes
|
.agents/skills/neon-postgres/references/neon-js.md
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon JS SDK
|
| 2 |
+
|
| 3 |
+
The `@neondatabase/neon-js` SDK provides a unified client for Neon Auth and Data API. It combines authentication handling with PostgREST-compatible database queries.
|
| 4 |
+
|
| 5 |
+
**Auth only?** Use `@neondatabase/auth` instead (see `neon-auth.md`) for smaller bundle size.
|
| 6 |
+
|
| 7 |
+
See the [official JavaScript SDK docs](https://neon.com/docs/reference/javascript-sdk.md) for complete details.
|
| 8 |
+
|
| 9 |
+
## Package Selection
|
| 10 |
+
|
| 11 |
+
| Use Case | Package | Notes |
|
| 12 |
+
| --------------- | ---------------------------- | ------------------- |
|
| 13 |
+
| Auth + Data API | `@neondatabase/neon-js` | Full SDK |
|
| 14 |
+
| Auth only | `@neondatabase/auth` | Smaller bundle |
|
| 15 |
+
| Data API only | `@neondatabase/postgrest-js` | Bring your own auth |
|
| 16 |
+
|
| 17 |
+
## Installation
|
| 18 |
+
|
| 19 |
+
```bash
|
| 20 |
+
npm install @neondatabase/neon-js@latest
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
> **Note:** While this package is in pre-release (beta), you must use `@latest` with npm. Without it, npm may install an older version. This is not needed with pnpm or yarn.
|
| 24 |
+
|
| 25 |
+
## Quick Setup Patterns
|
| 26 |
+
|
| 27 |
+
### Next.js
|
| 28 |
+
|
| 29 |
+
**1. Server Auth Instance:**
|
| 30 |
+
|
| 31 |
+
```typescript
|
| 32 |
+
// lib/auth/server.ts
|
| 33 |
+
import { createNeonAuth } from "@neondatabase/neon-js/auth/next/server";
|
| 34 |
+
|
| 35 |
+
export const auth = createNeonAuth({
|
| 36 |
+
baseUrl: process.env.NEON_AUTH_BASE_URL!,
|
| 37 |
+
cookies: {
|
| 38 |
+
secret: process.env.NEON_AUTH_COOKIE_SECRET!,
|
| 39 |
+
},
|
| 40 |
+
});
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
**2. API Route Handler:**
|
| 44 |
+
|
| 45 |
+
```typescript
|
| 46 |
+
// app/api/auth/[...path]/route.ts
|
| 47 |
+
import { auth } from "@/lib/auth/server";
|
| 48 |
+
export const { GET, POST } = auth.handler();
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
**3. Auth Client:**
|
| 52 |
+
|
| 53 |
+
```typescript
|
| 54 |
+
// lib/auth/client.ts
|
| 55 |
+
"use client";
|
| 56 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth/next";
|
| 57 |
+
export const authClient = createAuthClient();
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
**4. Database Client:**
|
| 61 |
+
|
| 62 |
+
```typescript
|
| 63 |
+
// lib/db/client.ts
|
| 64 |
+
import { createClient } from "@neondatabase/neon-js";
|
| 65 |
+
import type { Database } from "./database.types";
|
| 66 |
+
|
| 67 |
+
export const dbClient = createClient<Database>({
|
| 68 |
+
auth: { url: process.env.NEON_AUTH_BASE_URL! },
|
| 69 |
+
dataApi: { url: process.env.NEON_DATA_API_URL! },
|
| 70 |
+
});
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
**5. Middleware + UI setup** — See [Neon Auth reference](neon-auth.md) for middleware configuration, `NeonAuthUIProvider`, CSS imports, and `AuthView`/`AccountView` page components.
|
| 74 |
+
|
| 75 |
+
### React SPA
|
| 76 |
+
|
| 77 |
+
```typescript
|
| 78 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth";
|
| 79 |
+
|
| 80 |
+
const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL);
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
> **Note:** If you need React hooks like `useSession()` in custom components, pass an adapter:
|
| 84 |
+
> `createAuthClient(url, { adapter: BetterAuthReactAdapter() })`.
|
| 85 |
+
> UI components (`AuthView`, `SignedIn`, etc.) do not require an adapter.
|
| 86 |
+
|
| 87 |
+
### React SPA with Data API
|
| 88 |
+
|
| 89 |
+
```typescript
|
| 90 |
+
import { createClient } from "@neondatabase/neon-js";
|
| 91 |
+
|
| 92 |
+
const client = createClient<Database>({
|
| 93 |
+
auth: { url: import.meta.env.VITE_NEON_AUTH_URL },
|
| 94 |
+
dataApi: { url: import.meta.env.VITE_NEON_DATA_API_URL },
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
export const authClient = client.auth;
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
## Environment Variables
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
# Next.js (.env)
|
| 104 |
+
NEON_AUTH_BASE_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
|
| 105 |
+
NEON_AUTH_COOKIE_SECRET=your-secret-at-least-32-characters-long
|
| 106 |
+
NEON_DATA_API_URL=https://ep-xxx.apirest.us-east-1.aws.neon.tech/neondb/rest/v1
|
| 107 |
+
|
| 108 |
+
# Vite/React (.env)
|
| 109 |
+
VITE_NEON_AUTH_URL=https://ep-xxx.neonauth.us-east-1.aws.neon.tech/neondb/auth
|
| 110 |
+
VITE_NEON_DATA_API_URL=https://ep-xxx.apirest.us-east-1.aws.neon.tech/neondb/rest/v1
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Get your Auth URL from the Neon Console: Project -> Branch -> Auth -> Configuration.
|
| 114 |
+
|
| 115 |
+
Generate a cookie secret: `openssl rand -base64 32`
|
| 116 |
+
|
| 117 |
+
## Database Queries (PostgREST / Data API)
|
| 118 |
+
|
| 119 |
+
> **Prerequisite:** The Data API must be enabled per branch before making queries. Enable it via the Neon Console (Project → Data API), the MCP server's `provision_neon_data_api` tool, or the [REST API](https://api-docs.neon.tech/reference/createprojectbranchdataapi) (`POST /projects/{project_id}/branches/{branch_id}/data-api/{database_name}`). Without it, requests will return 404.
|
| 120 |
+
|
| 121 |
+
All query methods follow PostgREST syntax (same as Supabase).
|
| 122 |
+
|
| 123 |
+
```typescript
|
| 124 |
+
// Select with filters
|
| 125 |
+
const { data } = await client
|
| 126 |
+
.from("items")
|
| 127 |
+
.select("id, name, status")
|
| 128 |
+
.eq("status", "active")
|
| 129 |
+
.order("created_at", { ascending: false })
|
| 130 |
+
.limit(10);
|
| 131 |
+
|
| 132 |
+
// Select single row
|
| 133 |
+
const { data, error } = await client
|
| 134 |
+
.from("items")
|
| 135 |
+
.select("*")
|
| 136 |
+
.eq("id", 1)
|
| 137 |
+
.single();
|
| 138 |
+
|
| 139 |
+
// Insert (returns inserted row)
|
| 140 |
+
const { data, error } = await client
|
| 141 |
+
.from("items")
|
| 142 |
+
.insert({ name: "New Item", status: "pending" })
|
| 143 |
+
.select()
|
| 144 |
+
.single();
|
| 145 |
+
|
| 146 |
+
// Insert multiple
|
| 147 |
+
const { data } = await client
|
| 148 |
+
.from("items")
|
| 149 |
+
.insert([{ name: "A" }, { name: "B" }])
|
| 150 |
+
.select();
|
| 151 |
+
|
| 152 |
+
// Update
|
| 153 |
+
await client.from("items").update({ status: "completed" }).eq("id", 1);
|
| 154 |
+
|
| 155 |
+
// Update and return updated row
|
| 156 |
+
const { data } = await client
|
| 157 |
+
.from("items")
|
| 158 |
+
.update({ status: "completed" })
|
| 159 |
+
.eq("id", 1)
|
| 160 |
+
.select()
|
| 161 |
+
.single();
|
| 162 |
+
|
| 163 |
+
// Delete
|
| 164 |
+
await client.from("items").delete().eq("id", 1);
|
| 165 |
+
|
| 166 |
+
// Delete and return deleted row
|
| 167 |
+
const { data } = await client
|
| 168 |
+
.from("items")
|
| 169 |
+
.delete()
|
| 170 |
+
.eq("id", 1)
|
| 171 |
+
.select()
|
| 172 |
+
.single();
|
| 173 |
+
|
| 174 |
+
// Upsert
|
| 175 |
+
await client.from("items").upsert({ id: 1, name: "Updated", status: "active" });
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
### Filter Operators
|
| 179 |
+
|
| 180 |
+
| Operator | Example |
|
| 181 |
+
| ------------- | -------------------------------------------- |
|
| 182 |
+
| `.eq()` | `.eq("status", "active")` |
|
| 183 |
+
| `.neq()` | `.neq("status", "archived")` |
|
| 184 |
+
| `.gt()` | `.gt("price", 100)` |
|
| 185 |
+
| `.gte()` | `.gte("price", 100)` |
|
| 186 |
+
| `.lt()` | `.lt("price", 100)` |
|
| 187 |
+
| `.lte()` | `.lte("price", 100)` |
|
| 188 |
+
| `.like()` | `.like("name", "%item%")` |
|
| 189 |
+
| `.ilike()` | `.ilike("name", "%item%")` |
|
| 190 |
+
| `.is()` | `.is("deleted_at", null)` |
|
| 191 |
+
| `.in()` | `.in("status", ["active", "pending"])` |
|
| 192 |
+
| `.contains()` | `.contains("tags", ["important"])` |
|
| 193 |
+
| `.or()` | `.or("status.eq.active,price.gt.100")` |
|
| 194 |
+
| `.not()` | `.not("status", "eq", "archived")` |
|
| 195 |
+
| `.order()` | `.order("created_at", { ascending: false })` |
|
| 196 |
+
| `.limit()` | `.limit(10)` |
|
| 197 |
+
| `.range()` | `.range(0, 9)` (first 10 items) |
|
| 198 |
+
|
| 199 |
+
**Pagination formula**: `.range((page - 1) * pageSize, page * pageSize - 1)`
|
| 200 |
+
|
| 201 |
+
### Relationships
|
| 202 |
+
|
| 203 |
+
```typescript
|
| 204 |
+
// One-to-many
|
| 205 |
+
const { data } = await client
|
| 206 |
+
.from("posts")
|
| 207 |
+
.select("id, title, author:users(name, email)");
|
| 208 |
+
|
| 209 |
+
// Many-to-many
|
| 210 |
+
const { data } = await client
|
| 211 |
+
.from("posts")
|
| 212 |
+
.select("id, title, tags:post_tags(tag:tags(name))");
|
| 213 |
+
|
| 214 |
+
// Nested
|
| 215 |
+
const { data } = await client.from("posts").select(`
|
| 216 |
+
id, title,
|
| 217 |
+
author:users(id, name, profile:profiles(bio, avatar))
|
| 218 |
+
`);
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
### Error Handling
|
| 222 |
+
|
| 223 |
+
```typescript
|
| 224 |
+
const { data, error } = await client.from("items").select();
|
| 225 |
+
if (error) {
|
| 226 |
+
console.error(error.message, error.code, error.details);
|
| 227 |
+
return;
|
| 228 |
+
}
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Common error codes: `PGRST116` (no rows with `.single()`), `23505` (unique violation), `23503` (FK violation), `42P01` (table not found).
|
| 232 |
+
|
| 233 |
+
### Next.js Usage Examples
|
| 234 |
+
|
| 235 |
+
**Server Component:**
|
| 236 |
+
|
| 237 |
+
```typescript
|
| 238 |
+
// app/posts/page.tsx
|
| 239 |
+
import { dbClient } from "@/lib/db/client";
|
| 240 |
+
|
| 241 |
+
export default async function PostsPage() {
|
| 242 |
+
const { data: posts, error } = await dbClient
|
| 243 |
+
.from("posts")
|
| 244 |
+
.select("id, title, created_at, author:users(name)")
|
| 245 |
+
.order("created_at", { ascending: false })
|
| 246 |
+
.limit(10);
|
| 247 |
+
|
| 248 |
+
if (error) return <div>Error loading posts</div>;
|
| 249 |
+
|
| 250 |
+
return (
|
| 251 |
+
<ul>
|
| 252 |
+
{posts?.map((post) => (
|
| 253 |
+
<li key={post.id}>
|
| 254 |
+
<h2>{post.title}</h2>
|
| 255 |
+
<p>By {post.author?.name}</p>
|
| 256 |
+
</li>
|
| 257 |
+
))}
|
| 258 |
+
</ul>
|
| 259 |
+
);
|
| 260 |
+
}
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
**API Route:**
|
| 264 |
+
|
| 265 |
+
```typescript
|
| 266 |
+
// app/api/posts/route.ts
|
| 267 |
+
import { dbClient } from "@/lib/db/client";
|
| 268 |
+
import { NextResponse } from "next/server";
|
| 269 |
+
|
| 270 |
+
export async function GET() {
|
| 271 |
+
const { data, error } = await dbClient.from("posts").select();
|
| 272 |
+
if (error)
|
| 273 |
+
return NextResponse.json({ error: error.message }, { status: 500 });
|
| 274 |
+
return NextResponse.json(data);
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
export async function POST(request: Request) {
|
| 278 |
+
const body = await request.json();
|
| 279 |
+
const { data, error } = await dbClient
|
| 280 |
+
.from("posts")
|
| 281 |
+
.insert(body)
|
| 282 |
+
.select()
|
| 283 |
+
.single();
|
| 284 |
+
if (error)
|
| 285 |
+
return NextResponse.json({ error: error.message }, { status: 400 });
|
| 286 |
+
return NextResponse.json(data, { status: 201 });
|
| 287 |
+
}
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
## Auth Methods
|
| 291 |
+
|
| 292 |
+
### BetterAuth API (Default)
|
| 293 |
+
|
| 294 |
+
```typescript
|
| 295 |
+
await client.auth.signIn.email({ email, password });
|
| 296 |
+
await client.auth.signUp.email({ email, password, name });
|
| 297 |
+
await client.auth.signOut();
|
| 298 |
+
const { data: session } = await client.auth.getSession();
|
| 299 |
+
await client.auth.signIn.social({
|
| 300 |
+
provider: "google",
|
| 301 |
+
callbackURL: "/dashboard",
|
| 302 |
+
});
|
| 303 |
+
```
|
| 304 |
+
|
| 305 |
+
### Supabase-Compatible API
|
| 306 |
+
|
| 307 |
+
```typescript
|
| 308 |
+
import { createClient, SupabaseAuthAdapter } from "@neondatabase/neon-js";
|
| 309 |
+
|
| 310 |
+
const client = createClient({
|
| 311 |
+
auth: { adapter: SupabaseAuthAdapter(), url },
|
| 312 |
+
dataApi: { url },
|
| 313 |
+
});
|
| 314 |
+
|
| 315 |
+
await client.auth.signInWithPassword({ email, password });
|
| 316 |
+
await client.auth.signUp({ email, password });
|
| 317 |
+
const {
|
| 318 |
+
data: { session },
|
| 319 |
+
} = await client.auth.getSession();
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
## Key Imports
|
| 323 |
+
|
| 324 |
+
```typescript
|
| 325 |
+
// Main client
|
| 326 |
+
import {
|
| 327 |
+
createClient,
|
| 328 |
+
SupabaseAuthAdapter,
|
| 329 |
+
BetterAuthVanillaAdapter,
|
| 330 |
+
} from "@neondatabase/neon-js";
|
| 331 |
+
|
| 332 |
+
// Server auth (Next.js) -- unified instance
|
| 333 |
+
import { createNeonAuth } from "@neondatabase/neon-js/auth/next/server";
|
| 334 |
+
|
| 335 |
+
// Client auth (Next.js) -- auto-includes React adapter
|
| 336 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth/next";
|
| 337 |
+
|
| 338 |
+
// Client auth (React SPA / vanilla)
|
| 339 |
+
import { createAuthClient } from "@neondatabase/neon-js/auth";
|
| 340 |
+
|
| 341 |
+
// React adapter (only needed for useSession() in custom components)
|
| 342 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react";
|
| 343 |
+
|
| 344 |
+
// UI components (use /auth/react -- superset of /auth/react/ui and /auth/react/adapters)
|
| 345 |
+
import {
|
| 346 |
+
NeonAuthUIProvider,
|
| 347 |
+
AuthView,
|
| 348 |
+
AccountView,
|
| 349 |
+
SignedIn,
|
| 350 |
+
SignedOut,
|
| 351 |
+
UserButton,
|
| 352 |
+
} from "@neondatabase/neon-js/auth/react";
|
| 353 |
+
import { accountViewPaths } from "@neondatabase/neon-js/auth/react/ui/server";
|
| 354 |
+
|
| 355 |
+
// CSS (choose one, never both)
|
| 356 |
+
import "@neondatabase/neon-js/ui/css"; // Without Tailwind
|
| 357 |
+
// @import '@neondatabase/neon-js/ui/tailwind'; // With Tailwind v4 (in CSS file)
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
## Generate Types
|
| 361 |
+
|
| 362 |
+
```bash
|
| 363 |
+
npx neon-js gen-types --db-url "$DATABASE_URL" --output src/types/database.ts
|
| 364 |
+
```
|
| 365 |
+
|
| 366 |
+
Use types in the client for autocomplete and compile-time checking:
|
| 367 |
+
|
| 368 |
+
```typescript
|
| 369 |
+
import type { Database } from "./database.types";
|
| 370 |
+
const client = createClient<Database>({ ... });
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
## Supabase Migration
|
| 374 |
+
|
| 375 |
+
The Neon JS SDK uses the same PostgREST API as Supabase. Query syntax is identical:
|
| 376 |
+
|
| 377 |
+
```typescript
|
| 378 |
+
// Before (Supabase)
|
| 379 |
+
import { createClient } from "@supabase/supabase-js";
|
| 380 |
+
const client = createClient(SUPABASE_URL, SUPABASE_KEY);
|
| 381 |
+
|
| 382 |
+
// After (Neon)
|
| 383 |
+
import { createClient, SupabaseAuthAdapter } from "@neondatabase/neon-js";
|
| 384 |
+
const client = createClient({
|
| 385 |
+
auth: { adapter: SupabaseAuthAdapter(), url: NEON_AUTH_URL },
|
| 386 |
+
dataApi: { url: NEON_DATA_API_URL },
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
// Queries work the same
|
| 390 |
+
const { data } = await client.from("items").select();
|
| 391 |
+
```
|
| 392 |
+
|
| 393 |
+
## Common Mistakes
|
| 394 |
+
|
| 395 |
+
### Using old v0.1 server APIs
|
| 396 |
+
|
| 397 |
+
Use `createNeonAuth()` + `auth.handler()`, not standalone `authApiHandler()`. See `neon-auth.md` for the v0.2 pattern.
|
| 398 |
+
|
| 399 |
+
### Missing NEON_AUTH_COOKIE_SECRET
|
| 400 |
+
|
| 401 |
+
Required for Next.js, must be 32+ characters. Generate with `openssl rand -base64 32`.
|
| 402 |
+
|
| 403 |
+
### Missing force-dynamic on server components
|
| 404 |
+
|
| 405 |
+
Server components using `auth.getSession()` need `export const dynamic = 'force-dynamic'`.
|
| 406 |
+
|
| 407 |
+
### Wrong adapter import path
|
| 408 |
+
|
| 409 |
+
`BetterAuthReactAdapter` must be imported from a subpath and called as a function:
|
| 410 |
+
|
| 411 |
+
```typescript
|
| 412 |
+
// WRONG
|
| 413 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js";
|
| 414 |
+
|
| 415 |
+
// CORRECT
|
| 416 |
+
import { BetterAuthReactAdapter } from "@neondatabase/neon-js/auth/react";
|
| 417 |
+
auth: {
|
| 418 |
+
adapter: BetterAuthReactAdapter();
|
| 419 |
+
} // Don't forget ()
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
### CSS import conflicts
|
| 423 |
+
|
| 424 |
+
Choose ONE method. Never import both -- causes duplicate styles:
|
| 425 |
+
|
| 426 |
+
```css
|
| 427 |
+
/* With Tailwind v4 */
|
| 428 |
+
@import "tailwindcss";
|
| 429 |
+
@import "@neondatabase/neon-js/ui/tailwind";
|
| 430 |
+
```
|
| 431 |
+
|
| 432 |
+
```typescript
|
| 433 |
+
/* Without Tailwind */
|
| 434 |
+
import "@neondatabase/neon-js/ui/css";
|
| 435 |
+
```
|
| 436 |
+
|
| 437 |
+
### Missing "use client" directive
|
| 438 |
+
|
| 439 |
+
Required for any component using `useSession()` or other React hooks:
|
| 440 |
+
|
| 441 |
+
```typescript
|
| 442 |
+
"use client"; // Required!
|
| 443 |
+
import { authClient } from "@/lib/auth/client";
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
### Wrong API for adapter type
|
| 447 |
+
|
| 448 |
+
| Adapter | Sign In | Sign Up |
|
| 449 |
+
| ---------------------- | ----------------------------------------- | ----------------------------------- |
|
| 450 |
+
| BetterAuthReactAdapter | `signIn.email({ email, password })` | `signUp.email({ email, password })` |
|
| 451 |
+
| SupabaseAuthAdapter | `signInWithPassword({ email, password })` | `signUp({ email, password })` |
|
.agents/skills/neon-postgres/references/neon-python-sdk.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon Python SDK
|
| 2 |
+
|
| 3 |
+
The `neon-api` Python SDK is a Pythonic wrapper around the Neon REST API for managing Neon resources programmatically.
|
| 4 |
+
|
| 5 |
+
For core concepts (Organization, Project, Branch, Endpoint, etc.), see `what-is-neon.md`.
|
| 6 |
+
|
| 7 |
+
See the [official Python SDK docs](https://neon.com/docs/reference/python-sdk.md) for complete details.
|
| 8 |
+
|
| 9 |
+
## Installation
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
pip install neon-api
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Authentication
|
| 16 |
+
|
| 17 |
+
```python
|
| 18 |
+
import os
|
| 19 |
+
from neon_api import NeonAPI
|
| 20 |
+
|
| 21 |
+
neon = NeonAPI(api_key=os.environ["NEON_API_KEY"])
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Org-Aware Workflow
|
| 25 |
+
|
| 26 |
+
All Neon accounts are organization-based. Discover the user's org first, then pass `org_id` to project operations:
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
# 1. Get the user's organizations
|
| 30 |
+
orgs = neon.current_user_organizations()
|
| 31 |
+
org_id = orgs[0].id
|
| 32 |
+
|
| 33 |
+
# 2. List projects within the org
|
| 34 |
+
projects = neon.projects(org_id=org_id)
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Method Quick Reference
|
| 38 |
+
|
| 39 |
+
### Projects
|
| 40 |
+
|
| 41 |
+
| Operation | Method |
|
| 42 |
+
| ------------------ | ------------------------------------------------------------------------------- |
|
| 43 |
+
| List projects | `neon.projects(org_id=...)` |
|
| 44 |
+
| Create project | `neon.project_create(project={ 'name': ..., 'pg_version': 17, 'org_id': ... })` |
|
| 45 |
+
| Get project | `neon.project(project_id=...)` |
|
| 46 |
+
| Update project | `neon.project_update(project_id=..., project={...})` |
|
| 47 |
+
| Delete project | `neon.project_delete(project_id=...)` |
|
| 48 |
+
| Get connection URI | `neon.connection_uri(project_id=..., database_name=..., role_name=...)` |
|
| 49 |
+
|
| 50 |
+
### Branches
|
| 51 |
+
|
| 52 |
+
| Operation | Method |
|
| 53 |
+
| ------------- | ------------------------------------------------------------------- |
|
| 54 |
+
| Create branch | `neon.branch_create(project_id=..., branch={...}, endpoints=[...])` |
|
| 55 |
+
| List branches | `neon.branches(project_id=...)` |
|
| 56 |
+
| Get branch | `neon.branch(project_id=..., branch_id=...)` |
|
| 57 |
+
| Update branch | `neon.branch_update(project_id=..., branch_id=..., branch={...})` |
|
| 58 |
+
| Delete branch | `neon.branch_delete(project_id=..., branch_id=...)` |
|
| 59 |
+
|
| 60 |
+
### Databases
|
| 61 |
+
|
| 62 |
+
| Operation | Method |
|
| 63 |
+
| --------------- | ---------------------------------------------------------------------- |
|
| 64 |
+
| Create database | `neon.database_create(project_id=..., branch_id=..., database={...})` |
|
| 65 |
+
| List databases | `neon.databases(project_id=..., branch_id=...)` |
|
| 66 |
+
| Delete database | `neon.database_delete(project_id=..., branch_id=..., database_id=...)` |
|
| 67 |
+
|
| 68 |
+
### Roles
|
| 69 |
+
|
| 70 |
+
| Operation | Method |
|
| 71 |
+
| ----------- | ---------------------------------------------------------------- |
|
| 72 |
+
| Create role | `neon.role_create(project_id=..., branch_id=..., role_name=...)` |
|
| 73 |
+
| List roles | `neon.roles(project_id=..., branch_id=...)` |
|
| 74 |
+
| Delete role | `neon.role_delete(project_id=..., branch_id=..., role_name=...)` |
|
| 75 |
+
|
| 76 |
+
### Endpoints
|
| 77 |
+
|
| 78 |
+
| Operation | Method |
|
| 79 |
+
| ---------------- | ----------------------------------------------------------------------- |
|
| 80 |
+
| Create endpoint | `neon.endpoint_create(project_id=..., endpoint={...})` |
|
| 81 |
+
| Start endpoint | `neon.endpoint_start(project_id=..., endpoint_id=...)` |
|
| 82 |
+
| Suspend endpoint | `neon.endpoint_suspend(project_id=..., endpoint_id=...)` |
|
| 83 |
+
| Update endpoint | `neon.endpoint_update(project_id=..., endpoint_id=..., endpoint={...})` |
|
| 84 |
+
| Delete endpoint | `neon.endpoint_delete(project_id=..., endpoint_id=...)` |
|
| 85 |
+
|
| 86 |
+
### Organizations
|
| 87 |
+
|
| 88 |
+
| Operation | Method |
|
| 89 |
+
| -------------- | ----------------------------------- |
|
| 90 |
+
| List user orgs | `neon.current_user_organizations()` |
|
| 91 |
+
| Get org | `neon.organization(org_id=...)` |
|
| 92 |
+
|
| 93 |
+
### API Keys & Operations
|
| 94 |
+
|
| 95 |
+
| Operation | Method |
|
| 96 |
+
| --------------- | -------------------------------------------------- |
|
| 97 |
+
| List API keys | `neon.api_keys()` |
|
| 98 |
+
| Create API key | `neon.api_key_create(key_name=...)` |
|
| 99 |
+
| Revoke API key | `neon.api_key_revoke(key_id)` |
|
| 100 |
+
| List operations | `neon.operations(project_id=...)` |
|
| 101 |
+
| Get operation | `neon.operation(project_id=..., operation_id=...)` |
|
.agents/skills/neon-postgres/references/neon-rest-api.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon REST API
|
| 2 |
+
|
| 3 |
+
Essentials for making direct HTTP requests to the Neon Platform API.
|
| 4 |
+
|
| 5 |
+
See the [official API reference](https://neon.com/docs/reference/api-reference.md) and [interactive explorer](https://api-docs.neon.tech/reference/getting-started-with-neon-api) for complete details. The full [OpenAPI spec](https://neon.com/api_spec/release/v2.json) is available for programmatic lookup of exact endpoints, request/response schemas, and required fields.
|
| 6 |
+
|
| 7 |
+
## Base URL
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
https://console.neon.tech/api/v2/
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
## Authentication
|
| 14 |
+
|
| 15 |
+
Include a Neon API key in every request:
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
Authorization: Bearer $NEON_API_KEY
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
### API Key Types
|
| 22 |
+
|
| 23 |
+
| Type | Scope | Best For |
|
| 24 |
+
| -------------- | ------------------------------- | ----------------------------- |
|
| 25 |
+
| Personal | All projects user has access to | Individual use, scripting |
|
| 26 |
+
| Organization | Entire organization | CI/CD, org-wide automation |
|
| 27 |
+
| Project-scoped | Single project only | Project-specific integrations |
|
| 28 |
+
|
| 29 |
+
## Rate Limits
|
| 30 |
+
|
| 31 |
+
- 700 requests/minute (~11/second)
|
| 32 |
+
- Bursts up to 40 requests/second per route
|
| 33 |
+
- Handle `429 Too Many Requests` with retry + backoff
|
| 34 |
+
|
| 35 |
+
## Common Endpoints
|
| 36 |
+
|
| 37 |
+
| Operation | Method | Path |
|
| 38 |
+
| ------------------ | -------- | -------------------------------------------------------- |
|
| 39 |
+
| List projects | `GET` | `/projects?org_id={org_id}` |
|
| 40 |
+
| List user orgs | `GET` | `/users/me/organizations` |
|
| 41 |
+
| Create project | `POST` | `/projects` (include `org_id` in body) |
|
| 42 |
+
| Get connection URI | `GET` | `/projects/{project_id}/connection_uri` |
|
| 43 |
+
| Create branch | `POST` | `/projects/{project_id}/branches` |
|
| 44 |
+
| List branches | `GET` | `/projects/{project_id}/branches` |
|
| 45 |
+
| Delete branch | `DELETE` | `/projects/{project_id}/branches/{branch_id}` |
|
| 46 |
+
| Start endpoint | `POST` | `/projects/{project_id}/endpoints/{endpoint_id}/start` |
|
| 47 |
+
| Suspend endpoint | `POST` | `/projects/{project_id}/endpoints/{endpoint_id}/suspend` |
|
| 48 |
+
| List databases | `GET` | `/projects/{project_id}/branches/{branch_id}/databases` |
|
| 49 |
+
| Create database | `POST` | `/projects/{project_id}/branches/{branch_id}/databases` |
|
| 50 |
+
| List roles | `GET` | `/projects/{project_id}/branches/{branch_id}/roles` |
|
| 51 |
+
| List API keys | `GET` | `/api_keys` |
|
| 52 |
+
| List operations | `GET` | `/projects/{project_id}/operations` |
|
| 53 |
+
|
| 54 |
+
## Important Constraints
|
| 55 |
+
|
| 56 |
+
- You **cannot delete** a project's root or default branch
|
| 57 |
+
- You **cannot delete** a branch that has child branches — delete all children first
|
| 58 |
+
- Creating a new role may **drop existing connections** to the active compute endpoint
|
| 59 |
+
- A branch can have only one `read_write` endpoint but multiple `read_only` endpoints
|
| 60 |
+
- Operations are async — poll operation status before starting dependent operations
|
| 61 |
+
- Operations older than 6 months may be deleted from Neon's systems
|
| 62 |
+
- The first API key must be created from the [Neon Console](https://console.neon.tech/app/settings/api-keys); subsequent keys can be created via the API
|
| 63 |
+
|
| 64 |
+
## Error Codes
|
| 65 |
+
|
| 66 |
+
| Status | Meaning | Action |
|
| 67 |
+
| ------ | ------------ | ------------------------ |
|
| 68 |
+
| 401 | Unauthorized | Check API key |
|
| 69 |
+
| 404 | Not Found | Verify resource ID |
|
| 70 |
+
| 429 | Rate Limited | Retry with backoff |
|
| 71 |
+
| 500 | Server Error | Retry or contact support |
|
| 72 |
+
|
| 73 |
+
For TypeScript SDK usage, see `neon-typescript-sdk.md`. For Python SDK, see `neon-python-sdk.md`.
|
.agents/skills/neon-postgres/references/neon-serverless.md
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon Serverless Driver
|
| 2 |
+
|
| 3 |
+
Patterns and best practices for connecting to Neon databases in serverless environments using the `@neondatabase/serverless` driver. The driver connects over **HTTP** for fast, single queries or **WebSockets** for `node-postgres` compatibility and interactive transactions.
|
| 4 |
+
|
| 5 |
+
See the [official serverless driver docs](https://neon.com/docs/serverless/serverless-driver.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Installation
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
# Using npm
|
| 11 |
+
npm install @neondatabase/serverless
|
| 12 |
+
|
| 13 |
+
# Using JSR
|
| 14 |
+
bunx jsr add @neon/serverless
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
**Note:** Version 1.0.0+ requires **Node.js v19 or later**.
|
| 18 |
+
|
| 19 |
+
For projects that depend on `pg` but want to use Neon's WebSocket-based connection pool:
|
| 20 |
+
|
| 21 |
+
```json
|
| 22 |
+
"dependencies": {
|
| 23 |
+
"pg": "npm:@neondatabase/serverless@^0.10.4"
|
| 24 |
+
},
|
| 25 |
+
"overrides": {
|
| 26 |
+
"pg": "npm:@neondatabase/serverless@^0.10.4"
|
| 27 |
+
}
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## Connection String
|
| 31 |
+
|
| 32 |
+
Always use environment variables:
|
| 33 |
+
|
| 34 |
+
```typescript
|
| 35 |
+
// For HTTP queries
|
| 36 |
+
import { neon } from "@neondatabase/serverless";
|
| 37 |
+
const sql = neon(process.env.DATABASE_URL!);
|
| 38 |
+
|
| 39 |
+
// For WebSocket connections
|
| 40 |
+
import { Pool } from "@neondatabase/serverless";
|
| 41 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL! });
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
**Never hardcode credentials:**
|
| 45 |
+
|
| 46 |
+
```typescript
|
| 47 |
+
// AVOID
|
| 48 |
+
const sql = neon("postgres://username:password@host.neon.tech/neondb");
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## HTTP Queries with `neon` function
|
| 52 |
+
|
| 53 |
+
Ideal for simple, "one-shot" queries in serverless/edge environments. Uses HTTP `fetch` - fastest method for single queries.
|
| 54 |
+
|
| 55 |
+
### Parameterized Queries
|
| 56 |
+
|
| 57 |
+
Use tagged template literals for safe parameter interpolation:
|
| 58 |
+
|
| 59 |
+
```typescript
|
| 60 |
+
const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
For manually constructed queries:
|
| 64 |
+
|
| 65 |
+
```typescript
|
| 66 |
+
const [post] = await sql.query("SELECT * FROM posts WHERE id = $1", [postId]);
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
**Never concatenate user input:**
|
| 70 |
+
|
| 71 |
+
```typescript
|
| 72 |
+
// AVOID: SQL Injection Risk
|
| 73 |
+
const [post] = await sql("SELECT * FROM posts WHERE id = " + postId);
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
### Configuration Options
|
| 77 |
+
|
| 78 |
+
```typescript
|
| 79 |
+
// Return rows as arrays instead of objects
|
| 80 |
+
const sqlArrayMode = neon(process.env.DATABASE_URL!, { arrayMode: true });
|
| 81 |
+
const rows = await sqlArrayMode`SELECT id, title FROM posts`;
|
| 82 |
+
// rows -> [[1, "First Post"], [2, "Second Post"]]
|
| 83 |
+
|
| 84 |
+
// Get full results including row count and field metadata
|
| 85 |
+
const sqlFull = neon(process.env.DATABASE_URL!, { fullResults: true });
|
| 86 |
+
const result = await sqlFull`SELECT * FROM posts LIMIT 1`;
|
| 87 |
+
// result -> { rows: [...], fields: [...], rowCount: 1, ... }
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
## WebSocket Connections with `Pool` and `Client`
|
| 91 |
+
|
| 92 |
+
Use for `node-postgres` compatibility, interactive transactions, or session support.
|
| 93 |
+
|
| 94 |
+
### WebSocket Configuration
|
| 95 |
+
|
| 96 |
+
For Node.js v21 and earlier:
|
| 97 |
+
|
| 98 |
+
```typescript
|
| 99 |
+
import { Pool, neonConfig } from "@neondatabase/serverless";
|
| 100 |
+
import ws from "ws";
|
| 101 |
+
|
| 102 |
+
// Required for Node.js < v22
|
| 103 |
+
neonConfig.webSocketConstructor = ws;
|
| 104 |
+
|
| 105 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL! });
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### Serverless Lifecycle Management
|
| 109 |
+
|
| 110 |
+
Create, use, and close the pool within the same invocation:
|
| 111 |
+
|
| 112 |
+
```typescript
|
| 113 |
+
// Vercel Edge Functions example
|
| 114 |
+
export default async (req: Request, ctx: ExecutionContext) => {
|
| 115 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL! });
|
| 116 |
+
|
| 117 |
+
try {
|
| 118 |
+
const { rows } = await pool.query("SELECT * FROM users");
|
| 119 |
+
return new Response(JSON.stringify(rows));
|
| 120 |
+
} catch (err) {
|
| 121 |
+
console.error(err);
|
| 122 |
+
return new Response("Database error", { status: 500 });
|
| 123 |
+
} finally {
|
| 124 |
+
ctx.waitUntil(pool.end());
|
| 125 |
+
}
|
| 126 |
+
};
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
**Avoid** creating a global `Pool` instance outside the handler.
|
| 130 |
+
|
| 131 |
+
## Transactions
|
| 132 |
+
|
| 133 |
+
### HTTP Transactions
|
| 134 |
+
|
| 135 |
+
For running multiple queries in a single, non-interactive transaction:
|
| 136 |
+
|
| 137 |
+
```typescript
|
| 138 |
+
const [newUser, newProfile] = await sql.transaction(
|
| 139 |
+
[
|
| 140 |
+
sql`INSERT INTO users(name) VALUES(${name}) RETURNING id`,
|
| 141 |
+
sql`INSERT INTO profiles(user_id, bio) VALUES(${userId}, ${bio})`,
|
| 142 |
+
],
|
| 143 |
+
{
|
| 144 |
+
isolationLevel: "ReadCommitted",
|
| 145 |
+
readOnly: false,
|
| 146 |
+
},
|
| 147 |
+
);
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
### Interactive Transactions
|
| 151 |
+
|
| 152 |
+
For complex transactions with conditional logic:
|
| 153 |
+
|
| 154 |
+
```typescript
|
| 155 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL! });
|
| 156 |
+
const client = await pool.connect();
|
| 157 |
+
try {
|
| 158 |
+
await client.query("BEGIN");
|
| 159 |
+
const {
|
| 160 |
+
rows: [{ id }],
|
| 161 |
+
} = await client.query("INSERT INTO users(name) VALUES($1) RETURNING id", [
|
| 162 |
+
name,
|
| 163 |
+
]);
|
| 164 |
+
await client.query("INSERT INTO profiles(user_id, bio) VALUES($1, $2)", [
|
| 165 |
+
id,
|
| 166 |
+
bio,
|
| 167 |
+
]);
|
| 168 |
+
await client.query("COMMIT");
|
| 169 |
+
} catch (err) {
|
| 170 |
+
await client.query("ROLLBACK");
|
| 171 |
+
throw err;
|
| 172 |
+
} finally {
|
| 173 |
+
client.release();
|
| 174 |
+
await pool.end();
|
| 175 |
+
}
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## Environment-Specific Optimizations
|
| 179 |
+
|
| 180 |
+
```javascript
|
| 181 |
+
// For Vercel Edge Functions, specify nearest region
|
| 182 |
+
export const config = {
|
| 183 |
+
runtime: "edge",
|
| 184 |
+
regions: ["iad1"], // Region nearest to your Neon DB
|
| 185 |
+
};
|
| 186 |
+
|
| 187 |
+
// For Cloudflare Workers, consider using Hyperdrive
|
| 188 |
+
// https://neon.com/blog/hyperdrive-neon-faq
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
## ORM Integration
|
| 192 |
+
|
| 193 |
+
For Drizzle ORM integration with the serverless driver, see `neon-drizzle.md`.
|
| 194 |
+
|
| 195 |
+
### Prisma
|
| 196 |
+
|
| 197 |
+
```typescript
|
| 198 |
+
import { neonConfig } from "@neondatabase/serverless";
|
| 199 |
+
import { PrismaNeon, PrismaNeonHTTP } from "@prisma/adapter-neon";
|
| 200 |
+
import { PrismaClient } from "@prisma/client";
|
| 201 |
+
import ws from "ws";
|
| 202 |
+
|
| 203 |
+
const connectionString = process.env.DATABASE_URL;
|
| 204 |
+
neonConfig.webSocketConstructor = ws;
|
| 205 |
+
|
| 206 |
+
// HTTP adapter
|
| 207 |
+
const adapterHttp = new PrismaNeonHTTP(connectionString!, {});
|
| 208 |
+
export const prismaClientHttp = new PrismaClient({ adapter: adapterHttp });
|
| 209 |
+
|
| 210 |
+
// WebSocket adapter
|
| 211 |
+
const adapterWs = new PrismaNeon({ connectionString });
|
| 212 |
+
export const prismaClientWs = new PrismaClient({ adapter: adapterWs });
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
### Kysely
|
| 216 |
+
|
| 217 |
+
```typescript
|
| 218 |
+
import { Pool } from "@neondatabase/serverless";
|
| 219 |
+
import { Kysely, PostgresDialect } from "kysely";
|
| 220 |
+
|
| 221 |
+
const dialect = new PostgresDialect({
|
| 222 |
+
pool: new Pool({ connectionString: process.env.DATABASE_URL }),
|
| 223 |
+
});
|
| 224 |
+
|
| 225 |
+
const db = new Kysely({ dialect });
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
**NOTE:** Do not pass the `neon()` function to ORMs that expect a `node-postgres` compatible `Pool`.
|
| 229 |
+
|
| 230 |
+
## Error Handling
|
| 231 |
+
|
| 232 |
+
```javascript
|
| 233 |
+
// Pool error handling
|
| 234 |
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
| 235 |
+
pool.on("error", (err) => {
|
| 236 |
+
console.error("Unexpected error on idle client", err);
|
| 237 |
+
process.exit(-1);
|
| 238 |
+
});
|
| 239 |
+
|
| 240 |
+
// Query error handling
|
| 241 |
+
try {
|
| 242 |
+
const [post] = await sql`SELECT * FROM posts WHERE id = ${postId}`;
|
| 243 |
+
if (!post) {
|
| 244 |
+
return new Response("Not found", { status: 404 });
|
| 245 |
+
}
|
| 246 |
+
} catch (err) {
|
| 247 |
+
console.error("Database query failed:", err);
|
| 248 |
+
return new Response("Server error", { status: 500 });
|
| 249 |
+
}
|
| 250 |
+
```
|
.agents/skills/neon-postgres/references/neon-typescript-sdk.md
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Neon TypeScript SDK
|
| 2 |
+
|
| 3 |
+
The `@neondatabase/api-client` TypeScript SDK is a typed wrapper around the Neon REST API for managing Neon resources programmatically.
|
| 4 |
+
|
| 5 |
+
For core concepts (Organization, Project, Branch, Endpoint, etc.), see `what-is-neon.md`.
|
| 6 |
+
|
| 7 |
+
See the [official TypeScript SDK docs](https://neon.com/docs/reference/typescript-sdk.md) for complete details.
|
| 8 |
+
|
| 9 |
+
## Installation
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
npm install @neondatabase/api-client
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Authentication
|
| 16 |
+
|
| 17 |
+
```typescript
|
| 18 |
+
import { createApiClient } from "@neondatabase/api-client";
|
| 19 |
+
|
| 20 |
+
const apiClient = createApiClient({ apiKey: process.env.NEON_API_KEY! });
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Org-Aware Workflow
|
| 24 |
+
|
| 25 |
+
All Neon accounts are organization-based. You must discover the user's org first, then pass `org_id` to project operations:
|
| 26 |
+
|
| 27 |
+
```typescript
|
| 28 |
+
// 1. Get the user's organizations
|
| 29 |
+
const { data: orgs } = await apiClient.getCurrentUserOrganizations();
|
| 30 |
+
const orgId = orgs.organizations[0].id;
|
| 31 |
+
|
| 32 |
+
// 2. List projects within the org
|
| 33 |
+
const { data: projects } = await apiClient.listProjects({ org_id: orgId });
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
## Method Quick Reference
|
| 37 |
+
|
| 38 |
+
### Projects
|
| 39 |
+
|
| 40 |
+
| Operation | Method |
|
| 41 |
+
| ------------------ | ------------------------------------------------------------------------------- |
|
| 42 |
+
| List projects | `apiClient.listProjects({ org_id })` |
|
| 43 |
+
| Create project | `apiClient.createProject({ project: { name, pg_version, region_id, org_id } })` |
|
| 44 |
+
| Get project | `apiClient.getProject(projectId)` |
|
| 45 |
+
| Update project | `apiClient.updateProject(projectId, { project: { name } })` |
|
| 46 |
+
| Delete project | `apiClient.deleteProject(projectId)` |
|
| 47 |
+
| Get connection URI | `apiClient.getConnectionUri({ projectId, database_name, role_name, pooled })` |
|
| 48 |
+
|
| 49 |
+
### Branches
|
| 50 |
+
|
| 51 |
+
| Operation | Method |
|
| 52 |
+
| ------------- | --------------------------------------------------------------------------------------- |
|
| 53 |
+
| Create branch | `apiClient.createProjectBranch(projectId, { branch: { name }, endpoints: [{ type }] })` |
|
| 54 |
+
| List branches | `apiClient.listProjectBranches({ projectId })` |
|
| 55 |
+
| Get branch | `apiClient.getProjectBranch(projectId, branchId)` |
|
| 56 |
+
| Update branch | `apiClient.updateProjectBranch(projectId, branchId, { branch: { name } })` |
|
| 57 |
+
| Delete branch | `apiClient.deleteProjectBranch(projectId, branchId)` |
|
| 58 |
+
|
| 59 |
+
### Databases
|
| 60 |
+
|
| 61 |
+
| Operation | Method |
|
| 62 |
+
| --------------- | ------------------------------------------------------------------------------------------------ |
|
| 63 |
+
| Create database | `apiClient.createProjectBranchDatabase(projectId, branchId, { database: { name, owner_name } })` |
|
| 64 |
+
| List databases | `apiClient.listProjectBranchDatabases(projectId, branchId)` |
|
| 65 |
+
| Delete database | `apiClient.deleteProjectBranchDatabase(projectId, branchId, databaseName)` |
|
| 66 |
+
|
| 67 |
+
### Roles
|
| 68 |
+
|
| 69 |
+
| Operation | Method |
|
| 70 |
+
| ----------- | ---------------------------------------------------------------------------- |
|
| 71 |
+
| Create role | `apiClient.createProjectBranchRole(projectId, branchId, { role: { name } })` |
|
| 72 |
+
| List roles | `apiClient.listProjectBranchRoles(projectId, branchId)` |
|
| 73 |
+
| Delete role | `apiClient.deleteProjectBranchRole(projectId, branchId, roleName)` |
|
| 74 |
+
|
| 75 |
+
### Endpoints
|
| 76 |
+
|
| 77 |
+
| Operation | Method |
|
| 78 |
+
| ---------------- | ------------------------------------------------------------------------------- |
|
| 79 |
+
| Create endpoint | `apiClient.createProjectEndpoint(projectId, { endpoint: { branch_id, type } })` |
|
| 80 |
+
| List endpoints | `apiClient.listProjectEndpoints(projectId)` |
|
| 81 |
+
| Start endpoint | `apiClient.startProjectEndpoint(projectId, endpointId)` |
|
| 82 |
+
| Suspend endpoint | `apiClient.suspendProjectEndpoint(projectId, endpointId)` |
|
| 83 |
+
| Restart endpoint | `apiClient.restartProjectEndpoint(projectId, endpointId)` |
|
| 84 |
+
| Update endpoint | `apiClient.updateProjectEndpoint(projectId, endpointId, { endpoint: {...} })` |
|
| 85 |
+
| Delete endpoint | `apiClient.deleteProjectEndpoint(projectId, endpointId)` |
|
| 86 |
+
|
| 87 |
+
### API Keys
|
| 88 |
+
|
| 89 |
+
| Operation | Method |
|
| 90 |
+
| ---------- | -------------------------------------- |
|
| 91 |
+
| List keys | `apiClient.listApiKeys()` |
|
| 92 |
+
| Create key | `apiClient.createApiKey({ key_name })` |
|
| 93 |
+
| Revoke key | `apiClient.revokeApiKey(keyId)` |
|
| 94 |
+
|
| 95 |
+
### Operations
|
| 96 |
+
|
| 97 |
+
| Operation | Method |
|
| 98 |
+
| --------------- | ------------------------------------------------------- |
|
| 99 |
+
| List operations | `apiClient.listProjectOperations({ projectId })` |
|
| 100 |
+
| Get operation | `apiClient.getProjectOperation(projectId, operationId)` |
|
| 101 |
+
|
| 102 |
+
### Organizations
|
| 103 |
+
|
| 104 |
+
| Operation | Method |
|
| 105 |
+
| -------------- | ------------------------------------------------------------------------ |
|
| 106 |
+
| List user orgs | `apiClient.getCurrentUserOrganizations()` |
|
| 107 |
+
| Get org | `apiClient.getOrganization(orgId)` |
|
| 108 |
+
| List members | `apiClient.getOrganizationMembers(orgId)` |
|
| 109 |
+
| Create org key | `apiClient.createOrgApiKey(orgId, { key_name, project_id? })` |
|
| 110 |
+
| Invite member | `apiClient.createOrganizationInvitations(orgId, { invitations: [...] })` |
|
| 111 |
+
|
| 112 |
+
## Error Handling
|
| 113 |
+
|
| 114 |
+
```typescript
|
| 115 |
+
try {
|
| 116 |
+
const response = await apiClient.getProject(projectId);
|
| 117 |
+
return response.data;
|
| 118 |
+
} catch (error: any) {
|
| 119 |
+
if (error.isAxiosError) {
|
| 120 |
+
const status = error.response?.status;
|
| 121 |
+
// 401 = bad API key, 404 = not found, 429 = rate limited
|
| 122 |
+
console.error("API error:", status, error.response?.data?.message);
|
| 123 |
+
}
|
| 124 |
+
return null;
|
| 125 |
+
}
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
## Key Types
|
| 129 |
+
|
| 130 |
+
```typescript
|
| 131 |
+
import { EndpointType, MemberRole } from "@neondatabase/api-client";
|
| 132 |
+
|
| 133 |
+
// EndpointType.ReadWrite, EndpointType.ReadOnly
|
| 134 |
+
// MemberRole.Admin, MemberRole.Member
|
| 135 |
+
```
|
.agents/skills/neon-postgres/references/what-is-neon.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# What is Neon
|
| 2 |
+
|
| 3 |
+
Neon is a serverless Postgres platform that separates compute and storage to offer autoscaling, branching, instant restore, and scale-to-zero.
|
| 4 |
+
|
| 5 |
+
See the [official introduction](https://neon.com/docs/introduction.md) for complete details.
|
| 6 |
+
|
| 7 |
+
## Core Concepts
|
| 8 |
+
|
| 9 |
+
| Concept | Description | Key Relationship |
|
| 10 |
+
| ---------------- | --------------------------------------------------------------------- | ------------------------- |
|
| 11 |
+
| Organization | Highest-level container for billing, users, and projects | Contains Projects |
|
| 12 |
+
| Project | Primary container for all database resources for an application | Contains Branches |
|
| 13 |
+
| Branch | Lightweight, copy-on-write clone of database state | Contains Databases, Roles |
|
| 14 |
+
| Compute Endpoint | Running PostgreSQL instance (CPU/RAM for queries) | Attached to a Branch |
|
| 15 |
+
| Database | Logical container for data (tables, schemas, views) | Exists within a Branch |
|
| 16 |
+
| Role | PostgreSQL role for authentication and authorization | Belongs to a Branch |
|
| 17 |
+
| Operation | Async action by the control plane (creating branch, starting compute) | Associated with Project |
|
| 18 |
+
|
| 19 |
+
## Key Differentiators
|
| 20 |
+
|
| 21 |
+
1. **Serverless Architecture**: Compute scales automatically and can suspend when idle
|
| 22 |
+
2. **Branching**: Create instant database copies without duplicating storage
|
| 23 |
+
3. **Separation of Compute and Storage**: Pay for compute only when active
|
| 24 |
+
4. **Postgres Compatible**: Works with any Postgres driver, ORM, or tool
|
| 25 |
+
|
| 26 |
+
## When to Use Neon
|
| 27 |
+
|
| 28 |
+
- **Serverless applications**: Functions that need database access without managing connections
|
| 29 |
+
- **Development workflows**: Branch databases like code for isolated testing
|
| 30 |
+
- **Variable workloads**: Auto-scale during traffic spikes, scale to zero when idle
|
| 31 |
+
- **Cost optimization**: Pay only for active compute time and storage used
|
| 32 |
+
|
| 33 |
+
## Further Reading
|
| 34 |
+
|
| 35 |
+
| Topic | URL |
|
| 36 |
+
| ---------------------- | ----------------------------------------------------------- |
|
| 37 |
+
| Architecture | https://neon.com/docs/introduction/architecture-overview.md |
|
| 38 |
+
| Plans & Billing | https://neon.com/docs/introduction/about-billing.md |
|
| 39 |
+
| Regions | https://neon.com/docs/introduction/regions.md |
|
| 40 |
+
| Postgres Compatibility | https://neon.com/docs/reference/compatibility.md |
|
Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
|
| 12 |
+
# CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "7860"]
|
| 13 |
+
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8001"]
|
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: uvicorn src.main:app --host 0.0.0.0 --port $PORT
|
backend.log
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INFO: Will watch for changes in these directories: ['D:\\GIAIC\\hackathon-2-phase-2\\hackathon-2-phase-2\\backend']
|
| 2 |
+
INFO: Uvicorn running on http://0.0.0.0:8001 (Press CTRL+C to quit)
|
| 3 |
+
INFO: Started reloader process [16028] using WatchFiles
|
| 4 |
+
INFO: Started server process [10448]
|
| 5 |
+
INFO: Waiting for application startup.
|
| 6 |
+
INFO: Application startup complete.
|
| 7 |
+
2026-02-21 17:37:27 - todo_app - INFO - Incoming request: POST /api/v1/auth/login
|
| 8 |
+
2026-02-21 17:37:27 - todo_app - INFO - Request: POST /auth/login (unauthenticated)
|
| 9 |
+
2026-02-21 17:37:27 - todo_app - INFO - Login attempt for email: demo@example.com
|
| 10 |
+
(trapped) error reading bcrypt version
|
| 11 |
+
Traceback (most recent call last):
|
| 12 |
+
File "C:\Users\SG\AppData\Local\Programs\Python\Python311\Lib\site-packages\passlib\handlers\bcrypt.py", line 620, in _load_backend_mixin
|
| 13 |
+
version = _bcrypt.__about__.__version__
|
| 14 |
+
^^^^^^^^^^^^^^^^^
|
| 15 |
+
AttributeError: module 'bcrypt' has no attribute '__about__'
|
| 16 |
+
2026-02-21 17:37:29 - todo_app - INFO - Authentication result: True
|
| 17 |
+
2026-02-21 17:37:29 - todo_app - INFO - Creating access token for user_id=1
|
| 18 |
+
2026-02-21 17:37:29 - todo_app - INFO - Access token created successfully
|
| 19 |
+
2026-02-21 17:37:29 - todo_app - INFO - User logged in successfully: user_id=1, email=demo@example.com
|
| 20 |
+
2026-02-21 17:37:29 - todo_app - INFO - Request completed: POST /api/v1/auth/login - Status: 200 - Time: 2.715s
|
| 21 |
+
INFO: 127.0.0.1:49892 - "POST /api/v1/auth/login HTTP/1.1" 200 OK
|
| 22 |
+
2026-02-21 17:37:31 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 23 |
+
2026-02-21 17:37:31 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'user-agent': 'python-requests/2.32.2', 'accept-encoding': 'gzip, deflate', 'accept': '*/*', 'connection': 'keep-alive', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjc5MjQ5fQ.vWKlcUe327d47Q3XzpDu83jcNO9C1bw3O4IxVQtMjB0'}
|
| 24 |
+
2026-02-21 17:37:31 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjc5MjQ5fQ.vWKlcUe327d47Q3XzpDu83jcNO9C1bw3O4IxVQtMjB0'
|
| 25 |
+
2026-02-21 17:37:31 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 26 |
+
2026-02-21 17:37:31 - todo_app - INFO - Token decoded successfully, user_id: 1
|
| 27 |
+
2026-02-21 17:37:31 - todo_app - INFO - Request: GET /tasks (user_id=1)
|
| 28 |
+
2026-02-21 17:37:32 - todo_app - INFO - Retrieved 0 tasks for user_id=1
|
| 29 |
+
2026-02-21 17:37:32 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.285s
|
| 30 |
+
INFO: 127.0.0.1:49900 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 31 |
+
2026-02-21 17:38:50 - todo_app - INFO - Incoming request: GET /
|
| 32 |
+
2026-02-21 17:38:50 - todo_app - INFO - Health check endpoint accessed
|
| 33 |
+
2026-02-21 17:38:50 - todo_app - INFO - Request completed: GET / - Status: 200 - Time: 0.003s
|
| 34 |
+
INFO: 127.0.0.1:49978 - "GET / HTTP/1.1" 200 OK
|
| 35 |
+
2026-02-21 17:40:22 - todo_app - INFO - Incoming request: GET /
|
| 36 |
+
2026-02-21 17:40:22 - todo_app - INFO - Health check endpoint accessed
|
| 37 |
+
2026-02-21 17:40:22 - todo_app - INFO - Request completed: GET / - Status: 200 - Time: 0.001s
|
| 38 |
+
INFO: 127.0.0.1:50098 - "GET / HTTP/1.1" 200 OK
|
| 39 |
+
2026-02-21 17:41:03 - todo_app - INFO - Incoming request: OPTIONS /api/v1/auth/login
|
| 40 |
+
2026-02-21 17:41:03 - todo_app - INFO - Request completed: OPTIONS /api/v1/auth/login - Status: 200 - Time: 0.000s
|
| 41 |
+
INFO: 127.0.0.1:50141 - "OPTIONS /api/v1/auth/login HTTP/1.1" 200 OK
|
| 42 |
+
2026-02-21 17:41:03 - todo_app - INFO - Incoming request: POST /api/v1/auth/login
|
| 43 |
+
2026-02-21 17:41:03 - todo_app - INFO - Request: POST /auth/login (unauthenticated)
|
| 44 |
+
2026-02-21 17:41:03 - todo_app - INFO - Login attempt for email: khizar@gmail.com
|
| 45 |
+
2026-02-21 17:41:03 - todo_app - INFO - Authentication result: True
|
| 46 |
+
2026-02-21 17:41:03 - todo_app - INFO - Creating access token for user_id=3
|
| 47 |
+
2026-02-21 17:41:03 - todo_app - INFO - Access token created successfully
|
| 48 |
+
2026-02-21 17:41:03 - todo_app - INFO - User logged in successfully: user_id=3, email=khizar@gmail.com
|
| 49 |
+
2026-02-21 17:41:03 - todo_app - INFO - Request completed: POST /api/v1/auth/login - Status: 200 - Time: 0.500s
|
| 50 |
+
INFO: 127.0.0.1:50141 - "POST /api/v1/auth/login HTTP/1.1" 200 OK
|
| 51 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 52 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 53 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.002s
|
| 54 |
+
INFO: 127.0.0.1:50141 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 55 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.002s
|
| 56 |
+
INFO: 127.0.0.1:50142 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 57 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 58 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 59 |
+
INFO: 127.0.0.1:50141 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 60 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 61 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.000s
|
| 62 |
+
INFO: 127.0.0.1:50142 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 63 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 64 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.000s
|
| 65 |
+
INFO: 127.0.0.1:50142 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 66 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 67 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.001s
|
| 68 |
+
INFO: 127.0.0.1:50141 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 69 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 70 |
+
2026-02-21 17:41:04 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 71 |
+
2026-02-21 17:41:04 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 72 |
+
2026-02-21 17:41:04 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 73 |
+
2026-02-21 17:41:04 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 74 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 75 |
+
2026-02-21 17:41:04 - todo_app - INFO - Retrieved 0 tasks for user_id=3
|
| 76 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.251s
|
| 77 |
+
INFO: 127.0.0.1:50142 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 78 |
+
2026-02-21 17:41:04 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 79 |
+
2026-02-21 17:41:04 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 80 |
+
2026-02-21 17:41:04 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 81 |
+
2026-02-21 17:41:04 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 82 |
+
2026-02-21 17:41:04 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 83 |
+
2026-02-21 17:41:04 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 84 |
+
2026-02-21 17:41:05 - todo_app - INFO - Retrieved 0 tasks for user_id=3
|
| 85 |
+
2026-02-21 17:41:05 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.721s
|
| 86 |
+
INFO: 127.0.0.1:50141 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 87 |
+
2026-02-21 17:41:27 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 88 |
+
2026-02-21 17:41:27 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.002s
|
| 89 |
+
INFO: 127.0.0.1:50158 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 90 |
+
2026-02-21 17:41:27 - todo_app - INFO - Incoming request: POST /api/v1/tasks
|
| 91 |
+
2026-02-21 17:41:27 - todo_app - INFO - Request completed: POST /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 92 |
+
INFO: 127.0.0.1:50158 - "POST /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 93 |
+
2026-02-21 17:41:27 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 94 |
+
2026-02-21 17:41:27 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.001s
|
| 95 |
+
INFO: 127.0.0.1:50158 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 96 |
+
2026-02-21 17:41:27 - todo_app - INFO - Incoming request: POST /api/v1/tasks/
|
| 97 |
+
2026-02-21 17:41:27 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 98 |
+
2026-02-21 17:41:27 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 99 |
+
2026-02-21 17:41:27 - todo_app - INFO - Request: POST /tasks (user_id=3)
|
| 100 |
+
2026-02-21 17:41:28 - todo_app - INFO - Task created: task_id=1, user_id=3
|
| 101 |
+
2026-02-21 17:41:28 - todo_app - INFO - Request completed: POST /api/v1/tasks/ - Status: 201 - Time: 0.640s
|
| 102 |
+
INFO: 127.0.0.1:50158 - "POST /api/v1/tasks/ HTTP/1.1" 201 Created
|
| 103 |
+
2026-02-21 17:41:38 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 104 |
+
2026-02-21 17:41:38 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 105 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 106 |
+
2026-02-21 17:41:38 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 107 |
+
2026-02-21 17:41:38 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 108 |
+
2026-02-21 17:41:38 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 109 |
+
2026-02-21 17:41:38 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 110 |
+
2026-02-21 17:41:38 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 111 |
+
2026-02-21 17:41:38 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 112 |
+
2026-02-21 17:41:38 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 113 |
+
2026-02-21 17:41:38 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.264s
|
| 114 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 115 |
+
2026-02-21 17:41:42 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/1
|
| 116 |
+
2026-02-21 17:41:42 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/1 - Status: 200 - Time: 0.002s
|
| 117 |
+
INFO: 127.0.0.1:50160 - "OPTIONS /api/v1/tasks/1 HTTP/1.1" 200 OK
|
| 118 |
+
2026-02-21 17:41:42 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/1
|
| 119 |
+
2026-02-21 17:41:42 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 120 |
+
2026-02-21 17:41:42 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 121 |
+
2026-02-21 17:41:42 - todo_app - INFO - Request: PUT /tasks/1 (user_id=3)
|
| 122 |
+
2026-02-21 17:41:43 - todo_app - INFO - Task updated: task_id=1, user_id=3
|
| 123 |
+
2026-02-21 17:41:43 - todo_app - INFO - Request completed: PUT /api/v1/tasks/1 - Status: 200 - Time: 0.712s
|
| 124 |
+
INFO: 127.0.0.1:50160 - "PUT /api/v1/tasks/1 HTTP/1.1" 200 OK
|
| 125 |
+
2026-02-21 17:41:47 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 126 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 127 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 128 |
+
2026-02-21 17:41:47 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 129 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 130 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 131 |
+
2026-02-21 17:41:47 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 132 |
+
2026-02-21 17:41:47 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 133 |
+
2026-02-21 17:41:47 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 134 |
+
2026-02-21 17:41:47 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 135 |
+
2026-02-21 17:41:47 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 136 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 137 |
+
2026-02-21 17:41:47 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 138 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.258s
|
| 139 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 140 |
+
2026-02-21 17:41:47 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 141 |
+
2026-02-21 17:41:47 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 142 |
+
2026-02-21 17:41:47 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 143 |
+
2026-02-21 17:41:47 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 144 |
+
2026-02-21 17:41:47 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 145 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 146 |
+
2026-02-21 17:41:47 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 147 |
+
2026-02-21 17:41:47 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.265s
|
| 148 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 149 |
+
2026-02-21 17:41:52 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/1
|
| 150 |
+
2026-02-21 17:41:52 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 151 |
+
2026-02-21 17:41:52 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 152 |
+
2026-02-21 17:41:52 - todo_app - INFO - Request: PUT /tasks/1 (user_id=3)
|
| 153 |
+
2026-02-21 17:41:53 - todo_app - INFO - Task updated: task_id=1, user_id=3
|
| 154 |
+
2026-02-21 17:41:53 - todo_app - INFO - Request completed: PUT /api/v1/tasks/1 - Status: 200 - Time: 0.679s
|
| 155 |
+
INFO: 127.0.0.1:50160 - "PUT /api/v1/tasks/1 HTTP/1.1" 200 OK
|
| 156 |
+
2026-02-21 17:41:57 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 157 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 158 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 159 |
+
2026-02-21 17:41:57 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 160 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.000s
|
| 161 |
+
INFO: 127.0.0.1:50178 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 162 |
+
2026-02-21 17:41:57 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 163 |
+
2026-02-21 17:41:57 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 164 |
+
2026-02-21 17:41:57 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 165 |
+
2026-02-21 17:41:57 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 166 |
+
2026-02-21 17:41:57 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 167 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 168 |
+
2026-02-21 17:41:57 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 169 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.256s
|
| 170 |
+
INFO: 127.0.0.1:50178 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 171 |
+
2026-02-21 17:41:57 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 172 |
+
2026-02-21 17:41:57 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 173 |
+
2026-02-21 17:41:57 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 174 |
+
2026-02-21 17:41:57 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 175 |
+
2026-02-21 17:41:57 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 176 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 177 |
+
2026-02-21 17:41:57 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 178 |
+
2026-02-21 17:41:57 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.254s
|
| 179 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 180 |
+
2026-02-21 17:42:02 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 181 |
+
2026-02-21 17:42:02 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 182 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 183 |
+
2026-02-21 17:42:02 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 184 |
+
2026-02-21 17:42:02 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 185 |
+
2026-02-21 17:42:02 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjc5NDYzfQ.gO9Nr9SEdYVpaN6FNRrGrw3LI3eufyn6r-htO6u1Yiw'
|
| 186 |
+
2026-02-21 17:42:02 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 187 |
+
2026-02-21 17:42:02 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 188 |
+
2026-02-21 17:42:02 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 189 |
+
2026-02-21 17:42:02 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 190 |
+
2026-02-21 17:42:02 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.260s
|
| 191 |
+
INFO: 127.0.0.1:50160 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 192 |
+
2026-02-21 17:42:06 - todo_app - INFO - Incoming request: DELETE /api/v1/tasks/1
|
| 193 |
+
2026-02-21 17:42:06 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 194 |
+
2026-02-21 17:42:06 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 195 |
+
2026-02-21 17:42:06 - todo_app - INFO - Request: DELETE /tasks/1 (user_id=3)
|
| 196 |
+
2026-02-21 17:42:07 - todo_app - INFO - Task deleted: task_id=1, user_id=3
|
| 197 |
+
2026-02-21 17:42:07 - todo_app - INFO - Request completed: DELETE /api/v1/tasks/1 - Status: 204 - Time: 0.428s
|
| 198 |
+
INFO: 127.0.0.1:50160 - "DELETE /api/v1/tasks/1 HTTP/1.1" 204 No Content
|
| 199 |
+
2026-02-21 17:50:11 - todo_app - INFO - Incoming request: POST /api/v1/auth/login
|
| 200 |
+
2026-02-21 17:50:11 - todo_app - INFO - Request: POST /auth/login (unauthenticated)
|
| 201 |
+
2026-02-21 17:50:11 - todo_app - INFO - Login attempt for email: khizar@gmail.com
|
| 202 |
+
2026-02-21 17:50:13 - todo_app - INFO - Authentication result: True
|
| 203 |
+
2026-02-21 17:50:13 - todo_app - INFO - Creating access token for user_id=3
|
| 204 |
+
2026-02-21 17:50:13 - todo_app - INFO - Access token created successfully
|
| 205 |
+
2026-02-21 17:50:13 - todo_app - INFO - User logged in successfully: user_id=3, email=khizar@gmail.com
|
| 206 |
+
2026-02-21 17:50:13 - todo_app - INFO - Request completed: POST /api/v1/auth/login - Status: 200 - Time: 1.543s
|
| 207 |
+
INFO: 127.0.0.1:50694 - "POST /api/v1/auth/login HTTP/1.1" 200 OK
|
| 208 |
+
2026-02-21 17:50:13 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 209 |
+
2026-02-21 17:50:13 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 210 |
+
INFO: 127.0.0.1:50694 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 211 |
+
2026-02-21 17:50:13 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 212 |
+
2026-02-21 17:50:13 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.000s
|
| 213 |
+
INFO: 127.0.0.1:50696 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 214 |
+
2026-02-21 17:50:13 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 215 |
+
2026-02-21 17:50:13 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 216 |
+
2026-02-21 17:50:13 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 217 |
+
2026-02-21 17:50:13 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 218 |
+
2026-02-21 17:50:13 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 219 |
+
2026-02-21 17:50:13 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 220 |
+
2026-02-21 17:50:14 - todo_app - INFO - Retrieved 0 tasks for user_id=3
|
| 221 |
+
2026-02-21 17:50:14 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.679s
|
| 222 |
+
INFO: 127.0.0.1:50694 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 223 |
+
2026-02-21 17:50:14 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 224 |
+
2026-02-21 17:50:14 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 225 |
+
2026-02-21 17:50:14 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 226 |
+
2026-02-21 17:50:14 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 227 |
+
2026-02-21 17:50:14 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 228 |
+
2026-02-21 17:50:14 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 229 |
+
2026-02-21 17:50:14 - todo_app - INFO - Retrieved 0 tasks for user_id=3
|
| 230 |
+
2026-02-21 17:50:14 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.258s
|
| 231 |
+
INFO: 127.0.0.1:50696 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 232 |
+
2026-02-21 17:50:45 - todo_app - INFO - Incoming request: POST /api/v1/tasks
|
| 233 |
+
2026-02-21 17:50:45 - todo_app - INFO - Request completed: POST /api/v1/tasks - Status: 307 - Time: 0.002s
|
| 234 |
+
INFO: 127.0.0.1:50718 - "POST /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 235 |
+
2026-02-21 17:50:45 - todo_app - INFO - Incoming request: POST /api/v1/tasks/
|
| 236 |
+
2026-02-21 17:50:45 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 237 |
+
2026-02-21 17:50:45 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 238 |
+
2026-02-21 17:50:45 - todo_app - INFO - Request: POST /tasks (user_id=3)
|
| 239 |
+
2026-02-21 17:50:46 - todo_app - INFO - Task created: task_id=2, user_id=3
|
| 240 |
+
2026-02-21 17:50:46 - todo_app - INFO - Request completed: POST /api/v1/tasks/ - Status: 201 - Time: 0.616s
|
| 241 |
+
INFO: 127.0.0.1:50718 - "POST /api/v1/tasks/ HTTP/1.1" 201 Created
|
| 242 |
+
2026-02-21 17:50:53 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 243 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.002s
|
| 244 |
+
INFO: 127.0.0.1:50719 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 245 |
+
2026-02-21 17:50:53 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 246 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.002s
|
| 247 |
+
INFO: 127.0.0.1:50719 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 248 |
+
2026-02-21 17:50:53 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 249 |
+
2026-02-21 17:50:53 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 250 |
+
2026-02-21 17:50:53 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 251 |
+
2026-02-21 17:50:53 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 252 |
+
2026-02-21 17:50:53 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 253 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 254 |
+
2026-02-21 17:50:53 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 255 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.246s
|
| 256 |
+
INFO: 127.0.0.1:50719 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 257 |
+
2026-02-21 17:50:53 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 258 |
+
2026-02-21 17:50:53 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 259 |
+
2026-02-21 17:50:53 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 260 |
+
2026-02-21 17:50:53 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 261 |
+
2026-02-21 17:50:53 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 262 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 263 |
+
2026-02-21 17:50:53 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 264 |
+
2026-02-21 17:50:53 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.274s
|
| 265 |
+
INFO: 127.0.0.1:50719 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 266 |
+
2026-02-21 17:50:57 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/2
|
| 267 |
+
2026-02-21 17:50:57 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/2 - Status: 200 - Time: 0.000s
|
| 268 |
+
INFO: 127.0.0.1:50719 - "OPTIONS /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 269 |
+
2026-02-21 17:50:57 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/2
|
| 270 |
+
2026-02-21 17:50:57 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 271 |
+
2026-02-21 17:50:57 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 272 |
+
2026-02-21 17:50:57 - todo_app - INFO - Request: PUT /tasks/2 (user_id=3)
|
| 273 |
+
2026-02-21 17:50:57 - todo_app - INFO - Task updated: task_id=2, user_id=3
|
| 274 |
+
2026-02-21 17:50:57 - todo_app - INFO - Request completed: PUT /api/v1/tasks/2 - Status: 200 - Time: 0.661s
|
| 275 |
+
INFO: 127.0.0.1:50719 - "PUT /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 276 |
+
2026-02-21 17:51:00 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/2
|
| 277 |
+
2026-02-21 17:51:00 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 278 |
+
2026-02-21 17:51:00 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 279 |
+
2026-02-21 17:51:00 - todo_app - INFO - Request: PUT /tasks/2 (user_id=3)
|
| 280 |
+
2026-02-21 17:51:01 - todo_app - INFO - Task updated: task_id=2, user_id=3
|
| 281 |
+
2026-02-21 17:51:01 - todo_app - INFO - Request completed: PUT /api/v1/tasks/2 - Status: 200 - Time: 0.678s
|
| 282 |
+
INFO: 127.0.0.1:50719 - "PUT /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 283 |
+
2026-02-21 17:51:04 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/2
|
| 284 |
+
2026-02-21 17:51:04 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 285 |
+
2026-02-21 17:51:04 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 286 |
+
2026-02-21 17:51:04 - todo_app - INFO - Request: PUT /tasks/2 (user_id=3)
|
| 287 |
+
2026-02-21 17:51:04 - todo_app - INFO - Task updated: task_id=2, user_id=3
|
| 288 |
+
2026-02-21 17:51:04 - todo_app - INFO - Request completed: PUT /api/v1/tasks/2 - Status: 200 - Time: 0.662s
|
| 289 |
+
INFO: 127.0.0.1:50719 - "PUT /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 290 |
+
2026-02-21 17:51:06 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/2
|
| 291 |
+
2026-02-21 17:51:06 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 292 |
+
2026-02-21 17:51:06 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 293 |
+
2026-02-21 17:51:06 - todo_app - INFO - Request: PUT /tasks/2 (user_id=3)
|
| 294 |
+
2026-02-21 17:51:06 - todo_app - INFO - Task updated: task_id=2, user_id=3
|
| 295 |
+
2026-02-21 17:51:06 - todo_app - INFO - Request completed: PUT /api/v1/tasks/2 - Status: 200 - Time: 0.665s
|
| 296 |
+
INFO: 127.0.0.1:50719 - "PUT /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 297 |
+
2026-02-21 17:51:14 - todo_app - INFO - Incoming request: PUT /api/v1/tasks/2
|
| 298 |
+
2026-02-21 17:51:14 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 299 |
+
2026-02-21 17:51:14 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 300 |
+
2026-02-21 17:51:14 - todo_app - INFO - Request: PUT /tasks/2 (user_id=3)
|
| 301 |
+
2026-02-21 17:51:15 - todo_app - INFO - Task updated: task_id=2, user_id=3
|
| 302 |
+
2026-02-21 17:51:15 - todo_app - INFO - Request completed: PUT /api/v1/tasks/2 - Status: 200 - Time: 0.672s
|
| 303 |
+
INFO: 127.0.0.1:50733 - "PUT /api/v1/tasks/2 HTTP/1.1" 200 OK
|
| 304 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 305 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 306 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.003s
|
| 307 |
+
INFO: 127.0.0.1:51348 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 308 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.003s
|
| 309 |
+
INFO: 127.0.0.1:51349 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 310 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 311 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 312 |
+
INFO: 127.0.0.1:51349 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 313 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 314 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 315 |
+
INFO: 127.0.0.1:51348 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 316 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 317 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.002s
|
| 318 |
+
INFO: 127.0.0.1:51348 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 319 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 320 |
+
2026-02-21 18:08:09 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 321 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.002s
|
| 322 |
+
INFO: 127.0.0.1:51349 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 323 |
+
2026-02-21 18:08:09 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 324 |
+
2026-02-21 18:08:09 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 325 |
+
2026-02-21 18:08:09 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 326 |
+
2026-02-21 18:08:09 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 327 |
+
2026-02-21 18:08:09 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 328 |
+
2026-02-21 18:08:10 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 329 |
+
2026-02-21 18:08:10 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 1.277s
|
| 330 |
+
INFO: 127.0.0.1:51348 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 331 |
+
2026-02-21 18:08:10 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 332 |
+
2026-02-21 18:08:10 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 333 |
+
2026-02-21 18:08:10 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwiZXhwIjoxNzcxNjgwMDEzfQ.cOaXGp8m3LrCx1ovc0CeFHDe9VB2j76zuWgTahVFzQ4'
|
| 334 |
+
2026-02-21 18:08:10 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 335 |
+
2026-02-21 18:08:10 - todo_app - INFO - Token decoded successfully, user_id: 3
|
| 336 |
+
2026-02-21 18:08:10 - todo_app - INFO - Request: GET /tasks (user_id=3)
|
| 337 |
+
2026-02-21 18:08:11 - todo_app - INFO - Retrieved 1 tasks for user_id=3
|
| 338 |
+
2026-02-21 18:08:11 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.706s
|
| 339 |
+
INFO: 127.0.0.1:51349 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 340 |
+
2026-02-21 18:08:18 - todo_app - INFO - Incoming request: OPTIONS /api/v1/auth/login
|
| 341 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request completed: OPTIONS /api/v1/auth/login - Status: 200 - Time: 0.001s
|
| 342 |
+
INFO: 127.0.0.1:51352 - "OPTIONS /api/v1/auth/login HTTP/1.1" 200 OK
|
| 343 |
+
2026-02-21 18:08:18 - todo_app - INFO - Incoming request: POST /api/v1/auth/login
|
| 344 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request: POST /auth/login (unauthenticated)
|
| 345 |
+
2026-02-21 18:08:18 - todo_app - INFO - Login attempt for email: demo@example.com
|
| 346 |
+
2026-02-21 18:08:18 - todo_app - INFO - Authentication result: True
|
| 347 |
+
2026-02-21 18:08:18 - todo_app - INFO - Creating access token for user_id=1
|
| 348 |
+
2026-02-21 18:08:18 - todo_app - INFO - Access token created successfully
|
| 349 |
+
2026-02-21 18:08:18 - todo_app - INFO - User logged in successfully: user_id=1, email=demo@example.com
|
| 350 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request completed: POST /api/v1/auth/login - Status: 200 - Time: 0.509s
|
| 351 |
+
INFO: 127.0.0.1:51352 - "POST /api/v1/auth/login HTTP/1.1" 200 OK
|
| 352 |
+
2026-02-21 18:08:18 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 353 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.002s
|
| 354 |
+
INFO: 127.0.0.1:51352 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 355 |
+
2026-02-21 18:08:18 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 356 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 357 |
+
INFO: 127.0.0.1:51352 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 358 |
+
2026-02-21 18:08:18 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 359 |
+
2026-02-21 18:08:18 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 360 |
+
2026-02-21 18:08:18 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4'
|
| 361 |
+
2026-02-21 18:08:18 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 362 |
+
2026-02-21 18:08:18 - todo_app - INFO - Token decoded successfully, user_id: 1
|
| 363 |
+
2026-02-21 18:08:18 - todo_app - INFO - Request: GET /tasks (user_id=1)
|
| 364 |
+
2026-02-21 18:08:19 - todo_app - INFO - Retrieved 0 tasks for user_id=1
|
| 365 |
+
2026-02-21 18:08:19 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.249s
|
| 366 |
+
INFO: 127.0.0.1:51352 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 367 |
+
2026-02-21 18:08:19 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 368 |
+
2026-02-21 18:08:19 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 369 |
+
2026-02-21 18:08:19 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4'
|
| 370 |
+
2026-02-21 18:08:19 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 371 |
+
2026-02-21 18:08:19 - todo_app - INFO - Token decoded successfully, user_id: 1
|
| 372 |
+
2026-02-21 18:08:19 - todo_app - INFO - Request: GET /tasks (user_id=1)
|
| 373 |
+
2026-02-21 18:08:19 - todo_app - INFO - Retrieved 0 tasks for user_id=1
|
| 374 |
+
2026-02-21 18:08:19 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.251s
|
| 375 |
+
INFO: 127.0.0.1:51352 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 376 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 377 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks
|
| 378 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.002s
|
| 379 |
+
INFO: 127.0.0.1:52041 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 380 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks - Status: 200 - Time: 0.001s
|
| 381 |
+
INFO: 127.0.0.1:52040 - "OPTIONS /api/v1/tasks HTTP/1.1" 200 OK
|
| 382 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 383 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.001s
|
| 384 |
+
INFO: 127.0.0.1:52040 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 385 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: GET /api/v1/tasks
|
| 386 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: GET /api/v1/tasks - Status: 307 - Time: 0.000s
|
| 387 |
+
INFO: 127.0.0.1:52041 - "GET /api/v1/tasks HTTP/1.1" 307 Temporary Redirect
|
| 388 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 389 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.001s
|
| 390 |
+
INFO: 127.0.0.1:52040 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 391 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: OPTIONS /api/v1/tasks/
|
| 392 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request completed: OPTIONS /api/v1/tasks/ - Status: 200 - Time: 0.001s
|
| 393 |
+
INFO: 127.0.0.1:52041 - "OPTIONS /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 394 |
+
2026-02-21 18:22:01 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 395 |
+
2026-02-21 18:22:01 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 396 |
+
2026-02-21 18:22:01 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4'
|
| 397 |
+
2026-02-21 18:22:01 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 398 |
+
2026-02-21 18:22:01 - todo_app - INFO - Token decoded successfully, user_id: 1
|
| 399 |
+
2026-02-21 18:22:01 - todo_app - INFO - Request: GET /tasks (user_id=1)
|
| 400 |
+
2026-02-21 18:22:02 - todo_app - INFO - Retrieved 0 tasks for user_id=1
|
| 401 |
+
2026-02-21 18:22:02 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 1.197s
|
| 402 |
+
INFO: 127.0.0.1:52040 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 403 |
+
2026-02-21 18:22:02 - todo_app - INFO - Incoming request: GET /api/v1/tasks/
|
| 404 |
+
2026-02-21 18:22:02 - todo_app - INFO - GET /tasks - Headers: {'host': 'localhost:8001', 'connection': 'keep-alive', 'sec-ch-ua-platform': '"Windows"', 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'sec-ch-ua': '"Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145"', 'sec-ch-ua-mobile': '?0', 'origin': 'http://localhost:3000', 'sec-fetch-site': 'same-site', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'http://localhost:3000/', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9'}
|
| 405 |
+
2026-02-21 18:22:02 - todo_app - INFO - GET /tasks - Credentials: scheme='Bearer' credentials='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzcxNjgxMDk4fQ.0T_b7MS_wwYPpdmprp1m8vpqQ9hEOeYS4bWAJoneiV4'
|
| 406 |
+
2026-02-21 18:22:02 - todo_app - INFO - Verifying token: eyJhbGciOiJIUzI1NiIs...
|
| 407 |
+
2026-02-21 18:22:02 - todo_app - INFO - Token decoded successfully, user_id: 1
|
| 408 |
+
2026-02-21 18:22:02 - todo_app - INFO - Request: GET /tasks (user_id=1)
|
| 409 |
+
2026-02-21 18:22:03 - todo_app - INFO - Retrieved 0 tasks for user_id=1
|
| 410 |
+
2026-02-21 18:22:03 - todo_app - INFO - Request completed: GET /api/v1/tasks/ - Status: 200 - Time: 0.715s
|
| 411 |
+
INFO: 127.0.0.1:52041 - "GET /api/v1/tasks/ HTTP/1.1" 200 OK
|
| 412 |
+
2026-02-21 18:24:25 - todo_app - INFO - Incoming request: OPTIONS /api/v1/auth/register
|
| 413 |
+
2026-02-21 18:24:25 - todo_app - INFO - Request completed: OPTIONS /api/v1/auth/register - Status: 400 - Time: 0.005s
|
| 414 |
+
INFO: 127.0.0.1:52140 - "OPTIONS /api/v1/auth/register HTTP/1.1" 400 Bad Request
|
| 415 |
+
2026-02-21 18:24:30 - todo_app - INFO - Incoming request: OPTIONS /api/v1/auth/register
|
| 416 |
+
2026-02-21 18:24:30 - todo_app - INFO - Request completed: OPTIONS /api/v1/auth/register - Status: 400 - Time: 0.000s
|
| 417 |
+
INFO: 127.0.0.1:52141 - "OPTIONS /api/v1/auth/register HTTP/1.1" 400 Bad Request
|
curl
ADDED
|
File without changes
|
logs/app_20260221.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
logs/error_20260221.log
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
migrations/convert-user-id-to-text.sql
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- Migration: Convert tasks.user_id from INTEGER to TEXT for Better Auth compatibility
|
| 2 |
+
-- Run this AFTER Better Auth tables are created and BEFORE creating new tasks
|
| 3 |
+
|
| 4 |
+
-- Step 1: Drop existing foreign key constraint if it exists
|
| 5 |
+
ALTER TABLE tasks DROP CONSTRAINT IF EXISTS tasks_user_id_fkey;
|
| 6 |
+
|
| 7 |
+
-- Step 2: Add a temporary column for the new TEXT user_id
|
| 8 |
+
ALTER TABLE tasks ADD COLUMN user_id_text TEXT;
|
| 9 |
+
|
| 10 |
+
-- Step 3: If you have existing tasks with INTEGER user_ids, you need to handle them
|
| 11 |
+
-- Option A: Delete all existing tasks (simplest for development)
|
| 12 |
+
-- TRUNCATE TABLE tasks;
|
| 13 |
+
|
| 14 |
+
-- Option B: Convert existing INTEGER user_ids to TEXT (if you want to keep data)
|
| 15 |
+
-- UPDATE tasks SET user_id_text = user_id::TEXT WHERE user_id IS NOT NULL;
|
| 16 |
+
|
| 17 |
+
-- Step 4: Drop the old INTEGER user_id column
|
| 18 |
+
ALTER TABLE tasks DROP COLUMN user_id;
|
| 19 |
+
|
| 20 |
+
-- Step 5: Rename the new column to user_id
|
| 21 |
+
ALTER TABLE tasks RENAME COLUMN user_id_text TO user_id;
|
| 22 |
+
|
| 23 |
+
-- Step 6: Make user_id NOT NULL (after ensuring all rows have values)
|
| 24 |
+
ALTER TABLE tasks ALTER COLUMN user_id SET NOT NULL;
|
| 25 |
+
|
| 26 |
+
-- Step 7: Add index on user_id for performance
|
| 27 |
+
CREATE INDEX IF NOT EXISTS idx_tasks_user_id ON tasks(user_id);
|
| 28 |
+
|
| 29 |
+
-- Step 8: Add foreign key constraint to Better Auth user table
|
| 30 |
+
ALTER TABLE tasks
|
| 31 |
+
ADD CONSTRAINT tasks_user_id_fkey
|
| 32 |
+
FOREIGN KEY (user_id) REFERENCES "user"(id) ON DELETE CASCADE;
|
| 33 |
+
|
| 34 |
+
-- Verify the migration
|
| 35 |
+
SELECT column_name, data_type, is_nullable
|
| 36 |
+
FROM information_schema.columns
|
| 37 |
+
WHERE table_name = 'tasks' AND column_name = 'user_id';
|
render.yaml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
- type: web
|
| 3 |
+
name: todo-backend
|
| 4 |
+
env: python
|
| 5 |
+
region: singapore
|
| 6 |
+
plan: free
|
| 7 |
+
buildCommand: pip install -r requirements.txt
|
| 8 |
+
startCommand: uvicorn src.main:app --host 0.0.0.0 --port $PORT
|
| 9 |
+
envVars:
|
| 10 |
+
- key: DATABASE_URL
|
| 11 |
+
sync: false
|
| 12 |
+
- key: JWT_SECRET
|
| 13 |
+
sync: false
|
| 14 |
+
- key: BETTER_AUTH_SECRET
|
| 15 |
+
sync: false
|
| 16 |
+
- key: ALLOWED_ORIGINS
|
| 17 |
+
value: https://your-frontend.vercel.app,http://localhost:3000
|
| 18 |
+
- key: ENVIRONMENT
|
| 19 |
+
value: production
|
requirements.txt
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
sqlmodel
|
| 4 |
+
asyncpg
|
| 5 |
+
pydantic
|
| 6 |
+
pydantic-settings
|
| 7 |
+
passlib[bcrypt]
|
| 8 |
+
python-jose[cryptography]
|
| 9 |
+
python-multipart
|
| 10 |
+
better-exceptions
|
| 11 |
+
python-dotenv
|
| 12 |
+
alembic
|
| 13 |
+
psycopg2-binary
|
| 14 |
+
httpx
|
| 15 |
+
requests
|
| 16 |
+
pytest
|
| 17 |
+
pytest-asyncio
|
| 18 |
+
pytest-cov
|
| 19 |
+
black
|
| 20 |
+
flake8
|
| 21 |
+
mypy
|
| 22 |
+
slowapi
|
| 23 |
+
|
run-migration.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Script to migrate tasks table user_id from INTEGER to TEXT
|
| 3 |
+
"""
|
| 4 |
+
import psycopg2
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
def run_migration():
|
| 11 |
+
"""Run the user_id conversion migration"""
|
| 12 |
+
database_url = os.getenv('DATABASE_URL')
|
| 13 |
+
|
| 14 |
+
if not database_url:
|
| 15 |
+
print("ERROR: DATABASE_URL not found in environment variables")
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
# Read the SQL file
|
| 20 |
+
with open('migrations/convert-user-id-to-text.sql', 'r') as f:
|
| 21 |
+
sql = f.read()
|
| 22 |
+
|
| 23 |
+
# Connect to database
|
| 24 |
+
print("Connecting to database...")
|
| 25 |
+
conn = psycopg2.connect(database_url)
|
| 26 |
+
cursor = conn.cursor()
|
| 27 |
+
|
| 28 |
+
# Execute migration
|
| 29 |
+
print("Running user_id conversion migration...")
|
| 30 |
+
print("WARNING: This will delete all existing tasks!")
|
| 31 |
+
print("Press Ctrl+C to cancel, or Enter to continue...")
|
| 32 |
+
input()
|
| 33 |
+
|
| 34 |
+
cursor.execute(sql)
|
| 35 |
+
conn.commit()
|
| 36 |
+
|
| 37 |
+
print("SUCCESS: Migration completed successfully!")
|
| 38 |
+
print("\nVerifying migration...")
|
| 39 |
+
|
| 40 |
+
# Verify the change
|
| 41 |
+
cursor.execute("""
|
| 42 |
+
SELECT column_name, data_type, is_nullable
|
| 43 |
+
FROM information_schema.columns
|
| 44 |
+
WHERE table_name = 'tasks' AND column_name = 'user_id';
|
| 45 |
+
""")
|
| 46 |
+
result = cursor.fetchone()
|
| 47 |
+
if result:
|
| 48 |
+
print(f"Column: {result[0]}, Type: {result[1]}, Nullable: {result[2]}")
|
| 49 |
+
else:
|
| 50 |
+
print("ERROR: user_id column not found!")
|
| 51 |
+
|
| 52 |
+
# Close connection
|
| 53 |
+
cursor.close()
|
| 54 |
+
conn.close()
|
| 55 |
+
|
| 56 |
+
return True
|
| 57 |
+
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"ERROR: Migration failed: {e}")
|
| 60 |
+
return False
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
print("=" * 50)
|
| 64 |
+
print("Tasks Table Migration")
|
| 65 |
+
print("Convert user_id from INTEGER to TEXT")
|
| 66 |
+
print("=" * 50)
|
| 67 |
+
run_migration()
|
src/api/auth_router.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
| 2 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from jose import JWTError, jwt
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from slowapi import Limiter
|
| 8 |
+
from slowapi.util import get_remote_address
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
import os
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
from ..database import get_db
|
| 14 |
+
from ..models.user import UserCreate, UserResponse
|
| 15 |
+
from ..services.user_service import UserService
|
| 16 |
+
from ..utils.logger import logger, log_error, log_request, log_security_event
|
| 17 |
+
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
+
# JWT Configuration
|
| 21 |
+
SECRET_KEY = os.getenv("JWT_SECRET", "your-super-secret-jwt-key-change-in-production")
|
| 22 |
+
ALGORITHM = "HS256"
|
| 23 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 30))
|
| 24 |
+
|
| 25 |
+
router = APIRouter()
|
| 26 |
+
security = HTTPBearer()
|
| 27 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 28 |
+
|
| 29 |
+
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
| 30 |
+
"""
|
| 31 |
+
Create a new access token
|
| 32 |
+
"""
|
| 33 |
+
to_encode = data.copy()
|
| 34 |
+
if expires_delta:
|
| 35 |
+
expire = datetime.utcnow() + expires_delta
|
| 36 |
+
else:
|
| 37 |
+
expire = datetime.utcnow() + timedelta(minutes=15)
|
| 38 |
+
|
| 39 |
+
to_encode.update({"exp": expire})
|
| 40 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 41 |
+
return encoded_jwt
|
| 42 |
+
|
| 43 |
+
def verify_token(token: str):
|
| 44 |
+
"""
|
| 45 |
+
Verify and decode a JWT token from Better Auth
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 49 |
+
user_id: str = payload.get("sub") # Better Auth uses string IDs
|
| 50 |
+
if user_id is None:
|
| 51 |
+
log_security_event("Invalid token - missing user_id")
|
| 52 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 53 |
+
return user_id # Return as string
|
| 54 |
+
except JWTError as e:
|
| 55 |
+
log_security_event("JWT verification failed", {"error": str(e)})
|
| 56 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 57 |
+
|
| 58 |
+
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
| 59 |
+
@limiter.limit("5/minute")
|
| 60 |
+
def register(request: Request, user: UserCreate, db: Session = Depends(get_db)):
|
| 61 |
+
"""
|
| 62 |
+
Register a new user
|
| 63 |
+
"""
|
| 64 |
+
try:
|
| 65 |
+
log_request("POST", "/auth/register")
|
| 66 |
+
logger.info(f"Registration attempt for email: {user.email}")
|
| 67 |
+
|
| 68 |
+
# Check if user already exists
|
| 69 |
+
existing_user = UserService.get_user_by_email(db, user.email)
|
| 70 |
+
if existing_user:
|
| 71 |
+
log_security_event("Registration failed - email already exists", {"email": user.email})
|
| 72 |
+
raise HTTPException(
|
| 73 |
+
status_code=status.HTTP_409_CONFLICT,
|
| 74 |
+
detail="Email already registered"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
existing_username = UserService.get_user_by_username(db, user.username)
|
| 78 |
+
if existing_username:
|
| 79 |
+
log_security_event("Registration failed - username already taken", {"username": user.username})
|
| 80 |
+
raise HTTPException(
|
| 81 |
+
status_code=status.HTTP_409_CONFLICT,
|
| 82 |
+
detail="Username already taken"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Create new user
|
| 86 |
+
db_user = UserService.create_user(db, user)
|
| 87 |
+
logger.info(f"User registered successfully: user_id={db_user.id}, email={user.email}")
|
| 88 |
+
return db_user
|
| 89 |
+
except HTTPException:
|
| 90 |
+
raise
|
| 91 |
+
except Exception as e:
|
| 92 |
+
log_error(e, "register")
|
| 93 |
+
raise HTTPException(
|
| 94 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 95 |
+
detail="Failed to register user"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
class LoginRequest(BaseModel):
|
| 99 |
+
email: str
|
| 100 |
+
password: str
|
| 101 |
+
|
| 102 |
+
@router.post("/login")
|
| 103 |
+
@limiter.limit("10/minute")
|
| 104 |
+
def login(request: Request, login_data: LoginRequest, db: Session = Depends(get_db)):
|
| 105 |
+
"""
|
| 106 |
+
Authenticate user and return JWT token
|
| 107 |
+
"""
|
| 108 |
+
try:
|
| 109 |
+
log_request("POST", "/auth/login")
|
| 110 |
+
logger.info(f"Login attempt for email: {login_data.email}")
|
| 111 |
+
|
| 112 |
+
user = UserService.authenticate_user(db, login_data.email, login_data.password)
|
| 113 |
+
logger.info(f"Authentication result: {user is not None}")
|
| 114 |
+
|
| 115 |
+
if not user:
|
| 116 |
+
log_security_event("Failed login attempt", {"email": login_data.email})
|
| 117 |
+
raise HTTPException(
|
| 118 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 119 |
+
detail="Incorrect email or password"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
logger.info(f"Creating access token for user_id={user.id}")
|
| 123 |
+
# Create access token
|
| 124 |
+
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 125 |
+
access_token = create_access_token(
|
| 126 |
+
data={"sub": str(user.id)}, expires_delta=access_token_expires
|
| 127 |
+
)
|
| 128 |
+
logger.info(f"Access token created successfully")
|
| 129 |
+
|
| 130 |
+
logger.info(f"User logged in successfully: user_id={user.id}, email={login_data.email}")
|
| 131 |
+
return {
|
| 132 |
+
"access_token": access_token,
|
| 133 |
+
"token_type": "bearer",
|
| 134 |
+
"user_id": user.id,
|
| 135 |
+
"username": user.username
|
| 136 |
+
}
|
| 137 |
+
except HTTPException:
|
| 138 |
+
raise
|
| 139 |
+
except Exception as e:
|
| 140 |
+
logger.error(f"Login exception: {type(e).__name__}: {str(e)}")
|
| 141 |
+
import traceback
|
| 142 |
+
logger.error(f"Traceback: {traceback.format_exc()}")
|
| 143 |
+
log_error(e, "login")
|
| 144 |
+
raise HTTPException(
|
| 145 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 146 |
+
detail="Failed to authenticate user"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
@router.get("/me", response_model=UserResponse)
|
| 150 |
+
@limiter.limit("60/minute")
|
| 151 |
+
def get_current_user(
|
| 152 |
+
request: Request,
|
| 153 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 154 |
+
db: Session = Depends(get_db)
|
| 155 |
+
):
|
| 156 |
+
"""
|
| 157 |
+
Get current authenticated user
|
| 158 |
+
"""
|
| 159 |
+
try:
|
| 160 |
+
user_id = verify_token(credentials.credentials)
|
| 161 |
+
log_request("GET", "/auth/me", user_id)
|
| 162 |
+
|
| 163 |
+
user = UserService.get_user_by_id(db, user_id)
|
| 164 |
+
if not user:
|
| 165 |
+
logger.warning(f"User not found: user_id={user_id}")
|
| 166 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 167 |
+
|
| 168 |
+
logger.info(f"Retrieved current user: user_id={user_id}")
|
| 169 |
+
return user
|
| 170 |
+
except HTTPException:
|
| 171 |
+
raise
|
| 172 |
+
except Exception as e:
|
| 173 |
+
log_error(e, "get_current_user")
|
| 174 |
+
raise HTTPException(
|
| 175 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 176 |
+
detail="Failed to retrieve user information"
|
| 177 |
+
)
|
src/api/task_router.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
| 2 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
from slowapi import Limiter
|
| 6 |
+
from slowapi.util import get_remote_address
|
| 7 |
+
from jose import JWTError, jwt
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
from ..database import get_db
|
| 12 |
+
from ..models.task import TaskCreate, TaskUpdate, TaskResponse
|
| 13 |
+
from ..models.user import UserResponse
|
| 14 |
+
from ..services.task_service import TaskService
|
| 15 |
+
from ..services.user_service import UserService
|
| 16 |
+
from ..utils.logger import logger, log_error, log_request
|
| 17 |
+
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
+
# JWT Configuration (same as auth_router)
|
| 21 |
+
SECRET_KEY = os.getenv("JWT_SECRET", "your-super-secret-jwt-key-change-in-production")
|
| 22 |
+
ALGORITHM = "HS256"
|
| 23 |
+
|
| 24 |
+
router = APIRouter()
|
| 25 |
+
security = HTTPBearer()
|
| 26 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 27 |
+
|
| 28 |
+
def verify_token(token: str) -> str:
|
| 29 |
+
"""
|
| 30 |
+
Verify and decode a JWT token
|
| 31 |
+
Returns user_id as string
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
logger.info(f"Verifying token: {token[:20]}...")
|
| 35 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 36 |
+
user_id: str = payload.get("sub")
|
| 37 |
+
logger.info(f"Token decoded successfully, user_id: {user_id}")
|
| 38 |
+
if user_id is None:
|
| 39 |
+
logger.error("Token payload missing 'sub' field")
|
| 40 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 41 |
+
return user_id
|
| 42 |
+
except JWTError as e:
|
| 43 |
+
logger.error(f"JWT verification failed: {str(e)}")
|
| 44 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 45 |
+
|
| 46 |
+
@router.get("/", response_model=List[TaskResponse])
|
| 47 |
+
@limiter.limit("60/minute")
|
| 48 |
+
def get_tasks(
|
| 49 |
+
request: Request,
|
| 50 |
+
skip: int = 0,
|
| 51 |
+
limit: int = 100,
|
| 52 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 53 |
+
db: Session = Depends(get_db)
|
| 54 |
+
):
|
| 55 |
+
"""
|
| 56 |
+
Get all tasks for the authenticated user (JWT)
|
| 57 |
+
"""
|
| 58 |
+
try:
|
| 59 |
+
logger.info(f"GET /tasks - Headers: {dict(request.headers)}")
|
| 60 |
+
logger.info(f"GET /tasks - Credentials: {credentials}")
|
| 61 |
+
|
| 62 |
+
user_id = verify_token(credentials.credentials)
|
| 63 |
+
log_request("GET", "/tasks", user_id)
|
| 64 |
+
|
| 65 |
+
tasks = TaskService.get_tasks_for_user(db, user_id, skip=skip, limit=limit)
|
| 66 |
+
logger.info(f"Retrieved {len(tasks)} tasks for user_id={user_id}")
|
| 67 |
+
return tasks
|
| 68 |
+
except HTTPException:
|
| 69 |
+
raise
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.error(f"Error in get_tasks: {str(e)}")
|
| 72 |
+
log_error(e, "get_tasks")
|
| 73 |
+
raise HTTPException(
|
| 74 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 75 |
+
detail="Failed to retrieve tasks"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
@router.post("/", response_model=TaskResponse, status_code=status.HTTP_201_CREATED)
|
| 79 |
+
@limiter.limit("30/minute")
|
| 80 |
+
def create_task(
|
| 81 |
+
request: Request,
|
| 82 |
+
task: TaskCreate,
|
| 83 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 84 |
+
db: Session = Depends(get_db)
|
| 85 |
+
):
|
| 86 |
+
"""
|
| 87 |
+
Create a new task for the authenticated user (JWT)
|
| 88 |
+
"""
|
| 89 |
+
try:
|
| 90 |
+
user_id = verify_token(credentials.credentials)
|
| 91 |
+
log_request("POST", "/tasks", user_id)
|
| 92 |
+
|
| 93 |
+
# Validate status field
|
| 94 |
+
if task.status not in ["pending", "in-progress", "completed"]:
|
| 95 |
+
logger.warning(f"Invalid status provided: {task.status}")
|
| 96 |
+
raise HTTPException(
|
| 97 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 98 |
+
detail="Status must be one of: pending, in-progress, completed"
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
created_task = TaskService.create_task(db, task, user_id)
|
| 102 |
+
logger.info(f"Task created: task_id={created_task.id}, user_id={user_id}")
|
| 103 |
+
return created_task
|
| 104 |
+
except HTTPException:
|
| 105 |
+
raise
|
| 106 |
+
except ValueError as e:
|
| 107 |
+
logger.error(f"Validation error in create_task: {str(e)}")
|
| 108 |
+
raise HTTPException(
|
| 109 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 110 |
+
detail=str(e)
|
| 111 |
+
)
|
| 112 |
+
except Exception as e:
|
| 113 |
+
log_error(e, "create_task")
|
| 114 |
+
raise HTTPException(
|
| 115 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 116 |
+
detail="Failed to create task"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
@router.get("/{task_id}", response_model=TaskResponse)
|
| 120 |
+
@limiter.limit("60/minute")
|
| 121 |
+
def get_task(
|
| 122 |
+
request: Request,
|
| 123 |
+
task_id: int,
|
| 124 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 125 |
+
db: Session = Depends(get_db)
|
| 126 |
+
):
|
| 127 |
+
"""
|
| 128 |
+
Get a specific task by ID for the authenticated user (JWT)
|
| 129 |
+
"""
|
| 130 |
+
try:
|
| 131 |
+
user_id = verify_token(credentials.credentials)
|
| 132 |
+
log_request("GET", f"/tasks/{task_id}", user_id)
|
| 133 |
+
|
| 134 |
+
task = TaskService.get_task_by_id(db, task_id, user_id)
|
| 135 |
+
if not task:
|
| 136 |
+
logger.warning(f"Task not found or unauthorized: task_id={task_id}, user_id={user_id}")
|
| 137 |
+
raise HTTPException(status_code=404, detail="Task not found")
|
| 138 |
+
|
| 139 |
+
logger.info(f"Retrieved task: task_id={task_id}, user_id={user_id}")
|
| 140 |
+
return task
|
| 141 |
+
except HTTPException:
|
| 142 |
+
raise
|
| 143 |
+
except Exception as e:
|
| 144 |
+
log_error(e, "get_task")
|
| 145 |
+
raise HTTPException(
|
| 146 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 147 |
+
detail="Failed to retrieve task"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@router.put("/{task_id}", response_model=TaskResponse)
|
| 151 |
+
@limiter.limit("30/minute")
|
| 152 |
+
def update_task(
|
| 153 |
+
request: Request,
|
| 154 |
+
task_id: int,
|
| 155 |
+
task_update: TaskUpdate,
|
| 156 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 157 |
+
db: Session = Depends(get_db)
|
| 158 |
+
):
|
| 159 |
+
"""
|
| 160 |
+
Update a specific task for the authenticated user (JWT)
|
| 161 |
+
"""
|
| 162 |
+
try:
|
| 163 |
+
user_id = verify_token(credentials.credentials)
|
| 164 |
+
log_request("PUT", f"/tasks/{task_id}", user_id)
|
| 165 |
+
|
| 166 |
+
# Validate status field if provided
|
| 167 |
+
if task_update.status and task_update.status not in ["pending", "in-progress", "completed"]:
|
| 168 |
+
logger.warning(f"Invalid status provided: {task_update.status}")
|
| 169 |
+
raise HTTPException(
|
| 170 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 171 |
+
detail="Status must be one of: pending, in-progress, completed"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
updated_task = TaskService.update_task(db, task_id, task_update, user_id)
|
| 175 |
+
if not updated_task:
|
| 176 |
+
logger.warning(f"Task not found or unauthorized: task_id={task_id}, user_id={user_id}")
|
| 177 |
+
raise HTTPException(status_code=404, detail="Task not found")
|
| 178 |
+
|
| 179 |
+
logger.info(f"Task updated: task_id={task_id}, user_id={user_id}")
|
| 180 |
+
return updated_task
|
| 181 |
+
except HTTPException:
|
| 182 |
+
raise
|
| 183 |
+
except ValueError as e:
|
| 184 |
+
logger.error(f"Validation error in update_task: {str(e)}")
|
| 185 |
+
raise HTTPException(
|
| 186 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 187 |
+
detail=str(e)
|
| 188 |
+
)
|
| 189 |
+
except Exception as e:
|
| 190 |
+
log_error(e, "update_task")
|
| 191 |
+
raise HTTPException(
|
| 192 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 193 |
+
detail="Failed to update task"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
|
| 197 |
+
@limiter.limit("30/minute")
|
| 198 |
+
def delete_task(
|
| 199 |
+
request: Request,
|
| 200 |
+
task_id: int,
|
| 201 |
+
credentials: HTTPAuthorizationCredentials = Depends(security),
|
| 202 |
+
db: Session = Depends(get_db)
|
| 203 |
+
):
|
| 204 |
+
"""
|
| 205 |
+
Delete a specific task for the authenticated user (JWT)
|
| 206 |
+
"""
|
| 207 |
+
try:
|
| 208 |
+
user_id = verify_token(credentials.credentials)
|
| 209 |
+
log_request("DELETE", f"/tasks/{task_id}", user_id)
|
| 210 |
+
|
| 211 |
+
success = TaskService.delete_task(db, task_id, user_id)
|
| 212 |
+
if not success:
|
| 213 |
+
logger.warning(f"Task not found or unauthorized: task_id={task_id}, user_id={user_id}")
|
| 214 |
+
raise HTTPException(status_code=404, detail="Task not found")
|
| 215 |
+
|
| 216 |
+
logger.info(f"Task deleted: task_id={task_id}, user_id={user_id}")
|
| 217 |
+
return {"message": "Task deleted successfully"}
|
| 218 |
+
except HTTPException:
|
| 219 |
+
raise
|
| 220 |
+
except Exception as e:
|
| 221 |
+
log_error(e, "delete_task")
|
| 222 |
+
raise HTTPException(
|
| 223 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 224 |
+
detail="Failed to delete task"
|
| 225 |
+
)
|
src/auth/better_auth.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Better Auth session verification for FastAPI backend
|
| 3 |
+
"""
|
| 4 |
+
from fastapi import HTTPException, status, Request
|
| 5 |
+
from sqlalchemy import text
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import os
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
from urllib.parse import unquote
|
| 10 |
+
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
def verify_better_auth_session(request: Request) -> str:
|
| 14 |
+
"""
|
| 15 |
+
Verify Better Auth session from cookie
|
| 16 |
+
Returns user_id (TEXT) if valid
|
| 17 |
+
"""
|
| 18 |
+
# Get session token from cookie
|
| 19 |
+
session_cookie = request.cookies.get("better-auth.session_token")
|
| 20 |
+
|
| 21 |
+
print(f"[DEBUG] Raw cookie value: {session_cookie}")
|
| 22 |
+
|
| 23 |
+
if not session_cookie:
|
| 24 |
+
print("[DEBUG] No session cookie found")
|
| 25 |
+
raise HTTPException(
|
| 26 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 27 |
+
detail="Not authenticated"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
# URL decode the cookie value
|
| 31 |
+
session_token = unquote(session_cookie)
|
| 32 |
+
print(f"[DEBUG] Decoded session token: {session_token}")
|
| 33 |
+
|
| 34 |
+
# Better Auth cookie format: sessionId.signature
|
| 35 |
+
# We need just the sessionId part (before the first dot)
|
| 36 |
+
if '.' in session_token:
|
| 37 |
+
session_id = session_token.split('.')[0]
|
| 38 |
+
else:
|
| 39 |
+
session_id = session_token
|
| 40 |
+
|
| 41 |
+
print(f"[DEBUG] Extracted session ID: {session_id}")
|
| 42 |
+
|
| 43 |
+
# Query the database to verify the session
|
| 44 |
+
from ..database import engine
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
with engine.connect() as conn:
|
| 48 |
+
result = conn.execute(
|
| 49 |
+
text("""
|
| 50 |
+
SELECT "userId", "expiresAt"
|
| 51 |
+
FROM session
|
| 52 |
+
WHERE id = :session_id
|
| 53 |
+
"""),
|
| 54 |
+
{"session_id": session_id}
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
row = result.fetchone()
|
| 58 |
+
|
| 59 |
+
if not row:
|
| 60 |
+
print(f"[DEBUG] No session found in database for ID: {session_id}")
|
| 61 |
+
raise HTTPException(
|
| 62 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 63 |
+
detail="Invalid session"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
user_id, expires_at = row
|
| 67 |
+
print(f"[DEBUG] Found session - User ID: {user_id}, Expires: {expires_at}")
|
| 68 |
+
|
| 69 |
+
# Check if session is expired
|
| 70 |
+
if expires_at < datetime.utcnow():
|
| 71 |
+
print(f"[DEBUG] Session expired")
|
| 72 |
+
raise HTTPException(
|
| 73 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 74 |
+
detail="Session expired"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
print(f"[DEBUG] Session valid, returning user_id: {user_id}")
|
| 78 |
+
return user_id
|
| 79 |
+
|
| 80 |
+
except HTTPException:
|
| 81 |
+
raise
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"[DEBUG] Session verification error: {e}")
|
| 84 |
+
import traceback
|
| 85 |
+
traceback.print_exc()
|
| 86 |
+
raise HTTPException(
|
| 87 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 88 |
+
detail="Session verification failed"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
src/database.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import create_engine, Session, SQLModel
|
| 2 |
+
from sqlalchemy.pool import QueuePool
|
| 3 |
+
import os
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
load_dotenv()
|
| 7 |
+
|
| 8 |
+
# Database URL from environment variables
|
| 9 |
+
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://username:password@localhost/todo_db")
|
| 10 |
+
|
| 11 |
+
# Create engine with optimized connection pooling
|
| 12 |
+
engine = create_engine(
|
| 13 |
+
DATABASE_URL,
|
| 14 |
+
poolclass=QueuePool,
|
| 15 |
+
pool_size=10,
|
| 16 |
+
max_overflow=20,
|
| 17 |
+
pool_timeout=30,
|
| 18 |
+
pool_recycle=3600,
|
| 19 |
+
pool_pre_ping=True,
|
| 20 |
+
echo=False,
|
| 21 |
+
connect_args={
|
| 22 |
+
"options": "-c timezone=utc"
|
| 23 |
+
}
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
def get_db():
|
| 27 |
+
"""Dependency to get database session"""
|
| 28 |
+
with Session(engine) as session:
|
| 29 |
+
yield session
|
| 30 |
+
|
| 31 |
+
def init_db():
|
| 32 |
+
"""Initialize database tables"""
|
| 33 |
+
SQLModel.metadata.create_all(engine)
|
| 34 |
+
|
| 35 |
+
def close_db():
|
| 36 |
+
"""Close database connections"""
|
| 37 |
+
engine.dispose()
|
src/main.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, status
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import JSONResponse
|
| 4 |
+
from fastapi.exceptions import RequestValidationError
|
| 5 |
+
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 6 |
+
from slowapi.util import get_remote_address
|
| 7 |
+
from slowapi.errors import RateLimitExceeded
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
# Initialize rate limiter
|
| 15 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 16 |
+
|
| 17 |
+
app = FastAPI(
|
| 18 |
+
title="Todo API",
|
| 19 |
+
description="API for managing user tasks in the Todo application",
|
| 20 |
+
version="1.0.0"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Add rate limiter to app state
|
| 24 |
+
app.state.limiter = limiter
|
| 25 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 26 |
+
|
| 27 |
+
# Add CORS middleware
|
| 28 |
+
app.add_middleware(
|
| 29 |
+
CORSMiddleware,
|
| 30 |
+
allow_origins=os.getenv("ALLOWED_ORIGINS", "*").split(","),
|
| 31 |
+
allow_credentials=True,
|
| 32 |
+
allow_methods=["*"],
|
| 33 |
+
allow_headers=["*"],
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Import logging utilities
|
| 37 |
+
# from src.utils.logger import logger, log_error
|
| 38 |
+
from src.utils.logger import logger, log_error
|
| 39 |
+
from src.utils.security import generate_secure_headers
|
| 40 |
+
|
| 41 |
+
# Global exception handler
|
| 42 |
+
@app.exception_handler(Exception)
|
| 43 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
| 44 |
+
log_error(exc, f"Unhandled exception in {request.method} {request.url.path}")
|
| 45 |
+
return JSONResponse(
|
| 46 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 47 |
+
content={
|
| 48 |
+
"detail": "An internal server error occurred",
|
| 49 |
+
"type": "internal_error"
|
| 50 |
+
}
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Validation error handler
|
| 54 |
+
@app.exception_handler(RequestValidationError)
|
| 55 |
+
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
| 56 |
+
logger.warning(f"Validation error in {request.method} {request.url.path}: {exc.errors()}")
|
| 57 |
+
return JSONResponse(
|
| 58 |
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
| 59 |
+
content={
|
| 60 |
+
"detail": exc.errors(),
|
| 61 |
+
"type": "validation_error"
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Security headers middleware
|
| 66 |
+
@app.middleware("http")
|
| 67 |
+
async def add_security_headers(request: Request, call_next):
|
| 68 |
+
response = await call_next(request)
|
| 69 |
+
|
| 70 |
+
# Add security headers
|
| 71 |
+
secure_headers = generate_secure_headers()
|
| 72 |
+
for header, value in secure_headers.items():
|
| 73 |
+
response.headers[header] = value
|
| 74 |
+
|
| 75 |
+
return response
|
| 76 |
+
|
| 77 |
+
# Request logging middleware
|
| 78 |
+
@app.middleware("http")
|
| 79 |
+
async def log_requests(request: Request, call_next):
|
| 80 |
+
start_time = time.time()
|
| 81 |
+
|
| 82 |
+
# Log incoming request
|
| 83 |
+
logger.info(f"Incoming request: {request.method} {request.url.path}")
|
| 84 |
+
|
| 85 |
+
response = await call_next(request)
|
| 86 |
+
|
| 87 |
+
# Log response time
|
| 88 |
+
process_time = time.time() - start_time
|
| 89 |
+
logger.info(f"Request completed: {request.method} {request.url.path} - Status: {response.status_code} - Time: {process_time:.3f}s")
|
| 90 |
+
|
| 91 |
+
return response
|
| 92 |
+
|
| 93 |
+
# Import and include routers
|
| 94 |
+
from src.api import auth_router, task_router
|
| 95 |
+
|
| 96 |
+
app.include_router(auth_router.router, prefix="/api/v1/auth", tags=["authentication"])
|
| 97 |
+
app.include_router(task_router.router, prefix="/api/v1/tasks", tags=["tasks"])
|
| 98 |
+
|
| 99 |
+
@app.get("/")
|
| 100 |
+
@limiter.limit("100/minute")
|
| 101 |
+
def read_root(request: Request):
|
| 102 |
+
logger.info("Health check endpoint accessed")
|
| 103 |
+
return {"message": "Todo API is running", "status": "healthy", "version": "2.0"}
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
import uvicorn
|
| 107 |
+
uvicorn.run(
|
| 108 |
+
"src.main:app",
|
| 109 |
+
host="0.0.0.0",
|
| 110 |
+
port=int(os.getenv("PORT", 8000)),
|
| 111 |
+
reload=True
|
| 112 |
+
)
|
src/middleware/auth.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import HTTPException, status
|
| 2 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 3 |
+
from jose import JWTError, jwt
|
| 4 |
+
from functools import wraps
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
# JWT Configuration
|
| 11 |
+
SECRET_KEY = os.getenv("JWT_SECRET", "your-super-secret-jwt-key-change-in-production")
|
| 12 |
+
ALGORITHM = "HS256"
|
| 13 |
+
|
| 14 |
+
security = HTTPBearer()
|
| 15 |
+
|
| 16 |
+
def verify_token(token: str):
|
| 17 |
+
"""
|
| 18 |
+
Verify and decode a JWT token
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 22 |
+
user_id: int = payload.get("sub")
|
| 23 |
+
if user_id is None:
|
| 24 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 25 |
+
return user_id
|
| 26 |
+
except JWTError:
|
| 27 |
+
raise HTTPException(status_code=401, detail="Could not validate credentials")
|
| 28 |
+
|
| 29 |
+
def get_current_user(credentials: HTTPAuthorizationCredentials = security):
|
| 30 |
+
"""
|
| 31 |
+
Dependency to get current authenticated user
|
| 32 |
+
"""
|
| 33 |
+
user_id = verify_token(credentials.credentials)
|
| 34 |
+
return user_id
|
src/models/task.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
class Task(SQLModel, table=True):
|
| 6 |
+
"""SQLModel for Task entity"""
|
| 7 |
+
__tablename__ = "tasks"
|
| 8 |
+
|
| 9 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 10 |
+
title: str = Field(max_length=200)
|
| 11 |
+
description: Optional[str] = Field(default=None, max_length=1000)
|
| 12 |
+
status: str = Field(default="pending", index=True) # pending, in-progress, completed
|
| 13 |
+
user_id: str = Field(index=True) # Changed to str to match Better Auth
|
| 14 |
+
created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
|
| 15 |
+
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
| 16 |
+
due_date: Optional[datetime] = Field(default=None, index=True)
|
| 17 |
+
|
| 18 |
+
class TaskCreate(SQLModel):
|
| 19 |
+
"""Schema for creating a new Task"""
|
| 20 |
+
title: str
|
| 21 |
+
description: Optional[str] = None
|
| 22 |
+
status: str = "pending"
|
| 23 |
+
due_date: Optional[datetime] = None
|
| 24 |
+
|
| 25 |
+
class TaskUpdate(SQLModel):
|
| 26 |
+
"""Schema for updating a Task"""
|
| 27 |
+
title: Optional[str] = None
|
| 28 |
+
description: Optional[str] = None
|
| 29 |
+
status: Optional[str] = None
|
| 30 |
+
due_date: Optional[datetime] = None
|
| 31 |
+
|
| 32 |
+
class TaskResponse(SQLModel):
|
| 33 |
+
"""Schema for Task response"""
|
| 34 |
+
id: int
|
| 35 |
+
title: str
|
| 36 |
+
description: Optional[str]
|
| 37 |
+
status: str
|
| 38 |
+
user_id: str # Changed to str
|
| 39 |
+
created_at: datetime
|
| 40 |
+
updated_at: datetime
|
| 41 |
+
due_date: Optional[datetime]
|
src/models/user.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import SQLModel, Field
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
class User(SQLModel, table=True):
|
| 6 |
+
"""SQLModel for User entity (Legacy - Better Auth is now used)"""
|
| 7 |
+
__tablename__ = "users"
|
| 8 |
+
|
| 9 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 10 |
+
email: str = Field(unique=True, index=True)
|
| 11 |
+
username: str = Field(unique=True, index=True)
|
| 12 |
+
password_hash: str
|
| 13 |
+
password_reset_token: Optional[str] = None
|
| 14 |
+
password_reset_expires: Optional[datetime] = None
|
| 15 |
+
created_at: datetime = Field(default_factory=datetime.utcnow)
|
| 16 |
+
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
| 17 |
+
is_active: bool = Field(default=True)
|
| 18 |
+
|
| 19 |
+
# Note: Relationship removed - tasks now reference Better Auth user table
|
| 20 |
+
|
| 21 |
+
class UserCreate(SQLModel):
|
| 22 |
+
"""Schema for creating a new User"""
|
| 23 |
+
email: str
|
| 24 |
+
username: str
|
| 25 |
+
password: str
|
| 26 |
+
|
| 27 |
+
class UserUpdate(SQLModel):
|
| 28 |
+
"""Schema for updating a User"""
|
| 29 |
+
email: Optional[str] = None
|
| 30 |
+
username: Optional[str] = None
|
| 31 |
+
|
| 32 |
+
class UserResponse(SQLModel):
|
| 33 |
+
"""Schema for User response (excludes sensitive data)"""
|
| 34 |
+
id: int
|
| 35 |
+
email: str
|
| 36 |
+
username: str
|
| 37 |
+
is_active: bool
|
| 38 |
+
created_at: datetime
|
| 39 |
+
updated_at: datetime
|
src/services/auth_service.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timedelta
|
| 2 |
+
from jose import JWTError, jwt
|
| 3 |
+
from passlib.context import CryptContext
|
| 4 |
+
import os
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
load_dotenv()
|
| 8 |
+
|
| 9 |
+
# JWT Configuration
|
| 10 |
+
SECRET_KEY = os.getenv("JWT_SECRET", "your-super-secret-jwt-key-change-in-production")
|
| 11 |
+
ALGORITHM = "HS256"
|
| 12 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 30))
|
| 13 |
+
|
| 14 |
+
# Password hashing context
|
| 15 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 16 |
+
|
| 17 |
+
class AuthService:
|
| 18 |
+
"""
|
| 19 |
+
Service class for authentication-related operations
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def create_access_token(data: dict, expires_delta: timedelta = None):
|
| 24 |
+
"""
|
| 25 |
+
Create a new access token
|
| 26 |
+
"""
|
| 27 |
+
to_encode = data.copy()
|
| 28 |
+
if expires_delta:
|
| 29 |
+
expire = datetime.utcnow() + expires_delta
|
| 30 |
+
else:
|
| 31 |
+
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 32 |
+
|
| 33 |
+
to_encode.update({"exp": expire})
|
| 34 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 35 |
+
return encoded_jwt
|
| 36 |
+
|
| 37 |
+
@staticmethod
|
| 38 |
+
def verify_token(token: str):
|
| 39 |
+
"""
|
| 40 |
+
Verify and decode a JWT token
|
| 41 |
+
"""
|
| 42 |
+
try:
|
| 43 |
+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 44 |
+
user_id: int = payload.get("sub")
|
| 45 |
+
if user_id is None:
|
| 46 |
+
raise ValueError("Could not validate credentials")
|
| 47 |
+
return user_id
|
| 48 |
+
except JWTError:
|
| 49 |
+
raise ValueError("Could not validate credentials")
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def get_password_hash(password: str) -> str:
|
| 53 |
+
"""Hash a plain text password"""
|
| 54 |
+
return pwd_context.hash(password)
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 58 |
+
"""Verify a plain text password against its hash"""
|
| 59 |
+
return pwd_context.verify(plain_password, hashed_password)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def create_refresh_token(data: dict, expires_delta: timedelta = None):
|
| 63 |
+
"""
|
| 64 |
+
Create a new refresh token
|
| 65 |
+
"""
|
| 66 |
+
to_encode = data.copy()
|
| 67 |
+
if expires_delta:
|
| 68 |
+
expire = datetime.utcnow() + expires_delta
|
| 69 |
+
else:
|
| 70 |
+
# Refresh token expires in 7 days
|
| 71 |
+
expire = datetime.utcnow() + timedelta(days=7)
|
| 72 |
+
|
| 73 |
+
to_encode.update({"exp": expire, "type": "refresh"})
|
| 74 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 75 |
+
return encoded_jwt
|
src/services/task_service.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import Session, select
|
| 2 |
+
from ..models.task import Task, TaskCreate, TaskUpdate
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
|
| 5 |
+
class TaskService:
|
| 6 |
+
"""Service class for task-related operations"""
|
| 7 |
+
|
| 8 |
+
@classmethod
|
| 9 |
+
def create_task(cls, db: Session, task: TaskCreate, user_id: str) -> Task:
|
| 10 |
+
"""Create a new task for a specific user"""
|
| 11 |
+
db_task = Task(**task.model_dump(), user_id=user_id)
|
| 12 |
+
db.add(db_task)
|
| 13 |
+
db.commit()
|
| 14 |
+
db.refresh(db_task)
|
| 15 |
+
return db_task
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def get_task_by_id(cls, db: Session, task_id: int, user_id: str) -> Task:
|
| 19 |
+
"""Retrieve a specific task by ID for a specific user"""
|
| 20 |
+
statement = select(Task).where(Task.id == task_id, Task.user_id == user_id)
|
| 21 |
+
return db.exec(statement).first()
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def get_tasks_for_user(cls, db: Session, user_id: str, skip: int = 0, limit: int = 100) -> List[Task]:
|
| 25 |
+
"""Retrieve all tasks for a specific user with pagination"""
|
| 26 |
+
statement = select(Task).where(Task.user_id == user_id).offset(skip).limit(limit)
|
| 27 |
+
return db.exec(statement).all()
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
def update_task(cls, db: Session, task_id: int, task_update: TaskUpdate, user_id: str) -> Optional[Task]:
|
| 31 |
+
"""Update a specific task for a specific user"""
|
| 32 |
+
db_task = cls.get_task_by_id(db, task_id, user_id)
|
| 33 |
+
if not db_task:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
update_data = task_update.model_dump(exclude_unset=True)
|
| 37 |
+
for field, value in update_data.items():
|
| 38 |
+
setattr(db_task, field, value)
|
| 39 |
+
|
| 40 |
+
db.add(db_task)
|
| 41 |
+
db.commit()
|
| 42 |
+
db.refresh(db_task)
|
| 43 |
+
return db_task
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def delete_task(cls, db: Session, task_id: int, user_id: str) -> bool:
|
| 47 |
+
"""Delete a specific task for a specific user"""
|
| 48 |
+
db_task = cls.get_task_by_id(db, task_id, user_id)
|
| 49 |
+
if not db_task:
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
db.delete(db_task)
|
| 53 |
+
db.commit()
|
| 54 |
+
return True
|
| 55 |
+
|
| 56 |
+
@classmethod
|
| 57 |
+
def get_tasks_by_status(cls, db: Session, user_id: str, status: str) -> List[Task]:
|
| 58 |
+
"""Retrieve tasks for a user filtered by status"""
|
| 59 |
+
statement = select(Task).where(Task.user_id == user_id, Task.status == status)
|
| 60 |
+
return db.exec(statement).all()
|
src/services/user_service.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import Session, select
|
| 2 |
+
from ..models.user import User, UserCreate
|
| 3 |
+
from ..utils.security import SecurityValidator
|
| 4 |
+
from passlib.context import CryptContext
|
| 5 |
+
from fastapi import HTTPException, status
|
| 6 |
+
|
| 7 |
+
# Password hashing context
|
| 8 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 9 |
+
|
| 10 |
+
class UserService:
|
| 11 |
+
"""Service class for user-related operations"""
|
| 12 |
+
|
| 13 |
+
@staticmethod
|
| 14 |
+
def get_password_hash(password: str) -> str:
|
| 15 |
+
"""Hash a plain text password (bcrypt has 72 byte limit)"""
|
| 16 |
+
# Truncate password to 72 characters to avoid bcrypt error
|
| 17 |
+
truncated_password = password[:72]
|
| 18 |
+
return pwd_context.hash(truncated_password)
|
| 19 |
+
|
| 20 |
+
@staticmethod
|
| 21 |
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 22 |
+
"""Verify a plain text password against its hash"""
|
| 23 |
+
# Truncate password to 72 characters to match hashing
|
| 24 |
+
truncated_password = plain_password[:72]
|
| 25 |
+
return pwd_context.verify(truncated_password, hashed_password)
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def create_user(cls, db: Session, user: UserCreate) -> User:
|
| 29 |
+
"""Create a new user in the database with security validation"""
|
| 30 |
+
# Validate email
|
| 31 |
+
is_valid, error_msg = SecurityValidator.validate_email(user.email)
|
| 32 |
+
if not is_valid:
|
| 33 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_msg)
|
| 34 |
+
|
| 35 |
+
# Validate username
|
| 36 |
+
is_valid, error_msg = SecurityValidator.validate_username(user.username)
|
| 37 |
+
if not is_valid:
|
| 38 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_msg)
|
| 39 |
+
|
| 40 |
+
# Validate password
|
| 41 |
+
is_valid, error_msg = SecurityValidator.validate_password(user.password)
|
| 42 |
+
if not is_valid:
|
| 43 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_msg)
|
| 44 |
+
|
| 45 |
+
# Hash the password
|
| 46 |
+
hashed_password = cls.get_password_hash(user.password)
|
| 47 |
+
|
| 48 |
+
# Create user instance
|
| 49 |
+
db_user = User(
|
| 50 |
+
email=user.email.lower().strip(),
|
| 51 |
+
username=user.username.strip(),
|
| 52 |
+
password_hash=hashed_password
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
db.add(db_user)
|
| 56 |
+
db.commit()
|
| 57 |
+
db.refresh(db_user)
|
| 58 |
+
return db_user
|
| 59 |
+
|
| 60 |
+
@classmethod
|
| 61 |
+
def get_user_by_email(cls, db: Session, email: str) -> User:
|
| 62 |
+
"""Retrieve a user by email"""
|
| 63 |
+
statement = select(User).where(User.email == email.lower().strip())
|
| 64 |
+
return db.exec(statement).first()
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def get_user_by_username(cls, db: Session, username: str) -> User:
|
| 68 |
+
"""Retrieve a user by username"""
|
| 69 |
+
statement = select(User).where(User.username == username.strip())
|
| 70 |
+
return db.exec(statement).first()
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def get_user_by_id(cls, db: Session, user_id: str) -> User:
|
| 74 |
+
"""Retrieve a user by ID (Better Auth uses string IDs)"""
|
| 75 |
+
# For Better Auth compatibility, we query the Better Auth user table
|
| 76 |
+
# This is a simplified version - in production you'd query the actual Better Auth table
|
| 77 |
+
return None # Disabled for Better Auth - user verification happens via JWT
|
| 78 |
+
|
| 79 |
+
@classmethod
|
| 80 |
+
def authenticate_user(cls, db: Session, email: str, password: str) -> User:
|
| 81 |
+
"""Authenticate a user by email and password"""
|
| 82 |
+
user = cls.get_user_by_email(db, email)
|
| 83 |
+
if not user or not cls.verify_password(password, user.password_hash):
|
| 84 |
+
return None
|
| 85 |
+
return user
|
| 86 |
+
|
| 87 |
+
@classmethod
|
| 88 |
+
def update_user(cls, db: Session, user_id: int, user_update) -> User:
|
| 89 |
+
"""Update user information with validation"""
|
| 90 |
+
user = cls.get_user_by_id(db, user_id)
|
| 91 |
+
if not user:
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
if user_update.email:
|
| 95 |
+
is_valid, error_msg = SecurityValidator.validate_email(user_update.email)
|
| 96 |
+
if not is_valid:
|
| 97 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_msg)
|
| 98 |
+
user.email = user_update.email.lower().strip()
|
| 99 |
+
|
| 100 |
+
if user_update.username:
|
| 101 |
+
is_valid, error_msg = SecurityValidator.validate_username(user_update.username)
|
| 102 |
+
if not is_valid:
|
| 103 |
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_msg)
|
| 104 |
+
user.username = user_update.username.strip()
|
| 105 |
+
|
| 106 |
+
db.add(user)
|
| 107 |
+
db.commit()
|
| 108 |
+
db.refresh(user)
|
| 109 |
+
return user
|
src/utils/logger.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import sys
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
# Create logs directory if it doesn't exist
|
| 7 |
+
log_dir = Path("logs")
|
| 8 |
+
log_dir.mkdir(exist_ok=True)
|
| 9 |
+
|
| 10 |
+
# Configure logging format
|
| 11 |
+
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 12 |
+
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
|
| 13 |
+
|
| 14 |
+
# Create logger
|
| 15 |
+
logger = logging.getLogger("todo_app")
|
| 16 |
+
logger.setLevel(logging.DEBUG)
|
| 17 |
+
|
| 18 |
+
# Console handler
|
| 19 |
+
console_handler = logging.StreamHandler(sys.stdout)
|
| 20 |
+
console_handler.setLevel(logging.INFO)
|
| 21 |
+
console_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
|
| 22 |
+
console_handler.setFormatter(console_formatter)
|
| 23 |
+
|
| 24 |
+
# File handler for all logs
|
| 25 |
+
file_handler = logging.FileHandler(
|
| 26 |
+
log_dir / f"app_{datetime.now().strftime('%Y%m%d')}.log"
|
| 27 |
+
)
|
| 28 |
+
file_handler.setLevel(logging.DEBUG)
|
| 29 |
+
file_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
|
| 30 |
+
file_handler.setFormatter(file_formatter)
|
| 31 |
+
|
| 32 |
+
# File handler for errors only
|
| 33 |
+
error_handler = logging.FileHandler(
|
| 34 |
+
log_dir / f"error_{datetime.now().strftime('%Y%m%d')}.log"
|
| 35 |
+
)
|
| 36 |
+
error_handler.setLevel(logging.ERROR)
|
| 37 |
+
error_formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
|
| 38 |
+
error_handler.setFormatter(error_formatter)
|
| 39 |
+
|
| 40 |
+
# Add handlers to logger
|
| 41 |
+
logger.addHandler(console_handler)
|
| 42 |
+
logger.addHandler(file_handler)
|
| 43 |
+
logger.addHandler(error_handler)
|
| 44 |
+
|
| 45 |
+
def log_request(method: str, path: str, user_id: int = None):
|
| 46 |
+
"""Log incoming API requests"""
|
| 47 |
+
user_info = f"user_id={user_id}" if user_id else "unauthenticated"
|
| 48 |
+
logger.info(f"Request: {method} {path} ({user_info})")
|
| 49 |
+
|
| 50 |
+
def log_error(error: Exception, context: str = ""):
|
| 51 |
+
"""Log errors with context"""
|
| 52 |
+
logger.error(f"Error in {context}: {str(error)}", exc_info=True)
|
| 53 |
+
|
| 54 |
+
def log_security_event(event: str, details: dict = None):
|
| 55 |
+
"""Log security-related events"""
|
| 56 |
+
details_str = f" - {details}" if details else ""
|
| 57 |
+
logger.warning(f"Security Event: {event}{details_str}")
|
src/utils/performance.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Performance optimization utilities for the Todo application
|
| 3 |
+
"""
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
from typing import Optional
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PerformanceMonitor:
|
| 10 |
+
"""Monitor and log performance metrics"""
|
| 11 |
+
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.metrics = {}
|
| 14 |
+
|
| 15 |
+
def record_metric(self, operation: str, duration: float):
|
| 16 |
+
"""Record a performance metric"""
|
| 17 |
+
if operation not in self.metrics:
|
| 18 |
+
self.metrics[operation] = {
|
| 19 |
+
'count': 0,
|
| 20 |
+
'total_time': 0,
|
| 21 |
+
'min_time': float('inf'),
|
| 22 |
+
'max_time': 0
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
self.metrics[operation]['count'] += 1
|
| 26 |
+
self.metrics[operation]['total_time'] += duration
|
| 27 |
+
self.metrics[operation]['min_time'] = min(self.metrics[operation]['min_time'], duration)
|
| 28 |
+
self.metrics[operation]['max_time'] = max(self.metrics[operation]['max_time'], duration)
|
| 29 |
+
|
| 30 |
+
def get_metrics(self, operation: Optional[str] = None):
|
| 31 |
+
"""Get performance metrics"""
|
| 32 |
+
if operation:
|
| 33 |
+
if operation in self.metrics:
|
| 34 |
+
metric = self.metrics[operation]
|
| 35 |
+
return {
|
| 36 |
+
'operation': operation,
|
| 37 |
+
'count': metric['count'],
|
| 38 |
+
'avg_time': metric['total_time'] / metric['count'],
|
| 39 |
+
'min_time': metric['min_time'],
|
| 40 |
+
'max_time': metric['max_time']
|
| 41 |
+
}
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
return {
|
| 45 |
+
op: {
|
| 46 |
+
'count': m['count'],
|
| 47 |
+
'avg_time': m['total_time'] / m['count'],
|
| 48 |
+
'min_time': m['min_time'],
|
| 49 |
+
'max_time': m['max_time']
|
| 50 |
+
}
|
| 51 |
+
for op, m in self.metrics.items()
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Global performance monitor instance
|
| 56 |
+
performance_monitor = PerformanceMonitor()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def measure_performance(operation_name: str):
|
| 60 |
+
"""Decorator to measure function performance"""
|
| 61 |
+
def decorator(func):
|
| 62 |
+
def wrapper(*args, **kwargs):
|
| 63 |
+
start_time = time.time()
|
| 64 |
+
result = func(*args, **kwargs)
|
| 65 |
+
duration = time.time() - start_time
|
| 66 |
+
|
| 67 |
+
performance_monitor.record_metric(operation_name, duration)
|
| 68 |
+
|
| 69 |
+
# Log slow operations (> 1 second)
|
| 70 |
+
if duration > 1.0:
|
| 71 |
+
from ..utils.logger import logger
|
| 72 |
+
logger.warning(f"Slow operation detected: {operation_name} took {duration:.3f}s")
|
| 73 |
+
|
| 74 |
+
return result
|
| 75 |
+
return wrapper
|
| 76 |
+
return decorator
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@lru_cache(maxsize=128)
|
| 80 |
+
def cache_user_lookup(user_id: int):
|
| 81 |
+
"""Cache user lookups to reduce database queries"""
|
| 82 |
+
# This is a placeholder - actual implementation would query the database
|
| 83 |
+
# The LRU cache will store the most recent 128 user lookups
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class QueryOptimizer:
|
| 88 |
+
"""Optimize database queries"""
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def get_optimized_task_query(db, user_id: int, filters: dict = None):
|
| 92 |
+
"""
|
| 93 |
+
Get optimized task query with eager loading
|
| 94 |
+
"""
|
| 95 |
+
from ..models.task import Task
|
| 96 |
+
|
| 97 |
+
query = db.query(Task).filter(Task.user_id == user_id)
|
| 98 |
+
|
| 99 |
+
# Apply filters if provided
|
| 100 |
+
if filters:
|
| 101 |
+
if 'status' in filters:
|
| 102 |
+
query = query.filter(Task.status == filters['status'])
|
| 103 |
+
|
| 104 |
+
if 'created_after' in filters:
|
| 105 |
+
query = query.filter(Task.created_at >= filters['created_after'])
|
| 106 |
+
|
| 107 |
+
if 'due_before' in filters:
|
| 108 |
+
query = query.filter(Task.due_date <= filters['due_before'])
|
| 109 |
+
|
| 110 |
+
# Order by created_at descending for better performance
|
| 111 |
+
query = query.order_by(Task.created_at.desc())
|
| 112 |
+
|
| 113 |
+
return query
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
def batch_load_tasks(db, user_ids: list):
|
| 117 |
+
"""
|
| 118 |
+
Batch load tasks for multiple users to reduce queries
|
| 119 |
+
"""
|
| 120 |
+
from ..models.task import Task
|
| 121 |
+
|
| 122 |
+
tasks = db.query(Task).filter(Task.user_id.in_(user_ids)).all()
|
| 123 |
+
|
| 124 |
+
# Group tasks by user_id
|
| 125 |
+
tasks_by_user = {}
|
| 126 |
+
for task in tasks:
|
| 127 |
+
if task.user_id not in tasks_by_user:
|
| 128 |
+
tasks_by_user[task.user_id] = []
|
| 129 |
+
tasks_by_user[task.user_id].append(task)
|
| 130 |
+
|
| 131 |
+
return tasks_by_user
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class ResponseOptimizer:
|
| 135 |
+
"""Optimize API responses"""
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def paginate_results(query, page: int = 1, page_size: int = 20):
|
| 139 |
+
"""
|
| 140 |
+
Paginate query results for better performance
|
| 141 |
+
"""
|
| 142 |
+
offset = (page - 1) * page_size
|
| 143 |
+
total = query.count()
|
| 144 |
+
items = query.offset(offset).limit(page_size).all()
|
| 145 |
+
|
| 146 |
+
return {
|
| 147 |
+
'items': items,
|
| 148 |
+
'total': total,
|
| 149 |
+
'page': page,
|
| 150 |
+
'page_size': page_size,
|
| 151 |
+
'total_pages': (total + page_size - 1) // page_size
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def compress_response(data: dict):
|
| 156 |
+
"""
|
| 157 |
+
Compress response data by removing null values
|
| 158 |
+
"""
|
| 159 |
+
return {k: v for k, v in data.items() if v is not None}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# Connection pooling configuration
|
| 163 |
+
DATABASE_POOL_CONFIG = {
|
| 164 |
+
'pool_size': 10, # Number of connections to maintain
|
| 165 |
+
'max_overflow': 20, # Maximum number of connections to create beyond pool_size
|
| 166 |
+
'pool_timeout': 30, # Seconds to wait before giving up on getting a connection
|
| 167 |
+
'pool_recycle': 3600, # Recycle connections after 1 hour
|
| 168 |
+
'pool_pre_ping': True # Verify connections before using them
|
| 169 |
+
}
|
src/utils/security.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Security utilities for the Todo application
|
| 3 |
+
"""
|
| 4 |
+
import re
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from fastapi import HTTPException, status
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SecurityValidator:
|
| 10 |
+
"""Security validation utilities"""
|
| 11 |
+
|
| 12 |
+
# Password requirements
|
| 13 |
+
MIN_PASSWORD_LENGTH = 8
|
| 14 |
+
MAX_PASSWORD_LENGTH = 128
|
| 15 |
+
|
| 16 |
+
# Username requirements
|
| 17 |
+
MIN_USERNAME_LENGTH = 3
|
| 18 |
+
MAX_USERNAME_LENGTH = 30
|
| 19 |
+
USERNAME_PATTERN = re.compile(r'^[a-zA-Z0-9_-]+$')
|
| 20 |
+
|
| 21 |
+
# Email validation
|
| 22 |
+
EMAIL_PATTERN = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
|
| 23 |
+
|
| 24 |
+
# SQL injection patterns to detect
|
| 25 |
+
SQL_INJECTION_PATTERNS = [
|
| 26 |
+
r"(\bUNION\b.*\bSELECT\b)",
|
| 27 |
+
r"(\bDROP\b.*\bTABLE\b)",
|
| 28 |
+
r"(\bINSERT\b.*\bINTO\b)",
|
| 29 |
+
r"(\bDELETE\b.*\bFROM\b)",
|
| 30 |
+
r"(--)",
|
| 31 |
+
r"(;.*--)",
|
| 32 |
+
r"(\bOR\b.*=.*)",
|
| 33 |
+
r"('.*OR.*'.*=.*')"
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
@classmethod
|
| 37 |
+
def validate_password(cls, password: str) -> tuple[bool, Optional[str]]:
|
| 38 |
+
"""
|
| 39 |
+
Validate password strength
|
| 40 |
+
Returns: (is_valid, error_message)
|
| 41 |
+
"""
|
| 42 |
+
if len(password) < cls.MIN_PASSWORD_LENGTH:
|
| 43 |
+
return False, f"Password must be at least {cls.MIN_PASSWORD_LENGTH} characters"
|
| 44 |
+
|
| 45 |
+
if len(password) > cls.MAX_PASSWORD_LENGTH:
|
| 46 |
+
return False, f"Password must be at most {cls.MAX_PASSWORD_LENGTH} characters"
|
| 47 |
+
|
| 48 |
+
# Check for at least one uppercase letter
|
| 49 |
+
if not re.search(r'[A-Z]', password):
|
| 50 |
+
return False, "Password must contain at least one uppercase letter"
|
| 51 |
+
|
| 52 |
+
# Check for at least one lowercase letter
|
| 53 |
+
if not re.search(r'[a-z]', password):
|
| 54 |
+
return False, "Password must contain at least one lowercase letter"
|
| 55 |
+
|
| 56 |
+
# Check for at least one digit
|
| 57 |
+
if not re.search(r'\d', password):
|
| 58 |
+
return False, "Password must contain at least one digit"
|
| 59 |
+
|
| 60 |
+
# Check for at least one special character
|
| 61 |
+
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
|
| 62 |
+
return False, "Password must contain at least one special character"
|
| 63 |
+
|
| 64 |
+
return True, None
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def validate_username(cls, username: str) -> tuple[bool, Optional[str]]:
|
| 68 |
+
"""
|
| 69 |
+
Validate username format
|
| 70 |
+
Returns: (is_valid, error_message)
|
| 71 |
+
"""
|
| 72 |
+
if len(username) < cls.MIN_USERNAME_LENGTH:
|
| 73 |
+
return False, f"Username must be at least {cls.MIN_USERNAME_LENGTH} characters"
|
| 74 |
+
|
| 75 |
+
if len(username) > cls.MAX_USERNAME_LENGTH:
|
| 76 |
+
return False, f"Username must be at most {cls.MAX_USERNAME_LENGTH} characters"
|
| 77 |
+
|
| 78 |
+
if not cls.USERNAME_PATTERN.match(username):
|
| 79 |
+
return False, "Username can only contain letters, numbers, hyphens, and underscores"
|
| 80 |
+
|
| 81 |
+
return True, None
|
| 82 |
+
|
| 83 |
+
@classmethod
|
| 84 |
+
def validate_email(cls, email: str) -> tuple[bool, Optional[str]]:
|
| 85 |
+
"""
|
| 86 |
+
Validate email format
|
| 87 |
+
Returns: (is_valid, error_message)
|
| 88 |
+
"""
|
| 89 |
+
if not cls.EMAIL_PATTERN.match(email):
|
| 90 |
+
return False, "Invalid email format"
|
| 91 |
+
|
| 92 |
+
if len(email) > 254: # RFC 5321
|
| 93 |
+
return False, "Email address is too long"
|
| 94 |
+
|
| 95 |
+
return True, None
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def check_sql_injection(cls, input_string: str) -> bool:
|
| 99 |
+
"""
|
| 100 |
+
Check if input contains potential SQL injection patterns
|
| 101 |
+
Returns: True if suspicious pattern detected
|
| 102 |
+
"""
|
| 103 |
+
input_upper = input_string.upper()
|
| 104 |
+
|
| 105 |
+
for pattern in cls.SQL_INJECTION_PATTERNS:
|
| 106 |
+
if re.search(pattern, input_upper, re.IGNORECASE):
|
| 107 |
+
return True
|
| 108 |
+
|
| 109 |
+
return False
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def sanitize_input(cls, input_string: str, max_length: int = 1000) -> str:
|
| 113 |
+
"""
|
| 114 |
+
Sanitize user input by removing potentially dangerous characters
|
| 115 |
+
"""
|
| 116 |
+
if cls.check_sql_injection(input_string):
|
| 117 |
+
raise HTTPException(
|
| 118 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 119 |
+
detail="Invalid input detected"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Truncate to max length
|
| 123 |
+
sanitized = input_string[:max_length]
|
| 124 |
+
|
| 125 |
+
# Remove null bytes
|
| 126 |
+
sanitized = sanitized.replace('\x00', '')
|
| 127 |
+
|
| 128 |
+
return sanitized.strip()
|
| 129 |
+
|
| 130 |
+
@classmethod
|
| 131 |
+
def validate_task_title(cls, title: str) -> tuple[bool, Optional[str]]:
|
| 132 |
+
"""
|
| 133 |
+
Validate task title
|
| 134 |
+
Returns: (is_valid, error_message)
|
| 135 |
+
"""
|
| 136 |
+
if not title or len(title.strip()) == 0:
|
| 137 |
+
return False, "Title cannot be empty"
|
| 138 |
+
|
| 139 |
+
if len(title) > 200:
|
| 140 |
+
return False, "Title must be 200 characters or less"
|
| 141 |
+
|
| 142 |
+
if cls.check_sql_injection(title):
|
| 143 |
+
return False, "Invalid characters in title"
|
| 144 |
+
|
| 145 |
+
return True, None
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def validate_task_description(cls, description: Optional[str]) -> tuple[bool, Optional[str]]:
|
| 149 |
+
"""
|
| 150 |
+
Validate task description
|
| 151 |
+
Returns: (is_valid, error_message)
|
| 152 |
+
"""
|
| 153 |
+
if description is None:
|
| 154 |
+
return True, None
|
| 155 |
+
|
| 156 |
+
if len(description) > 1000:
|
| 157 |
+
return False, "Description must be 1000 characters or less"
|
| 158 |
+
|
| 159 |
+
if cls.check_sql_injection(description):
|
| 160 |
+
return False, "Invalid characters in description"
|
| 161 |
+
|
| 162 |
+
return True, None
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def validate_content_type(content_type: str, allowed_types: list[str]) -> bool:
|
| 166 |
+
"""
|
| 167 |
+
Validate content type against allowed types
|
| 168 |
+
"""
|
| 169 |
+
return content_type in allowed_types
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def generate_secure_headers() -> dict:
|
| 173 |
+
"""
|
| 174 |
+
Generate secure HTTP headers
|
| 175 |
+
"""
|
| 176 |
+
return {
|
| 177 |
+
"X-Content-Type-Options": "nosniff",
|
| 178 |
+
"X-Frame-Options": "DENY",
|
| 179 |
+
"X-XSS-Protection": "1; mode=block",
|
| 180 |
+
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
|
| 181 |
+
"Content-Security-Policy": "default-src 'self'",
|
| 182 |
+
"Referrer-Policy": "strict-origin-when-cross-origin"
|
| 183 |
+
}
|
test_api.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Simple API test script to verify backend endpoints
|
| 3 |
+
Run this after starting the backend server
|
| 4 |
+
"""
|
| 5 |
+
import requests
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
BASE_URL = "http://localhost:8001/api/v1"
|
| 9 |
+
|
| 10 |
+
def test_register():
|
| 11 |
+
"""Test user registration"""
|
| 12 |
+
print("\n=== Testing Registration ===")
|
| 13 |
+
url = f"{BASE_URL}/auth/register"
|
| 14 |
+
data = {
|
| 15 |
+
"email": "test@example.com",
|
| 16 |
+
"username": "testuser",
|
| 17 |
+
"password": "Password123!"
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
response = requests.post(url, json=data)
|
| 22 |
+
print(f"Status Code: {response.status_code}")
|
| 23 |
+
print(f"Response: {json.dumps(response.json(), indent=2)}")
|
| 24 |
+
return response.status_code in [200, 201, 409] # 409 if already exists
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"Error: {e}")
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
def test_login():
|
| 30 |
+
"""Test user login"""
|
| 31 |
+
print("\n=== Testing Login ===")
|
| 32 |
+
url = f"{BASE_URL}/auth/login"
|
| 33 |
+
data = {
|
| 34 |
+
"email": "test@example.com",
|
| 35 |
+
"password": "Password123!"
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
response = requests.post(url, json=data)
|
| 40 |
+
print(f"Status Code: {response.status_code}")
|
| 41 |
+
result = response.json()
|
| 42 |
+
print(f"Response: {json.dumps(result, indent=2)}")
|
| 43 |
+
|
| 44 |
+
if response.status_code == 200:
|
| 45 |
+
return result.get("access_token")
|
| 46 |
+
return None
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Error: {e}")
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
def test_create_task(token):
|
| 52 |
+
"""Test task creation"""
|
| 53 |
+
print("\n=== Testing Create Task ===")
|
| 54 |
+
url = f"{BASE_URL}/tasks"
|
| 55 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 56 |
+
data = {
|
| 57 |
+
"title": "Test Task",
|
| 58 |
+
"description": "This is a test task",
|
| 59 |
+
"status": "pending"
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
response = requests.post(url, json=data, headers=headers)
|
| 64 |
+
print(f"Status Code: {response.status_code}")
|
| 65 |
+
print(f"Response: {json.dumps(response.json(), indent=2)}")
|
| 66 |
+
return response.status_code == 201
|
| 67 |
+
except Exception as e:
|
| 68 |
+
print(f"Error: {e}")
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
def test_get_tasks(token):
|
| 72 |
+
"""Test getting all tasks"""
|
| 73 |
+
print("\n=== Testing Get Tasks ===")
|
| 74 |
+
url = f"{BASE_URL}/tasks"
|
| 75 |
+
headers = {"Authorization": f"Bearer {token}"}
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
response = requests.get(url, headers=headers)
|
| 79 |
+
print(f"Status Code: {response.status_code}")
|
| 80 |
+
print(f"Response: {json.dumps(response.json(), indent=2)}")
|
| 81 |
+
return response.status_code == 200
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"Error: {e}")
|
| 84 |
+
return False
|
| 85 |
+
|
| 86 |
+
def main():
|
| 87 |
+
print("=" * 50)
|
| 88 |
+
print("Backend API Test Suite")
|
| 89 |
+
print("=" * 50)
|
| 90 |
+
print(f"Testing against: {BASE_URL}")
|
| 91 |
+
|
| 92 |
+
# Test registration
|
| 93 |
+
if not test_register():
|
| 94 |
+
print("\n❌ Registration test failed!")
|
| 95 |
+
return
|
| 96 |
+
|
| 97 |
+
# Test login
|
| 98 |
+
token = test_login()
|
| 99 |
+
if not token:
|
| 100 |
+
print("\n❌ Login test failed!")
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
print(f"\n✅ Got access token: {token[:20]}...")
|
| 104 |
+
|
| 105 |
+
# Test create task
|
| 106 |
+
if not test_create_task(token):
|
| 107 |
+
print("\n❌ Create task test failed!")
|
| 108 |
+
return
|
| 109 |
+
|
| 110 |
+
# Test get tasks
|
| 111 |
+
if not test_get_tasks(token):
|
| 112 |
+
print("\n❌ Get tasks test failed!")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
print("\n" + "=" * 50)
|
| 116 |
+
print("✅ All tests passed!")
|
| 117 |
+
print("=" * 50)
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|
test_jwt.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Test script to verify JWT authentication is working"""
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
# Fix encoding for Windows
|
| 8 |
+
if sys.platform == 'win32':
|
| 9 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 10 |
+
|
| 11 |
+
BASE_URL = "http://localhost:8001/api/v1"
|
| 12 |
+
|
| 13 |
+
print("=" * 60)
|
| 14 |
+
print("Testing JWT Authentication Flow")
|
| 15 |
+
print("=" * 60)
|
| 16 |
+
|
| 17 |
+
# Step 1: Login
|
| 18 |
+
print("\n1. Testing login...")
|
| 19 |
+
login_response = requests.post(
|
| 20 |
+
f"{BASE_URL}/auth/login",
|
| 21 |
+
json={"email": "demo@example.com", "password": "Password123!"}
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
print(f" Status: {login_response.status_code}")
|
| 25 |
+
if login_response.status_code == 200:
|
| 26 |
+
login_data = login_response.json()
|
| 27 |
+
print(f" [OK] Login successful")
|
| 28 |
+
print(f" User ID: {login_data.get('user_id')}")
|
| 29 |
+
print(f" Token: {login_data.get('access_token')[:30]}...")
|
| 30 |
+
|
| 31 |
+
token = login_data.get('access_token')
|
| 32 |
+
|
| 33 |
+
# Step 2: Test tasks endpoint with JWT
|
| 34 |
+
print("\n2. Testing tasks endpoint with JWT token...")
|
| 35 |
+
tasks_response = requests.get(
|
| 36 |
+
f"{BASE_URL}/tasks/",
|
| 37 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
print(f" Status: {tasks_response.status_code}")
|
| 41 |
+
if tasks_response.status_code == 200:
|
| 42 |
+
print(f" [OK] Tasks endpoint working with JWT!")
|
| 43 |
+
tasks = tasks_response.json()
|
| 44 |
+
print(f" Found {len(tasks)} tasks")
|
| 45 |
+
else:
|
| 46 |
+
print(f" [FAIL] Tasks endpoint failed!")
|
| 47 |
+
print(f" Error: {tasks_response.json()}")
|
| 48 |
+
else:
|
| 49 |
+
print(f" [FAIL] Login failed!")
|
| 50 |
+
print(f" Error: {login_response.json()}")
|
| 51 |
+
|
| 52 |
+
print("\n" + "=" * 60)
|
tests/integration/test_api_endpoints.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from fastapi.testclient import TestClient
|
| 3 |
+
from sqlalchemy import create_engine
|
| 4 |
+
from sqlalchemy.orm import sessionmaker
|
| 5 |
+
from src.main import app
|
| 6 |
+
from src.database import get_db, Base
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Use in-memory SQLite for testing
|
| 10 |
+
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
|
| 11 |
+
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
|
| 12 |
+
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def override_get_db():
|
| 16 |
+
"""Override database dependency for testing"""
|
| 17 |
+
try:
|
| 18 |
+
db = TestingSessionLocal()
|
| 19 |
+
yield db
|
| 20 |
+
finally:
|
| 21 |
+
db.close()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
app.dependency_overrides[get_db] = override_get_db
|
| 25 |
+
client = TestClient(app)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@pytest.fixture(scope="function")
|
| 29 |
+
def test_db():
|
| 30 |
+
"""Create test database tables before each test and drop after"""
|
| 31 |
+
Base.metadata.create_all(bind=engine)
|
| 32 |
+
yield
|
| 33 |
+
Base.metadata.drop_all(bind=engine)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestAuthEndpoints:
|
| 37 |
+
"""Integration tests for authentication endpoints"""
|
| 38 |
+
|
| 39 |
+
def test_register_user_success(self, test_db):
|
| 40 |
+
"""Test successful user registration"""
|
| 41 |
+
response = client.post(
|
| 42 |
+
"/api/v1/auth/register",
|
| 43 |
+
json={
|
| 44 |
+
"email": "test@example.com",
|
| 45 |
+
"username": "testuser",
|
| 46 |
+
"password": "SecurePass123!"
|
| 47 |
+
}
|
| 48 |
+
)
|
| 49 |
+
assert response.status_code == 201
|
| 50 |
+
data = response.json()
|
| 51 |
+
assert data["email"] == "test@example.com"
|
| 52 |
+
assert data["username"] == "testuser"
|
| 53 |
+
assert "id" in data
|
| 54 |
+
|
| 55 |
+
def test_register_duplicate_email(self, test_db):
|
| 56 |
+
"""Test registration with duplicate email"""
|
| 57 |
+
# First registration
|
| 58 |
+
client.post(
|
| 59 |
+
"/api/v1/auth/register",
|
| 60 |
+
json={
|
| 61 |
+
"email": "test@example.com",
|
| 62 |
+
"username": "testuser1",
|
| 63 |
+
"password": "SecurePass123!"
|
| 64 |
+
}
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Second registration with same email
|
| 68 |
+
response = client.post(
|
| 69 |
+
"/api/v1/auth/register",
|
| 70 |
+
json={
|
| 71 |
+
"email": "test@example.com",
|
| 72 |
+
"username": "testuser2",
|
| 73 |
+
"password": "SecurePass123!"
|
| 74 |
+
}
|
| 75 |
+
)
|
| 76 |
+
assert response.status_code == 409
|
| 77 |
+
assert "Email already registered" in response.json()["detail"]
|
| 78 |
+
|
| 79 |
+
def test_register_duplicate_username(self, test_db):
|
| 80 |
+
"""Test registration with duplicate username"""
|
| 81 |
+
# First registration
|
| 82 |
+
client.post(
|
| 83 |
+
"/api/v1/auth/register",
|
| 84 |
+
json={
|
| 85 |
+
"email": "test1@example.com",
|
| 86 |
+
"username": "testuser",
|
| 87 |
+
"password": "SecurePass123!"
|
| 88 |
+
}
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Second registration with same username
|
| 92 |
+
response = client.post(
|
| 93 |
+
"/api/v1/auth/register",
|
| 94 |
+
json={
|
| 95 |
+
"email": "test2@example.com",
|
| 96 |
+
"username": "testuser",
|
| 97 |
+
"password": "SecurePass123!"
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
assert response.status_code == 409
|
| 101 |
+
assert "Username already taken" in response.json()["detail"]
|
| 102 |
+
|
| 103 |
+
def test_login_success(self, test_db):
|
| 104 |
+
"""Test successful login"""
|
| 105 |
+
# Register user first
|
| 106 |
+
client.post(
|
| 107 |
+
"/api/v1/auth/register",
|
| 108 |
+
json={
|
| 109 |
+
"email": "test@example.com",
|
| 110 |
+
"username": "testuser",
|
| 111 |
+
"password": "SecurePass123!"
|
| 112 |
+
}
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Login
|
| 116 |
+
response = client.post(
|
| 117 |
+
"/api/v1/auth/login",
|
| 118 |
+
params={
|
| 119 |
+
"email": "test@example.com",
|
| 120 |
+
"password": "SecurePass123!"
|
| 121 |
+
}
|
| 122 |
+
)
|
| 123 |
+
assert response.status_code == 200
|
| 124 |
+
data = response.json()
|
| 125 |
+
assert "access_token" in data
|
| 126 |
+
assert data["token_type"] == "bearer"
|
| 127 |
+
assert "user_id" in data
|
| 128 |
+
|
| 129 |
+
def test_login_wrong_password(self, test_db):
|
| 130 |
+
"""Test login with wrong password"""
|
| 131 |
+
# Register user first
|
| 132 |
+
client.post(
|
| 133 |
+
"/api/v1/auth/register",
|
| 134 |
+
json={
|
| 135 |
+
"email": "test@example.com",
|
| 136 |
+
"username": "testuser",
|
| 137 |
+
"password": "SecurePass123!"
|
| 138 |
+
}
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
# Login with wrong password
|
| 142 |
+
response = client.post(
|
| 143 |
+
"/api/v1/auth/login",
|
| 144 |
+
params={
|
| 145 |
+
"email": "test@example.com",
|
| 146 |
+
"password": "WrongPassword"
|
| 147 |
+
}
|
| 148 |
+
)
|
| 149 |
+
assert response.status_code == 401
|
| 150 |
+
assert "Incorrect email or password" in response.json()["detail"]
|
| 151 |
+
|
| 152 |
+
def test_login_nonexistent_user(self, test_db):
|
| 153 |
+
"""Test login with non-existent user"""
|
| 154 |
+
response = client.post(
|
| 155 |
+
"/api/v1/auth/login",
|
| 156 |
+
params={
|
| 157 |
+
"email": "nonexistent@example.com",
|
| 158 |
+
"password": "SecurePass123!"
|
| 159 |
+
}
|
| 160 |
+
)
|
| 161 |
+
assert response.status_code == 401
|
| 162 |
+
|
| 163 |
+
def test_get_current_user(self, test_db):
|
| 164 |
+
"""Test getting current user information"""
|
| 165 |
+
# Register and login
|
| 166 |
+
client.post(
|
| 167 |
+
"/api/v1/auth/register",
|
| 168 |
+
json={
|
| 169 |
+
"email": "test@example.com",
|
| 170 |
+
"username": "testuser",
|
| 171 |
+
"password": "SecurePass123!"
|
| 172 |
+
}
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
login_response = client.post(
|
| 176 |
+
"/api/v1/auth/login",
|
| 177 |
+
params={
|
| 178 |
+
"email": "test@example.com",
|
| 179 |
+
"password": "SecurePass123!"
|
| 180 |
+
}
|
| 181 |
+
)
|
| 182 |
+
token = login_response.json()["access_token"]
|
| 183 |
+
|
| 184 |
+
# Get current user
|
| 185 |
+
response = client.get(
|
| 186 |
+
"/api/v1/auth/me",
|
| 187 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 188 |
+
)
|
| 189 |
+
assert response.status_code == 200
|
| 190 |
+
data = response.json()
|
| 191 |
+
assert data["email"] == "test@example.com"
|
| 192 |
+
assert data["username"] == "testuser"
|
| 193 |
+
|
| 194 |
+
def test_get_current_user_invalid_token(self, test_db):
|
| 195 |
+
"""Test getting current user with invalid token"""
|
| 196 |
+
response = client.get(
|
| 197 |
+
"/api/v1/auth/me",
|
| 198 |
+
headers={"Authorization": "Bearer invalid_token"}
|
| 199 |
+
)
|
| 200 |
+
assert response.status_code == 401
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class TestTaskEndpoints:
|
| 204 |
+
"""Integration tests for task endpoints"""
|
| 205 |
+
|
| 206 |
+
def get_auth_token(self):
|
| 207 |
+
"""Helper method to register and login a user"""
|
| 208 |
+
client.post(
|
| 209 |
+
"/api/v1/auth/register",
|
| 210 |
+
json={
|
| 211 |
+
"email": "test@example.com",
|
| 212 |
+
"username": "testuser",
|
| 213 |
+
"password": "SecurePass123!"
|
| 214 |
+
}
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
login_response = client.post(
|
| 218 |
+
"/api/v1/auth/login",
|
| 219 |
+
params={
|
| 220 |
+
"email": "test@example.com",
|
| 221 |
+
"password": "SecurePass123!"
|
| 222 |
+
}
|
| 223 |
+
)
|
| 224 |
+
return login_response.json()["access_token"]
|
| 225 |
+
|
| 226 |
+
def test_create_task_success(self, test_db):
|
| 227 |
+
"""Test successful task creation"""
|
| 228 |
+
token = self.get_auth_token()
|
| 229 |
+
|
| 230 |
+
response = client.post(
|
| 231 |
+
"/api/v1/tasks/",
|
| 232 |
+
json={
|
| 233 |
+
"title": "Test Task",
|
| 234 |
+
"description": "Test Description",
|
| 235 |
+
"status": "pending"
|
| 236 |
+
},
|
| 237 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 238 |
+
)
|
| 239 |
+
assert response.status_code == 201
|
| 240 |
+
data = response.json()
|
| 241 |
+
assert data["title"] == "Test Task"
|
| 242 |
+
assert data["description"] == "Test Description"
|
| 243 |
+
assert data["status"] == "pending"
|
| 244 |
+
assert "id" in data
|
| 245 |
+
|
| 246 |
+
def test_create_task_invalid_status(self, test_db):
|
| 247 |
+
"""Test task creation with invalid status"""
|
| 248 |
+
token = self.get_auth_token()
|
| 249 |
+
|
| 250 |
+
response = client.post(
|
| 251 |
+
"/api/v1/tasks/",
|
| 252 |
+
json={
|
| 253 |
+
"title": "Test Task",
|
| 254 |
+
"description": "Test Description",
|
| 255 |
+
"status": "invalid_status"
|
| 256 |
+
},
|
| 257 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 258 |
+
)
|
| 259 |
+
assert response.status_code == 400
|
| 260 |
+
|
| 261 |
+
def test_create_task_unauthorized(self, test_db):
|
| 262 |
+
"""Test task creation without authentication"""
|
| 263 |
+
response = client.post(
|
| 264 |
+
"/api/v1/tasks/",
|
| 265 |
+
json={
|
| 266 |
+
"title": "Test Task",
|
| 267 |
+
"description": "Test Description",
|
| 268 |
+
"status": "pending"
|
| 269 |
+
}
|
| 270 |
+
)
|
| 271 |
+
assert response.status_code == 403
|
| 272 |
+
|
| 273 |
+
def test_get_tasks(self, test_db):
|
| 274 |
+
"""Test retrieving all tasks for a user"""
|
| 275 |
+
token = self.get_auth_token()
|
| 276 |
+
|
| 277 |
+
# Create multiple tasks
|
| 278 |
+
for i in range(3):
|
| 279 |
+
client.post(
|
| 280 |
+
"/api/v1/tasks/",
|
| 281 |
+
json={
|
| 282 |
+
"title": f"Task {i}",
|
| 283 |
+
"description": f"Description {i}",
|
| 284 |
+
"status": "pending"
|
| 285 |
+
},
|
| 286 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Get all tasks
|
| 290 |
+
response = client.get(
|
| 291 |
+
"/api/v1/tasks/",
|
| 292 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 293 |
+
)
|
| 294 |
+
assert response.status_code == 200
|
| 295 |
+
data = response.json()
|
| 296 |
+
assert len(data) == 3
|
| 297 |
+
|
| 298 |
+
def test_get_task_by_id(self, test_db):
|
| 299 |
+
"""Test retrieving a specific task"""
|
| 300 |
+
token = self.get_auth_token()
|
| 301 |
+
|
| 302 |
+
# Create a task
|
| 303 |
+
create_response = client.post(
|
| 304 |
+
"/api/v1/tasks/",
|
| 305 |
+
json={
|
| 306 |
+
"title": "Test Task",
|
| 307 |
+
"description": "Test Description",
|
| 308 |
+
"status": "pending"
|
| 309 |
+
},
|
| 310 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 311 |
+
)
|
| 312 |
+
task_id = create_response.json()["id"]
|
| 313 |
+
|
| 314 |
+
# Get the task
|
| 315 |
+
response = client.get(
|
| 316 |
+
f"/api/v1/tasks/{task_id}",
|
| 317 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 318 |
+
)
|
| 319 |
+
assert response.status_code == 200
|
| 320 |
+
data = response.json()
|
| 321 |
+
assert data["id"] == task_id
|
| 322 |
+
assert data["title"] == "Test Task"
|
| 323 |
+
|
| 324 |
+
def test_get_task_not_found(self, test_db):
|
| 325 |
+
"""Test retrieving a non-existent task"""
|
| 326 |
+
token = self.get_auth_token()
|
| 327 |
+
|
| 328 |
+
response = client.get(
|
| 329 |
+
"/api/v1/tasks/999",
|
| 330 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 331 |
+
)
|
| 332 |
+
assert response.status_code == 404
|
| 333 |
+
|
| 334 |
+
def test_update_task(self, test_db):
|
| 335 |
+
"""Test updating a task"""
|
| 336 |
+
token = self.get_auth_token()
|
| 337 |
+
|
| 338 |
+
# Create a task
|
| 339 |
+
create_response = client.post(
|
| 340 |
+
"/api/v1/tasks/",
|
| 341 |
+
json={
|
| 342 |
+
"title": "Original Title",
|
| 343 |
+
"description": "Original Description",
|
| 344 |
+
"status": "pending"
|
| 345 |
+
},
|
| 346 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 347 |
+
)
|
| 348 |
+
task_id = create_response.json()["id"]
|
| 349 |
+
|
| 350 |
+
# Update the task
|
| 351 |
+
response = client.put(
|
| 352 |
+
f"/api/v1/tasks/{task_id}",
|
| 353 |
+
json={
|
| 354 |
+
"title": "Updated Title",
|
| 355 |
+
"status": "completed"
|
| 356 |
+
},
|
| 357 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 358 |
+
)
|
| 359 |
+
assert response.status_code == 200
|
| 360 |
+
data = response.json()
|
| 361 |
+
assert data["title"] == "Updated Title"
|
| 362 |
+
assert data["status"] == "completed"
|
| 363 |
+
|
| 364 |
+
def test_delete_task(self, test_db):
|
| 365 |
+
"""Test deleting a task"""
|
| 366 |
+
token = self.get_auth_token()
|
| 367 |
+
|
| 368 |
+
# Create a task
|
| 369 |
+
create_response = client.post(
|
| 370 |
+
"/api/v1/tasks/",
|
| 371 |
+
json={
|
| 372 |
+
"title": "Test Task",
|
| 373 |
+
"description": "Test Description",
|
| 374 |
+
"status": "pending"
|
| 375 |
+
},
|
| 376 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 377 |
+
)
|
| 378 |
+
task_id = create_response.json()["id"]
|
| 379 |
+
|
| 380 |
+
# Delete the task
|
| 381 |
+
response = client.delete(
|
| 382 |
+
f"/api/v1/tasks/{task_id}",
|
| 383 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 384 |
+
)
|
| 385 |
+
assert response.status_code == 204
|
| 386 |
+
|
| 387 |
+
# Verify task is deleted
|
| 388 |
+
get_response = client.get(
|
| 389 |
+
f"/api/v1/tasks/{task_id}",
|
| 390 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 391 |
+
)
|
| 392 |
+
assert get_response.status_code == 404
|
| 393 |
+
|
| 394 |
+
def test_user_isolation(self, test_db):
|
| 395 |
+
"""Test that users can only access their own tasks"""
|
| 396 |
+
# Create first user and task
|
| 397 |
+
client.post(
|
| 398 |
+
"/api/v1/auth/register",
|
| 399 |
+
json={
|
| 400 |
+
"email": "user1@example.com",
|
| 401 |
+
"username": "user1",
|
| 402 |
+
"password": "SecurePass123!"
|
| 403 |
+
}
|
| 404 |
+
)
|
| 405 |
+
login1 = client.post(
|
| 406 |
+
"/api/v1/auth/login",
|
| 407 |
+
params={"email": "user1@example.com", "password": "SecurePass123!"}
|
| 408 |
+
)
|
| 409 |
+
token1 = login1.json()["access_token"]
|
| 410 |
+
|
| 411 |
+
create_response = client.post(
|
| 412 |
+
"/api/v1/tasks/",
|
| 413 |
+
json={"title": "User 1 Task", "status": "pending"},
|
| 414 |
+
headers={"Authorization": f"Bearer {token1}"}
|
| 415 |
+
)
|
| 416 |
+
task_id = create_response.json()["id"]
|
| 417 |
+
|
| 418 |
+
# Create second user
|
| 419 |
+
client.post(
|
| 420 |
+
"/api/v1/auth/register",
|
| 421 |
+
json={
|
| 422 |
+
"email": "user2@example.com",
|
| 423 |
+
"username": "user2",
|
| 424 |
+
"password": "SecurePass123!"
|
| 425 |
+
}
|
| 426 |
+
)
|
| 427 |
+
login2 = client.post(
|
| 428 |
+
"/api/v1/auth/login",
|
| 429 |
+
params={"email": "user2@example.com", "password": "SecurePass123!"}
|
| 430 |
+
)
|
| 431 |
+
token2 = login2.json()["access_token"]
|
| 432 |
+
|
| 433 |
+
# Try to access user1's task with user2's token
|
| 434 |
+
response = client.get(
|
| 435 |
+
f"/api/v1/tasks/{task_id}",
|
| 436 |
+
headers={"Authorization": f"Bearer {token2}"}
|
| 437 |
+
)
|
| 438 |
+
assert response.status_code == 404 # Should not find the task
|
tests/unit/test_task_service.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from unittest.mock import Mock, MagicMock
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from src.services.task_service import TaskService
|
| 5 |
+
from src.models.task import Task, TaskCreate, TaskUpdate
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestTaskService:
|
| 9 |
+
"""Unit tests for TaskService"""
|
| 10 |
+
|
| 11 |
+
def test_create_task_success(self):
|
| 12 |
+
"""Test successful task creation"""
|
| 13 |
+
# Arrange
|
| 14 |
+
mock_db = Mock(spec=Session)
|
| 15 |
+
task_data = TaskCreate(
|
| 16 |
+
title="Test Task",
|
| 17 |
+
description="Test Description",
|
| 18 |
+
status="pending"
|
| 19 |
+
)
|
| 20 |
+
user_id = 1
|
| 21 |
+
|
| 22 |
+
# Mock the database operations
|
| 23 |
+
mock_db.add = Mock()
|
| 24 |
+
mock_db.commit = Mock()
|
| 25 |
+
mock_db.refresh = Mock()
|
| 26 |
+
|
| 27 |
+
# Act
|
| 28 |
+
result = TaskService.create_task(mock_db, task_data, user_id)
|
| 29 |
+
|
| 30 |
+
# Assert
|
| 31 |
+
mock_db.add.assert_called_once()
|
| 32 |
+
mock_db.commit.assert_called_once()
|
| 33 |
+
mock_db.refresh.assert_called_once()
|
| 34 |
+
assert result.title == "Test Task"
|
| 35 |
+
assert result.user_id == user_id
|
| 36 |
+
|
| 37 |
+
def test_create_task_integrity_error(self):
|
| 38 |
+
"""Test task creation with integrity constraint violation"""
|
| 39 |
+
# Arrange
|
| 40 |
+
from sqlalchemy.exc import IntegrityError
|
| 41 |
+
mock_db = Mock(spec=Session)
|
| 42 |
+
task_data = TaskCreate(
|
| 43 |
+
title="Test Task",
|
| 44 |
+
description="Test Description",
|
| 45 |
+
status="pending"
|
| 46 |
+
)
|
| 47 |
+
user_id = 1
|
| 48 |
+
|
| 49 |
+
# Mock database to raise IntegrityError
|
| 50 |
+
mock_db.add = Mock()
|
| 51 |
+
mock_db.commit = Mock(side_effect=IntegrityError("", "", ""))
|
| 52 |
+
mock_db.rollback = Mock()
|
| 53 |
+
|
| 54 |
+
# Act & Assert
|
| 55 |
+
with pytest.raises(ValueError, match="Failed to create task"):
|
| 56 |
+
TaskService.create_task(mock_db, task_data, user_id)
|
| 57 |
+
|
| 58 |
+
mock_db.rollback.assert_called_once()
|
| 59 |
+
|
| 60 |
+
def test_get_task_by_id_found(self):
|
| 61 |
+
"""Test retrieving an existing task"""
|
| 62 |
+
# Arrange
|
| 63 |
+
mock_db = Mock(spec=Session)
|
| 64 |
+
task_id = 1
|
| 65 |
+
user_id = 1
|
| 66 |
+
|
| 67 |
+
mock_task = Task(
|
| 68 |
+
id=task_id,
|
| 69 |
+
title="Test Task",
|
| 70 |
+
description="Test Description",
|
| 71 |
+
status="pending",
|
| 72 |
+
user_id=user_id
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
mock_query = MagicMock()
|
| 76 |
+
mock_db.query.return_value = mock_query
|
| 77 |
+
mock_query.filter.return_value.first.return_value = mock_task
|
| 78 |
+
|
| 79 |
+
# Act
|
| 80 |
+
result = TaskService.get_task_by_id(mock_db, task_id, user_id)
|
| 81 |
+
|
| 82 |
+
# Assert
|
| 83 |
+
assert result is not None
|
| 84 |
+
assert result.id == task_id
|
| 85 |
+
assert result.user_id == user_id
|
| 86 |
+
|
| 87 |
+
def test_get_task_by_id_not_found(self):
|
| 88 |
+
"""Test retrieving a non-existent task"""
|
| 89 |
+
# Arrange
|
| 90 |
+
mock_db = Mock(spec=Session)
|
| 91 |
+
task_id = 999
|
| 92 |
+
user_id = 1
|
| 93 |
+
|
| 94 |
+
mock_query = MagicMock()
|
| 95 |
+
mock_db.query.return_value = mock_query
|
| 96 |
+
mock_query.filter.return_value.first.return_value = None
|
| 97 |
+
|
| 98 |
+
# Act
|
| 99 |
+
result = TaskService.get_task_by_id(mock_db, task_id, user_id)
|
| 100 |
+
|
| 101 |
+
# Assert
|
| 102 |
+
assert result is None
|
| 103 |
+
|
| 104 |
+
def test_get_tasks_for_user(self):
|
| 105 |
+
"""Test retrieving all tasks for a user"""
|
| 106 |
+
# Arrange
|
| 107 |
+
mock_db = Mock(spec=Session)
|
| 108 |
+
user_id = 1
|
| 109 |
+
|
| 110 |
+
mock_tasks = [
|
| 111 |
+
Task(id=1, title="Task 1", status="pending", user_id=user_id),
|
| 112 |
+
Task(id=2, title="Task 2", status="completed", user_id=user_id)
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
mock_query = MagicMock()
|
| 116 |
+
mock_db.query.return_value = mock_query
|
| 117 |
+
mock_query.filter.return_value.offset.return_value.limit.return_value.all.return_value = mock_tasks
|
| 118 |
+
|
| 119 |
+
# Act
|
| 120 |
+
result = TaskService.get_tasks_for_user(mock_db, user_id)
|
| 121 |
+
|
| 122 |
+
# Assert
|
| 123 |
+
assert len(result) == 2
|
| 124 |
+
assert all(task.user_id == user_id for task in result)
|
| 125 |
+
|
| 126 |
+
def test_update_task_success(self):
|
| 127 |
+
"""Test successful task update"""
|
| 128 |
+
# Arrange
|
| 129 |
+
mock_db = Mock(spec=Session)
|
| 130 |
+
task_id = 1
|
| 131 |
+
user_id = 1
|
| 132 |
+
|
| 133 |
+
mock_task = Task(
|
| 134 |
+
id=task_id,
|
| 135 |
+
title="Old Title",
|
| 136 |
+
description="Old Description",
|
| 137 |
+
status="pending",
|
| 138 |
+
user_id=user_id
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
task_update = TaskUpdate(
|
| 142 |
+
title="New Title",
|
| 143 |
+
status="completed"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
mock_query = MagicMock()
|
| 147 |
+
mock_db.query.return_value = mock_query
|
| 148 |
+
mock_query.filter.return_value.first.return_value = mock_task
|
| 149 |
+
mock_db.commit = Mock()
|
| 150 |
+
mock_db.refresh = Mock()
|
| 151 |
+
|
| 152 |
+
# Act
|
| 153 |
+
result = TaskService.update_task(mock_db, task_id, task_update, user_id)
|
| 154 |
+
|
| 155 |
+
# Assert
|
| 156 |
+
assert result is not None
|
| 157 |
+
assert result.title == "New Title"
|
| 158 |
+
assert result.status == "completed"
|
| 159 |
+
mock_db.commit.assert_called_once()
|
| 160 |
+
|
| 161 |
+
def test_update_task_not_found(self):
|
| 162 |
+
"""Test updating a non-existent task"""
|
| 163 |
+
# Arrange
|
| 164 |
+
mock_db = Mock(spec=Session)
|
| 165 |
+
task_id = 999
|
| 166 |
+
user_id = 1
|
| 167 |
+
task_update = TaskUpdate(title="New Title")
|
| 168 |
+
|
| 169 |
+
mock_query = MagicMock()
|
| 170 |
+
mock_db.query.return_value = mock_query
|
| 171 |
+
mock_query.filter.return_value.first.return_value = None
|
| 172 |
+
|
| 173 |
+
# Act
|
| 174 |
+
result = TaskService.update_task(mock_db, task_id, task_update, user_id)
|
| 175 |
+
|
| 176 |
+
# Assert
|
| 177 |
+
assert result is None
|
| 178 |
+
|
| 179 |
+
def test_delete_task_success(self):
|
| 180 |
+
"""Test successful task deletion"""
|
| 181 |
+
# Arrange
|
| 182 |
+
mock_db = Mock(spec=Session)
|
| 183 |
+
task_id = 1
|
| 184 |
+
user_id = 1
|
| 185 |
+
|
| 186 |
+
mock_task = Task(
|
| 187 |
+
id=task_id,
|
| 188 |
+
title="Test Task",
|
| 189 |
+
status="pending",
|
| 190 |
+
user_id=user_id
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
mock_query = MagicMock()
|
| 194 |
+
mock_db.query.return_value = mock_query
|
| 195 |
+
mock_query.filter.return_value.first.return_value = mock_task
|
| 196 |
+
mock_db.delete = Mock()
|
| 197 |
+
mock_db.commit = Mock()
|
| 198 |
+
|
| 199 |
+
# Act
|
| 200 |
+
result = TaskService.delete_task(mock_db, task_id, user_id)
|
| 201 |
+
|
| 202 |
+
# Assert
|
| 203 |
+
assert result is True
|
| 204 |
+
mock_db.delete.assert_called_once_with(mock_task)
|
| 205 |
+
mock_db.commit.assert_called_once()
|
| 206 |
+
|
| 207 |
+
def test_delete_task_not_found(self):
|
| 208 |
+
"""Test deleting a non-existent task"""
|
| 209 |
+
# Arrange
|
| 210 |
+
mock_db = Mock(spec=Session)
|
| 211 |
+
task_id = 999
|
| 212 |
+
user_id = 1
|
| 213 |
+
|
| 214 |
+
mock_query = MagicMock()
|
| 215 |
+
mock_db.query.return_value = mock_query
|
| 216 |
+
mock_query.filter.return_value.first.return_value = None
|
| 217 |
+
|
| 218 |
+
# Act
|
| 219 |
+
result = TaskService.delete_task(mock_db, task_id, user_id)
|
| 220 |
+
|
| 221 |
+
# Assert
|
| 222 |
+
assert result is False
|
| 223 |
+
|
| 224 |
+
def test_get_tasks_by_status(self):
|
| 225 |
+
"""Test retrieving tasks filtered by status"""
|
| 226 |
+
# Arrange
|
| 227 |
+
mock_db = Mock(spec=Session)
|
| 228 |
+
user_id = 1
|
| 229 |
+
status = "completed"
|
| 230 |
+
|
| 231 |
+
mock_tasks = [
|
| 232 |
+
Task(id=1, title="Task 1", status="completed", user_id=user_id),
|
| 233 |
+
Task(id=2, title="Task 2", status="completed", user_id=user_id)
|
| 234 |
+
]
|
| 235 |
+
|
| 236 |
+
mock_query = MagicMock()
|
| 237 |
+
mock_db.query.return_value = mock_query
|
| 238 |
+
mock_query.filter.return_value.all.return_value = mock_tasks
|
| 239 |
+
|
| 240 |
+
# Act
|
| 241 |
+
result = TaskService.get_tasks_by_status(mock_db, user_id, status)
|
| 242 |
+
|
| 243 |
+
# Assert
|
| 244 |
+
assert len(result) == 2
|
| 245 |
+
assert all(task.status == status for task in result)
|
tests/unit/test_user_service.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from unittest.mock import Mock, MagicMock
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
from src.services.user_service import UserService
|
| 5 |
+
from src.models.user import User, UserCreate, UserUpdate
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestUserService:
|
| 9 |
+
"""Unit tests for UserService"""
|
| 10 |
+
|
| 11 |
+
def test_create_user_success(self):
|
| 12 |
+
"""Test successful user creation"""
|
| 13 |
+
# Arrange
|
| 14 |
+
mock_db = Mock(spec=Session)
|
| 15 |
+
user_data = UserCreate(
|
| 16 |
+
email="test@example.com",
|
| 17 |
+
username="testuser",
|
| 18 |
+
password="SecurePass123!"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Mock the database operations
|
| 22 |
+
mock_db.add = Mock()
|
| 23 |
+
mock_db.commit = Mock()
|
| 24 |
+
mock_db.refresh = Mock()
|
| 25 |
+
|
| 26 |
+
# Act
|
| 27 |
+
result = UserService.create_user(mock_db, user_data)
|
| 28 |
+
|
| 29 |
+
# Assert
|
| 30 |
+
mock_db.add.assert_called_once()
|
| 31 |
+
mock_db.commit.assert_called_once()
|
| 32 |
+
mock_db.refresh.assert_called_once()
|
| 33 |
+
assert result.email == "test@example.com"
|
| 34 |
+
assert result.username == "testuser"
|
| 35 |
+
|
| 36 |
+
def test_get_user_by_id_found(self):
|
| 37 |
+
"""Test retrieving an existing user by ID"""
|
| 38 |
+
# Arrange
|
| 39 |
+
mock_db = Mock(spec=Session)
|
| 40 |
+
user_id = 1
|
| 41 |
+
|
| 42 |
+
mock_user = User(
|
| 43 |
+
id=user_id,
|
| 44 |
+
email="test@example.com",
|
| 45 |
+
username="testuser",
|
| 46 |
+
password_hash="hashed_password",
|
| 47 |
+
is_active=True
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
mock_query = MagicMock()
|
| 51 |
+
mock_db.query.return_value = mock_query
|
| 52 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 53 |
+
|
| 54 |
+
# Act
|
| 55 |
+
result = UserService.get_user_by_id(mock_db, user_id)
|
| 56 |
+
|
| 57 |
+
# Assert
|
| 58 |
+
assert result is not None
|
| 59 |
+
assert result.id == user_id
|
| 60 |
+
assert result.email == "test@example.com"
|
| 61 |
+
|
| 62 |
+
def test_get_user_by_id_not_found(self):
|
| 63 |
+
"""Test retrieving a non-existent user by ID"""
|
| 64 |
+
# Arrange
|
| 65 |
+
mock_db = Mock(spec=Session)
|
| 66 |
+
user_id = 999
|
| 67 |
+
|
| 68 |
+
mock_query = MagicMock()
|
| 69 |
+
mock_db.query.return_value = mock_query
|
| 70 |
+
mock_query.filter.return_value.first.return_value = None
|
| 71 |
+
|
| 72 |
+
# Act
|
| 73 |
+
result = UserService.get_user_by_id(mock_db, user_id)
|
| 74 |
+
|
| 75 |
+
# Assert
|
| 76 |
+
assert result is None
|
| 77 |
+
|
| 78 |
+
def test_get_user_by_email_found(self):
|
| 79 |
+
"""Test retrieving an existing user by email"""
|
| 80 |
+
# Arrange
|
| 81 |
+
mock_db = Mock(spec=Session)
|
| 82 |
+
email = "test@example.com"
|
| 83 |
+
|
| 84 |
+
mock_user = User(
|
| 85 |
+
id=1,
|
| 86 |
+
email=email,
|
| 87 |
+
username="testuser",
|
| 88 |
+
password_hash="hashed_password",
|
| 89 |
+
is_active=True
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
mock_query = MagicMock()
|
| 93 |
+
mock_db.query.return_value = mock_query
|
| 94 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 95 |
+
|
| 96 |
+
# Act
|
| 97 |
+
result = UserService.get_user_by_email(mock_db, email)
|
| 98 |
+
|
| 99 |
+
# Assert
|
| 100 |
+
assert result is not None
|
| 101 |
+
assert result.email == email
|
| 102 |
+
|
| 103 |
+
def test_get_user_by_email_not_found(self):
|
| 104 |
+
"""Test retrieving a non-existent user by email"""
|
| 105 |
+
# Arrange
|
| 106 |
+
mock_db = Mock(spec=Session)
|
| 107 |
+
email = "nonexistent@example.com"
|
| 108 |
+
|
| 109 |
+
mock_query = MagicMock()
|
| 110 |
+
mock_db.query.return_value = mock_query
|
| 111 |
+
mock_query.filter.return_value.first.return_value = None
|
| 112 |
+
|
| 113 |
+
# Act
|
| 114 |
+
result = UserService.get_user_by_email(mock_db, email)
|
| 115 |
+
|
| 116 |
+
# Assert
|
| 117 |
+
assert result is None
|
| 118 |
+
|
| 119 |
+
def test_get_user_by_username_found(self):
|
| 120 |
+
"""Test retrieving an existing user by username"""
|
| 121 |
+
# Arrange
|
| 122 |
+
mock_db = Mock(spec=Session)
|
| 123 |
+
username = "testuser"
|
| 124 |
+
|
| 125 |
+
mock_user = User(
|
| 126 |
+
id=1,
|
| 127 |
+
email="test@example.com",
|
| 128 |
+
username=username,
|
| 129 |
+
password_hash="hashed_password",
|
| 130 |
+
is_active=True
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
mock_query = MagicMock()
|
| 134 |
+
mock_db.query.return_value = mock_query
|
| 135 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 136 |
+
|
| 137 |
+
# Act
|
| 138 |
+
result = UserService.get_user_by_username(mock_db, username)
|
| 139 |
+
|
| 140 |
+
# Assert
|
| 141 |
+
assert result is not None
|
| 142 |
+
assert result.username == username
|
| 143 |
+
|
| 144 |
+
def test_get_user_by_username_not_found(self):
|
| 145 |
+
"""Test retrieving a non-existent user by username"""
|
| 146 |
+
# Arrange
|
| 147 |
+
mock_db = Mock(spec=Session)
|
| 148 |
+
username = "nonexistent"
|
| 149 |
+
|
| 150 |
+
mock_query = MagicMock()
|
| 151 |
+
mock_db.query.return_value = mock_query
|
| 152 |
+
mock_query.filter.return_value.first.return_value = None
|
| 153 |
+
|
| 154 |
+
# Act
|
| 155 |
+
result = UserService.get_user_by_username(mock_db, username)
|
| 156 |
+
|
| 157 |
+
# Assert
|
| 158 |
+
assert result is None
|
| 159 |
+
|
| 160 |
+
def test_authenticate_user_success(self):
|
| 161 |
+
"""Test successful user authentication"""
|
| 162 |
+
# Arrange
|
| 163 |
+
mock_db = Mock(spec=Session)
|
| 164 |
+
email = "test@example.com"
|
| 165 |
+
password = "SecurePass123!"
|
| 166 |
+
|
| 167 |
+
# Mock user with hashed password
|
| 168 |
+
from passlib.context import CryptContext
|
| 169 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 170 |
+
hashed_password = pwd_context.hash(password)
|
| 171 |
+
|
| 172 |
+
mock_user = User(
|
| 173 |
+
id=1,
|
| 174 |
+
email=email,
|
| 175 |
+
username="testuser",
|
| 176 |
+
password_hash=hashed_password,
|
| 177 |
+
is_active=True
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
mock_query = MagicMock()
|
| 181 |
+
mock_db.query.return_value = mock_query
|
| 182 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 183 |
+
|
| 184 |
+
# Act
|
| 185 |
+
result = UserService.authenticate_user(mock_db, email, password)
|
| 186 |
+
|
| 187 |
+
# Assert
|
| 188 |
+
assert result is not None
|
| 189 |
+
assert result.email == email
|
| 190 |
+
|
| 191 |
+
def test_authenticate_user_wrong_password(self):
|
| 192 |
+
"""Test authentication with wrong password"""
|
| 193 |
+
# Arrange
|
| 194 |
+
mock_db = Mock(spec=Session)
|
| 195 |
+
email = "test@example.com"
|
| 196 |
+
correct_password = "SecurePass123!"
|
| 197 |
+
wrong_password = "WrongPassword"
|
| 198 |
+
|
| 199 |
+
# Mock user with hashed password
|
| 200 |
+
from passlib.context import CryptContext
|
| 201 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 202 |
+
hashed_password = pwd_context.hash(correct_password)
|
| 203 |
+
|
| 204 |
+
mock_user = User(
|
| 205 |
+
id=1,
|
| 206 |
+
email=email,
|
| 207 |
+
username="testuser",
|
| 208 |
+
password_hash=hashed_password,
|
| 209 |
+
is_active=True
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
mock_query = MagicMock()
|
| 213 |
+
mock_db.query.return_value = mock_query
|
| 214 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 215 |
+
|
| 216 |
+
# Act
|
| 217 |
+
result = UserService.authenticate_user(mock_db, email, wrong_password)
|
| 218 |
+
|
| 219 |
+
# Assert
|
| 220 |
+
assert result is None
|
| 221 |
+
|
| 222 |
+
def test_authenticate_user_not_found(self):
|
| 223 |
+
"""Test authentication with non-existent user"""
|
| 224 |
+
# Arrange
|
| 225 |
+
mock_db = Mock(spec=Session)
|
| 226 |
+
email = "nonexistent@example.com"
|
| 227 |
+
password = "SecurePass123!"
|
| 228 |
+
|
| 229 |
+
mock_query = MagicMock()
|
| 230 |
+
mock_db.query.return_value = mock_query
|
| 231 |
+
mock_query.filter.return_value.first.return_value = None
|
| 232 |
+
|
| 233 |
+
# Act
|
| 234 |
+
result = UserService.authenticate_user(mock_db, email, password)
|
| 235 |
+
|
| 236 |
+
# Assert
|
| 237 |
+
assert result is None
|
| 238 |
+
|
| 239 |
+
def test_update_user_success(self):
|
| 240 |
+
"""Test successful user update"""
|
| 241 |
+
# Arrange
|
| 242 |
+
mock_db = Mock(spec=Session)
|
| 243 |
+
user_id = 1
|
| 244 |
+
|
| 245 |
+
mock_user = User(
|
| 246 |
+
id=user_id,
|
| 247 |
+
email="old@example.com",
|
| 248 |
+
username="oldusername",
|
| 249 |
+
password_hash="hashed_password",
|
| 250 |
+
is_active=True
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
user_update = UserUpdate(
|
| 254 |
+
email="new@example.com",
|
| 255 |
+
username="newusername"
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
mock_query = MagicMock()
|
| 259 |
+
mock_db.query.return_value = mock_query
|
| 260 |
+
mock_query.filter.return_value.first.return_value = mock_user
|
| 261 |
+
mock_db.commit = Mock()
|
| 262 |
+
mock_db.refresh = Mock()
|
| 263 |
+
|
| 264 |
+
# Act
|
| 265 |
+
result = UserService.update_user(mock_db, user_id, user_update)
|
| 266 |
+
|
| 267 |
+
# Assert
|
| 268 |
+
assert result is not None
|
| 269 |
+
assert result.email == "new@example.com"
|
| 270 |
+
assert result.username == "newusername"
|
| 271 |
+
mock_db.commit.assert_called_once()
|
| 272 |
+
|
| 273 |
+
def test_update_user_not_found(self):
|
| 274 |
+
"""Test updating a non-existent user"""
|
| 275 |
+
# Arrange
|
| 276 |
+
mock_db = Mock(spec=Session)
|
| 277 |
+
user_id = 999
|
| 278 |
+
user_update = UserUpdate(email="new@example.com")
|
| 279 |
+
|
| 280 |
+
mock_query = MagicMock()
|
| 281 |
+
mock_db.query.return_value = mock_query
|
| 282 |
+
mock_query.filter.return_value.first.return_value = None
|
| 283 |
+
|
| 284 |
+
# Act
|
| 285 |
+
result = UserService.update_user(mock_db, user_id, user_update)
|
| 286 |
+
|
| 287 |
+
# Assert
|
| 288 |
+
assert result is None
|