Untitled
unknown
plain_text
a year ago
2.9 kB
4
Indexable
import json
import os
from fastapi import Depends, HTTPException, Request
from sqlalchemy import func
from src.database import SessionLocal, dbutils
from src.database.models.User import UserModel
from src.dependables.auth_verify import verify_user
from fastapi.security import APIKeyHeader
# Following function is used to verify the admin token during accessing the upgrade endpoints
api_key_header = APIKeyHeader(name="x-token", auto_error=False)
async def verify_admin_token(api_key: str = Depends(api_key_header)):
if api_key != os.environ.get('MIDDLEWARE_SESSION_KEY'):
raise HTTPException(status_code=401, detail="Invalid Admin Token")
def db(request: Request):
db = SessionLocal()
request.state.db = db
try:
yield db
finally:
db.close()
def auth(request: Request, token_headers=Depends(verify_user), db=Depends(db)):
# if os.environ.get("MODE") != "production":
# token_headers = '{ "user": "ppandya" }'
# following line checks if mode is development and sets the flag accordingly
# This was used in past to check if user is admin or not for development only for any user to be admin when login
# request.state.is_admin = os.environ.get("MODE") == "development"
if token_headers is not None:
login: str = json.loads(token_headers).get("user")
user = (
UserModel.query(db)
.filter(func.lower(UserModel.user_id) == login.lower())
.first()
)
# print("User is: ", user)
if user is None:
raise HTTPException(status_code=403, detail="You are not authorized to use Performance Ecosystem.")
request.state.auth_original = user
# Following checks if the user is admin or not and sets the flag accordingly
request.state.is_true_admin = user is not None and user.role == "admin"
if user is not None and (user.role == "admin" or user.role == "powerUser"):
request.state.is_admin = True
# NOTE: This is used when user selects different account to view
# and front end pass the admin credentials as header with the new userid
admin_headers = request.headers.get("Admin-Credentials")
if admin_headers is not None:
token_headers = admin_headers
# NOTE: This is TBD to check use
if token_headers is not None:
login: str = json.loads(token_headers).get("user")
user = (
UserModel.query(db)
.filter(func.lower(UserModel.user_id) == login.lower())
.first()
)
request.state.auth = user
return user
raise HTTPException(status_code=401, detail="You are not authenticated.")
def maintenance(db=Depends(db)):
if dbutils.is_db_locked(db):
raise HTTPException(status_code=503)Editor is loading...
Leave a Comment