@@ -70,18 +70,18 @@ def verify_token(token):
7070class TokenAuthBackend (AuthenticationBackend ):
7171 async def authenticate (self , conn ):
7272 if "authorization" not in conn .headers :
73- return
73+ return None
7474
7575 auth = conn .headers ["authorization" ]
7676 try :
7777 scheme , credentials = auth .split ()
7878 if scheme .lower () != "token" :
79- return
79+ return None
8080 try :
8181 decoded_token = base64 .b64decode (credentials ).decode ("ascii" )
8282 except UnicodeDecodeError :
8383 logger .debug ("Unable to decode token" )
84- return False
84+ return None
8585 except (ValueError , UnicodeDecodeError , binascii .Error ):
8686 raise AuthenticationError ("Invalid auth credentials" )
8787
@@ -90,7 +90,7 @@ async def authenticate(self, conn):
9090 )
9191 if not valid_token :
9292 logger .debug ("Token not valid." )
93- return
93+ return None
9494 tm .authenticated_user_id = user_id
9595 return AuthCredentials (["authenticated" ]), SimpleUser (user_id )
9696
@@ -251,7 +251,6 @@ async def login_required(
251251 raise AuthenticationError ("Invalid auth credentials" )
252252 valid_token , user_id = AuthenticationService .is_valid_token (decoded_token , 604800 )
253253 if not valid_token :
254- logger .debug ("Token not valid" )
255254 raise HTTPException (
256255 status_code = status .HTTP_401_UNAUTHORIZED ,
257256 detail = {"Error" : "Token is expired or invalid" , "SubCode" : "InvalidToken" },
@@ -275,12 +274,18 @@ async def login_required_optional(
275274 decoded_token = base64 .b64decode (credentials ).decode ("ascii" )
276275 except UnicodeDecodeError :
277276 logger .debug ("Unable to decode token" )
278- raise HTTPException (status_code = 401 , detail = "Invalid token" )
277+ raise HTTPException (
278+ status_code = status .HTTP_401_UNAUTHORIZED ,
279+ detail = {
280+ "Error" : "Token is expired or invalid" ,
281+ "SubCode" : "InvalidToken" ,
282+ },
283+ headers = {"WWW-Authenticate" : "Bearer" },
284+ )
279285 except (ValueError , UnicodeDecodeError , binascii .Error ):
280286 raise AuthenticationError ("Invalid auth credentials" )
281287 valid_token , user_id = AuthenticationService .is_valid_token (decoded_token , 604800 )
282288 if not valid_token :
283- logger .debug ("Token not valid" )
284289 return None
285290 return AuthUserDTO (id = user_id )
286291
0 commit comments