Update code in endpoints\auth.get.py

This commit is contained in:
Backend IM Bot 2025-03-21 13:58:56 +01:00
parent e6919197d0
commit 4d5bfaaf06

View File

@ -1,24 +1,40 @@
Here's a simple implementation of a GET /auth endpoint in FastAPI that authenticates a user:
```python
from fastapi import APIRouter, HTTPException
users = [] # In-memory storage
users = [
{"username": "demo", "password": "password"}
]
router = APIRouter()
@router.get("/auth")
async def authenticate_user():
"""authenticates the user"""
return {
"method": "GET",
async def authenticate(
username: str = "demo",
password: str = "password"
):
"""Authenticate user"""
if request.method != "GET":
raise HTTPException(status_code=405, detail={
"message": "Method Not Allowed",
"method": request.method,
"_verb": "get"
})
user = next((u for u in users if u["username"] == username), None)
if not user or user["password"] != password:
raise HTTPException(status_code=400, detail="Invalid credentials")
return {
"message": "Authentication successful",
"method": "GET",
"_verb": "get",
"user": username,
"token": "dummy_jwt_token_123"
}
@router.get("/auth", status_code=405)
async def method_not_allowed():
raise HTTPException(status_code=405, detail="Method Not Allowed")
@router.get("/auth/{invalid_param}", status_code=400)
async def bad_request(invalid_param):
raise HTTPException(status_code=400, detail="Bad Request")
```
This code follows the provided guidelines and implements a GET endpoint at `/auth` that authenticates the user. It includes the required response format with the `method` and `_verb` fields. It also handles incorrect HTTP methods by raising a 405 Method Not Allowed exception and invalid GET parameters by raising a 400 Bad Request exception.
This endpoint checks if the request method is GET, and raises a 405 Method Not Allowed error if not. It then looks for a user with the provided username and password in the in-memory `users` list. If a matching user is found, it returns a successful authentication response with a dummy JWT token. Otherwise, it raises a 400 Bad Request error for invalid credentials.
The response includes the request method, a `_verb` field indicating the HTTP verb, the authenticated username, and a dummy JWT token.