You want to create a FastAPI endpoint that allows access only to users with roles 'admin' or 'moderator'. Which of these dependency implementations correctly enforces this?
hard🚀 Application Q8 of 15
FastAPI - Authentication and Security
You want to create a FastAPI endpoint that allows access only to users with roles 'admin' or 'moderator'. Which of these dependency implementations correctly enforces this?
Adef role_check(user: User = Depends(get_current_user)):
if not any(role in user.roles for role in ['admin', 'moderator']):
raise HTTPException(status_code=403)
Bdef role_check(user: User = Depends(get_current_user)):
if user.roles != ['admin', 'moderator']:
raise HTTPException(status_code=403)
Cdef role_check(user: User = Depends(get_current_user)):
if 'admin' and 'moderator' not in user.roles:
raise HTTPException(status_code=403)
Ddef role_check(user: User = Depends(get_current_user)):
if 'admin' or 'moderator' in user.roles:
raise HTTPException(status_code=403)
Step-by-Step Solution
Solution:
Step 1: Understand role membership check
def role_check(user: User = Depends(get_current_user)):
if not any(role in user.roles for role in ['admin', 'moderator']):
raise HTTPException(status_code=403) uses any() to check if user has at least one required role, which is correct.
Step 2: Identify errors in other options
def role_check(user: User = Depends(get_current_user)):
if user.roles != ['admin', 'moderator']:
raise HTTPException(status_code=403) compares list equality incorrectly; C and D have wrong logical expressions.
Final Answer:
Option A correctly checks for any required role and raises exception if missing -> Option A
Quick Check:
Use any() to check multiple roles correctly [OK]
Quick Trick:Use any() to check if user has any required role [OK]
Common Mistakes:
MISTAKES
Comparing lists instead of checking membership
Incorrect logical operators in role checks
Raising exception on wrong condition
Master "Authentication and Security" in FastAPI
9 interactive learning modes - each teaches the same concept differently