docs_src/security/tutorial005_py310.py PYTHON 180 lines View on github.com → Search inside
1from datetime import datetime, timedelta, timezone23import jwt4from fastapi import Depends, FastAPI, HTTPException, Security, status5from fastapi.security import (6    OAuth2PasswordBearer,7    OAuth2PasswordRequestForm,8    SecurityScopes,9)10from jwt.exceptions import InvalidTokenError11from pwdlib import PasswordHash12from pydantic import BaseModel, ValidationError1314# to get a string like this run:15# openssl rand -hex 3216SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"17ALGORITHM = "HS256"18ACCESS_TOKEN_EXPIRE_MINUTES = 30192021fake_users_db = {22    "johndoe": {23        "username": "johndoe",24        "full_name": "John Doe",25        "email": "johndoe@example.com",26        "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc",27        "disabled": False,28    },29    "alice": {30        "username": "alice",31        "full_name": "Alice Chains",32        "email": "alicechains@example.com",33        "hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE",34        "disabled": True,35    },36}373839class Token(BaseModel):40    access_token: str41    token_type: str424344class TokenData(BaseModel):45    username: str | None = None46    scopes: list[str] = []474849class User(BaseModel):50    username: str51    email: str | None = None52    full_name: str | None = None53    disabled: bool | None = None545556class UserInDB(User):57    hashed_password: str585960password_hash = PasswordHash.recommended()6162DUMMY_HASH = password_hash.hash("dummypassword")6364oauth2_scheme = OAuth2PasswordBearer(65    tokenUrl="token",66    scopes={"me": "Read information about the current user.", "items": "Read items."},67)6869app = FastAPI()707172def verify_password(plain_password, hashed_password):73    return password_hash.verify(plain_password, hashed_password)747576def get_password_hash(password):77    return password_hash.hash(password)787980def get_user(db, username: str):81    if username in db:82        user_dict = db[username]83        return UserInDB(**user_dict)848586def authenticate_user(fake_db, username: str, password: str):87    user = get_user(fake_db, username)88    if not user:89        verify_password(password, DUMMY_HASH)90        return False91    if not verify_password(password, user.hashed_password):92        return False93    return user949596def create_access_token(data: dict, expires_delta: timedelta | None = None):97    to_encode = data.copy()98    if expires_delta:99        expire = datetime.now(timezone.utc) + expires_delta100    else:101        expire = datetime.now(timezone.utc) + timedelta(minutes=15)102    to_encode.update({"exp": expire})103    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)104    return encoded_jwt105106107async def get_current_user(108    security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)109):110    if security_scopes.scopes:111        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'112    else:113        authenticate_value = "Bearer"114    credentials_exception = HTTPException(115        status_code=status.HTTP_401_UNAUTHORIZED,116        detail="Could not validate credentials",117        headers={"WWW-Authenticate": authenticate_value},118    )119    try:120        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])121        username: str = payload.get("sub")122        if username is None:123            raise credentials_exception124        scope: str = payload.get("scope", "")125        token_scopes = scope.split(" ")126        token_data = TokenData(scopes=token_scopes, username=username)127    except (InvalidTokenError, ValidationError):128        raise credentials_exception129    user = get_user(fake_users_db, username=token_data.username)130    if user is None:131        raise credentials_exception132    for scope in security_scopes.scopes:133        if scope not in token_data.scopes:134            raise HTTPException(135                status_code=status.HTTP_401_UNAUTHORIZED,136                detail="Not enough permissions",137                headers={"WWW-Authenticate": authenticate_value},138            )139    return user140141142async def get_current_active_user(143    current_user: User = Security(get_current_user, scopes=["me"]),144):145    if current_user.disabled:146        raise HTTPException(status_code=400, detail="Inactive user")147    return current_user148149150@app.post("/token")151async def login_for_access_token(152    form_data: OAuth2PasswordRequestForm = Depends(),153) -> Token:154    user = authenticate_user(fake_users_db, form_data.username, form_data.password)155    if not user:156        raise HTTPException(status_code=400, detail="Incorrect username or password")157    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)158    access_token = create_access_token(159        data={"sub": user.username, "scope": " ".join(form_data.scopes)},160        expires_delta=access_token_expires,161    )162    return Token(access_token=access_token, token_type="bearer")163164165@app.get("/users/me/")166async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User:167    return current_user168169170@app.get("/users/me/items/")171async def read_own_items(172    current_user: User = Security(get_current_active_user, scopes=["items"]),173):174    return [{"item_id": "Foo", "owner": current_user.username}]175176177@app.get("/status/")178async def read_system_status(current_user: User = Depends(get_current_user)):179    return {"status": "ok"}

Code quality findings 11

Ensure functions have docstrings for documentation
info maintainability missing-docstring
def verify_password(plain_password, hashed_password):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_password_hash(password):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def get_user(db, username: str):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def authenticate_user(fake_db, username: str, password: str):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def create_access_token(data: dict, expires_delta: timedelta | None = None):
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def get_current_user(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def get_current_active_user(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def login_for_access_token(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User:
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def read_own_items(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
async def read_system_status(current_user: User = Depends(get_current_user)):

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings