From 4d5bfaaf06ceb5e22385d660591a9eb4adbcc6cc Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Fri, 21 Mar 2025 13:58:56 +0100 Subject: [PATCH] Update code in endpoints\auth.get.py --- endpoints/auth.get.py | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/endpoints/auth.get.py b/endpoints/auth.get.py index 8f957e2..44443ae 100644 --- a/endpoints/auth.get.py +++ b/endpoints/auth.get.py @@ -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""" +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" + "_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. \ No newline at end of file +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. \ No newline at end of file