149189 / 149189/Singularity

500 Internal Server Error when POSTing to /api/auth/register

オープン
#1 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る
backend bug
主要言語
Python
スター
0
フォーク
0
PR マージ指標
30日以内にマージされた PR はありません

説明

## Description

POST requests to the `/api/auth/register` endpoint return `500 Internal Server Error` during registration. Server starts up fine and connects to MongoDB, but the register route fails at runtime. The error is not currently showing a full traceback in the response — we need the root cause (duplicate key, hashing error, JWT misconfiguration, etc.).

## Reproduction Steps

1. Start the backend:

```bash
(venv) C:\Users\kaust\OneDrive\Documents\GitHub\Singularity\backend> py run.py
```

2. Send a registration request:

```bash
curl -v -X POST http://127.0.0.1:8000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"Pass1234"}'
```

## Observed Behavior

* The server prints startup logs and connects to MongoDB, then:

```
INFO: 127.0.0.1:62275 - "OPTIONS /api/auth/register HTTP/1.1" 200 OK
Registration error:
INFO: 127.0.0.1:62275 - "POST /api/auth/register HTTP/1.1" 500 Internal Server Error
```

* The client receives HTTP 500; no detailed traceback is currently visible in logs posted here.

## Expected Behavior

* Successful registration returns `201` or `200` with created user id / token.
* If the request is invalid (e.g., duplicate email), return `400` with a helpful error message (e.g., "Email already registered").
* Full traceback logged to server console (in dev) for easier debugging.

## Environment

* OS: Windows (logs from `C:\Users\kaust\OneDrive\...`)
* Python: running `py run.py` from venv
* Server: Uvicorn (auto reload)
* Database: MongoDB (connected; DB name: `singularity`)
* Stack: FastAPI + Mongo driver (Motor )

## Logs

```
(venv) C:\Users\kaust\OneDrive\Documents\GitHub\Singularity\backend>py run.py
INFO: Will watch for changes in these directories: ['C:\\Users\\kaust\\OneDrive\\Documents\\GitHub\\Singularity\\backend']
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started reloader process [31464] using StatReload
INFO: Started server process [22052]
INFO: Waiting for application startup.
✅ Connected to MongoDB: singularity
📊 Database indexes created
INFO: Application startup complete.
INFO: 127.0.0.1:62275 - "OPTIONS /api/auth/register HTTP/1.1" 200 OK
Registration error:
INFO: 127.0.0.1:62275 - "POST /api/auth/register HTTP/1.1" 500 Internal Server Error
```

## Possible Root Causes (prioritized)

* Duplicate key error on insert (unique index on `email`) → should be handled and returned as 400.
* Missing / incorrectly loaded environment variables (e.g., `JWT_SECRET`) causing JWT encoding to fail.
* Password hashing error (wrong type passed to `bcrypt`/`passlib`).
* BSON / `ObjectId` conversion errors when creating/reading IDs.
* Unhandled exceptions from DB driver (Motor / PyMongo network or schema errors).
* Any other unhandled runtime exception in the register handler.

## Suggested Immediate Debugging Steps

1. **Enable detailed exceptions in dev**
Set FastAPI debug for local debugging:

```py
app = FastAPI(debug=True)
```

2. **Enable uvicorn debug logging** when launching:

```bash
uvicorn run:app --reload --log-level debug
```

(Or ensure `py run.py` passes `log_level="debug"` to `uvicorn.run`.)

3. **Add exception logging to the register route** to capture full traceback:

```py
import logging, traceback
logger = logging.getLogger("uvicorn.error")

try:
# handler logic...
except Exception:
logger.exception("Unhandled exception during registration")
traceback.print_exc()
raise HTTPException(status_code=500, detail="Internal Server Error")
```

4. **Test with a unique email** to rule out `DuplicateKeyError`. If failure only occurs for certain emails, inspect the unique index:

* Run `db.users.getIndexes()` in Mongo shell or check via MongoDB Compass.

5. **Verify environment variables** like `JWT_SECRET` are set and not `None`. Add an early runtime check:

```py
import os
if not os.environ.get("JWT_SECRET"):
raise RuntimeError("JWT_SECRET not set")
```

## Quick Fix Examples (to handle common errors)

* Catch duplicate key:

```py
from pymongo.errors import DuplicateKeyError

try:
await db.users.insert_one(user_doc)
except DuplicateKeyError:
raise HTTPException(status_code=400, detail="Email already registered")
```

* Ensure password hashing receives bytes and returns a string:

```py
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
user_doc['password'] = hashed.decode('utf-8')
```

* Validate `jwt.encode` uses a valid secret:

```py
import os
SECRET_KEY = os.environ.get('JWT_SECRET')
if not SECRET_KEY:
raise RuntimeError("JWT_SECRET not set")
token = jwt.encode({"user_id": user_id}, SECRET_KEY, algorithm="HS256")
```

## Acceptance Criteria (for closing this issue)

* The register endpoint returns `200/201` for valid new registrations.
* Duplicate registration returns `400` with a descriptive message.
* Any server exceptions are logged with full traceback during development.
* Add a unit/integration test covering registration success and duplicate-email case.

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

調査の方向性

The issue is in the /api/auth/register endpoint. Start by enabling debug logging in run.py or running uvicorn with --log-level debug. Examine the route handler in the auth module, likely in a file like routes/auth.py or similar. Add exception logging to capture the full traceback, then test with a unique email. Check for duplicate key errors, JWT secret configuration, and password hashing. The acceptance criteria include adding a test.

索引モデルが issue の本文から書いたものです。

評価

技術スタック
fastapi, mongodb, python
領域
api, authentication, backend
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
55/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。