| 1 |
from datetime import datetime, timedelta, timezone |
| 2 |
|
| 3 |
import jwt |
| 4 |
from fastapi import Depends, FastAPI, HTTPException, Security, status |
| 5 |
from fastapi.security import ( |
| 6 |
OAuth2PasswordBearer, |
| 7 |
OAuth2PasswordRequestForm, |
| 8 |
SecurityScopes, |
| 9 |
) |
| 10 |
from jwt.exceptions import InvalidTokenError |
| 11 |
from pwdlib import PasswordHash |
| 12 |
from pydantic import BaseModel, ValidationError |
| 13 |
|
| 14 |
# to get a string like this run: |
| 15 |
# openssl rand -hex 32 |
| 16 |
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" |
| 17 |
ALGORITHM = "HS256" |
| 18 |
ACCESS_TOKEN_EXPIRE_MINUTES = 30 |
| 19 |
|
| 20 |
|
| 21 |
fake_users_db = { |
| 22 |
"johndoe": { |
| 23 |
"username": "johndoe", |
| 24 |
"full_name": "John Doe", |
| 25 |
"email": "[email protected]", |
| 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": "[email protected]", |
| 33 |
"hashed_password": "$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE", |
| 34 |
"disabled": True, |
| 35 |
}, |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
class Token(BaseModel): |
| 40 |
access_token: str |
| 41 |
token_type: str |
| 42 |
|
| 43 |
|
| 44 |
class TokenData(BaseModel): |
| 45 |
username: str | None = None |
| 46 |
scopes: list[str] = [] |
| 47 |
|
| 48 |
|
| 49 |
class User(BaseModel): |
| 50 |
username: str |
| 51 |
email: str | None = None |
| 52 |
full_name: str | None = None |
| 53 |
disabled: bool | None = None |
| 54 |
|
| 55 |
|
| 56 |
class UserInDB(User): |
| 57 |
hashed_password: str |
| 58 |
|
| 59 |
|
| 60 |
password_hash = PasswordHash.recommended() |
| 61 |
|
| 62 |
DUMMY_HASH = password_hash.hash("dummypassword") |
| 63 |
|
| 64 |
oauth2_scheme = OAuth2PasswordBearer( |
| 65 |
tokenUrl="token", |
| 66 |
scopes={"me": "Read information about the current user.", "items": "Read items."}, |
| 67 |
) |
| 68 |
|
| 69 |
app = FastAPI() |
| 70 |
|
| 71 |
|
| 72 |
def verify_password(plain_password, hashed_password): |
| 73 |
return password_hash.verify(plain_password, hashed_password) |
| 74 |
|
| 75 |
|
| 76 |
def get_password_hash(password): |
| 77 |
return password_hash.hash(password) |
| 78 |
|
| 79 |
|
| 80 |
def get_user(db, username: str): |
| 81 |
if username in db: |
| 82 |
user_dict = db[username] |
| 83 |
return UserInDB(**user_dict) |
| 84 |
|
| 85 |
|
| 86 |
def 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 False |
| 91 |
if not verify_password(password, user.hashed_password): |
| 92 |
return False |
| 93 |
return user |
| 94 |
|
| 95 |
|
| 96 |
def 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_delta |
| 100 |
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_jwt |
| 105 |
|
| 106 |
|
| 107 |
async 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_exception |
| 124 |
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_exception |
| 129 |
user = get_user(fake_users_db, username=token_data.username) |
| 130 |
if user is None: |
| 131 |
raise credentials_exception |
| 132 |
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 user |
| 140 |
|
| 141 |
|
| 142 |
async 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_user |
| 148 |
|
| 149 |
|
| 150 |
@app.post("/token") |
| 151 |
async 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") |
| 163 |
|
| 164 |
|
| 165 |
@app.get("/users/me/") |
| 166 |
async def read_users_me(current_user: User = Depends(get_current_active_user)) -> User: |
| 167 |
return current_user |
| 168 |
|
| 169 |
|
| 170 |
@app.get("/users/me/items/") |
| 171 |
async 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}] |
| 175 |
|
| 176 |
|
| 177 |
@app.get("/status/") |
| 178 |
async def read_system_status(current_user: User = Depends(get_current_user)): |
| 179 |
return {"status": "ok"} |