From 6992565adb3c9baf7cf1fc08ba15691ffcca88ca Mon Sep 17 00:00:00 2001 From: Chats Date: Tue, 30 Apr 2024 12:48:14 -0400 Subject: [PATCH] implement authentication middleware as middleware --- src/utils/middleware/authentication.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/utils/middleware/authentication.py b/src/utils/middleware/authentication.py index 6b13157..783e5d6 100644 --- a/src/utils/middleware/authentication.py +++ b/src/utils/middleware/authentication.py @@ -1,11 +1,35 @@ import bcrypt +from fastapi import status +from fastapi.requests import Request +from fastapi.responses import JSONResponse + from src.cfg.settings import security TOKEN = security["token"] hashed = bcrypt.hashpw(bytes(TOKEN, "utf-8"), bcrypt.gensalt()) +async def authenticate(request: Request, call_next): + authenticated_prefixes = "admin" + response = None + headers = dict(request.scope["headers"]) + if ( + authenticated_prefixes in request.url.path + and "authorization" in request.headers + ): + if verify_password(request.headers["Authorization"]): + response = await call_next(request) + else: + response = JSONResponse( + status_code=status.HTTP_401_UNAUTHORIZED, + content={"error": "Unauthorized"}, + ) + else: + response = await call_next(request) + return response + + def verify_length(token): length = len(token) if length <= 7 or length >= 25: