From 4a3827f7c072b50a84c5656c2cb56cea8fcf589b Mon Sep 17 00:00:00 2001 From: Valentin CZERYBA Date: Wed, 11 Oct 2023 23:45:12 +0200 Subject: [PATCH] add dependencies --- app/dependencies.py | 74 +++++++++++++++++++++++++++++++++++++++++++ app/main.py | 1 + app/models/users.py | 13 ++++---- app/routers/events.py | 0 app/routers/users.py | 10 ++++++ 5 files changed, 91 insertions(+), 7 deletions(-) create mode 100644 app/dependencies.py create mode 100644 app/routers/events.py diff --git a/app/dependencies.py b/app/dependencies.py new file mode 100644 index 0000000..c34a1f7 --- /dev/null +++ b/app/dependencies.py @@ -0,0 +1,74 @@ +from datetime import datetime, timedelta +from typing import Annotated + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import JWTError, jwt +from passlib.context import CryptContext + + +fake_users = [ + # password foo + {'id': 1, 'username': 'admin', 'password': '$2b$12$N.i74Kle18n5Toxhas.rVOjZreVC2WM34fCidNDyhSNgxVlbKwX7i', + 'permissions': ['items:read', 'items:write', 'users:read', 'users:write'] + }, + # password bar + {'id': 2, 'username': 'client', 'password': '$2b$12$KUgpw1m0LF/s9NS1ZB5rRO2cA5D13MqRm56ab7ik2ixftXW/aqEyq', + 'permissions': ['items:read']} +] + +SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +def verify_password(plain_password, hashed_password): + return pwd_context.verify(plain_password, hashed_password) + +def get_password_hash(password): + return pwd_context.hash(password) + +def get_user(db, username: str): + for user in db: + if username == user.username: + return UserInDB(**user) + +def authenticate_user(fake_db, username: str, password: str): + user = get_user(fake_db, username) + if not user: + return False + if not verify_password(password, user.password): + return False + return user + +def create_access_token(data: dict, expires_delta: timedelta | None = None): + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=15) + to_encode.update({"exp": expire}) + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + return encoded_jwt + +async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + username: str = payload.get("sub") + if username is None: + raise credentials_exception + token_data = TokenData(username=username) + except JWTError: + raise credentials_exception + user = get_user(fake_users, username=token_data.username) + if user is None: + raise credentials_exception + return user diff --git a/app/main.py b/app/main.py index 5dfe2c7..a50b2c5 100644 --- a/app/main.py +++ b/app/main.py @@ -2,6 +2,7 @@ from fastapi import FastAPI from .routers import users + app = FastAPI() app.include_router(users.router) diff --git a/app/models/users.py b/app/models/users.py index b3da0b6..e1b9b4d 100644 --- a/app/models/users.py +++ b/app/models/users.py @@ -1,12 +1,11 @@ from pydantic import BaseModel -from pydantic_mongo import AbstractRepository, ObjectIdField -class Users(BaseModel): - id: ObjectIdField = None +class User(BaseModel): + id: int username: str + password: str + permissions: list[str] = [] - -class UsersRepository(AbstractRepository[Users]): - class Meta: - collection_name = users \ No newline at end of file +class UserInDB(User): + password: str \ No newline at end of file diff --git a/app/routers/events.py b/app/routers/events.py new file mode 100644 index 0000000..e69de29 diff --git a/app/routers/users.py b/app/routers/users.py index e3352a8..2dabaa1 100644 --- a/app/routers/users.py +++ b/app/routers/users.py @@ -1,5 +1,15 @@ from fastapi import APIRouter +fake_users = [ + # password foo + {'id': 1, 'username': 'admin', 'password': '$2b$12$N.i74Kle18n5Toxhas.rVOjZreVC2WM34fCidNDyhSNgxVlbKwX7i', + 'permissions': ['items:read', 'items:write', 'users:read', 'users:write'] + }, + # password bar + {'id': 2, 'username': 'client', 'password': '$2b$12$KUgpw1m0LF/s9NS1ZB5rRO2cA5D13MqRm56ab7ik2ixftXW/aqEyq', + 'permissions': ['items:read']} +] + router = APIRouter() @router.get("/users/", tags=["users"])