149189 / 149189/Singularity

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

未关闭
#1 0 条评论 0 个 reaction 已指派 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 摘要。