from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user_role(token: str = Depends(oauth2_scheme)):
# Simulate decoding token to get role
if token == "admin-token":
return "admin"
elif token == "user-token":
return "user"
else:
raise HTTPException(status_code=401, detail="Invalid token")
async def role_checker(required_role: str):
async def checker(role: str = Depends(get_current_user_role)):
if role != required_role:
raise HTTPException(status_code=403, detail="Access forbidden")
return checker
@app.get("/admin")
async def admin_endpoint(dep=Depends(role_checker("admin"))):
return {"message": "Welcome admin!"}This code checks the user's role from a token and only allows access to the /admin endpoint if the role is 'admin'.