forked from open-webui/open-webui
refac: use dependencies to verify token
- feat: added new util to get the current user when needed. Middleware was adding authentication logic to all the routes. let's revisit if we can move the non-auth endpoints to a separate route. - refac: update the routes to use new helpers for verification and retrieving user - chore: added black for local formatting of py code
This commit is contained in:
parent
a01b112f7f
commit
bdd153d8f5
10 changed files with 167 additions and 251 deletions
|
@ -1,7 +1,9 @@
|
|||
from fastapi.security import HTTPBasicCredentials, HTTPBearer
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from fastapi import HTTPException, status, Depends
|
||||
from apps.web.models.users import Users
|
||||
from pydantic import BaseModel
|
||||
from typing import Union, Optional
|
||||
|
||||
from constants import ERROR_MESSAGES
|
||||
from passlib.context import CryptContext
|
||||
from datetime import datetime, timedelta
|
||||
import requests
|
||||
|
@ -53,16 +55,23 @@ def extract_token_from_auth_header(auth_header: str):
|
|||
return auth_header[len("Bearer ") :]
|
||||
|
||||
|
||||
def verify_token(request):
|
||||
try:
|
||||
authorization = request.headers["authorization"]
|
||||
if authorization:
|
||||
_, token = authorization.split()
|
||||
decoded_token = jwt.decode(
|
||||
token, JWT_SECRET_KEY, options={"verify_signature": False}
|
||||
def verify_auth_token(auth_token: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
|
||||
data = decode_token(auth_token.credentials)
|
||||
if data != None and "email" in data:
|
||||
user = Users.get_user_by_email(data["email"])
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=ERROR_MESSAGES.INVALID_TOKEN,
|
||||
)
|
||||
return decoded_token
|
||||
else:
|
||||
return None
|
||||
except Exception as e:
|
||||
return None
|
||||
return
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail=ERROR_MESSAGES.UNAUTHORIZED,
|
||||
)
|
||||
|
||||
|
||||
def get_current_user(auth_token: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
|
||||
data = decode_token(auth_token.credentials)
|
||||
return Users.get_user_by_email(data["email"])
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue