Bird
0
0

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:
  1. 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.
  2. 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.
  3. Final Answer:

    Option A correctly checks for any required role and raises exception if missing -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes