From e8d2670024947c2ab90a893ab2d296a50347dcc0 Mon Sep 17 00:00:00 2001 From: Valentin CZERYBA Date: Thu, 12 Oct 2023 23:15:26 +0200 Subject: [PATCH] get token fonctionnel --- app/dependencies.py | 12 ++++++------ app/models/users.py | 1 + app/routers/users.py | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/app/dependencies.py b/app/dependencies.py index 1b7328a..5692bb6 100644 --- a/app/dependencies.py +++ b/app/dependencies.py @@ -6,17 +6,17 @@ from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from passlib.context import CryptContext -from .models import users +from .models import users, token fake_users = [ # password foo {'id': 1, 'username': 'admin', 'password': '$2b$12$N.i74Kle18n5Toxhas.rVOjZreVC2WM34fCidNDyhSNgxVlbKwX7i', - 'roles': 'Admin' + 'roles': 'Admin', 'disabled': False }, # password bar {'id': 2, 'username': 'client', 'password': '$2b$12$KUgpw1m0LF/s9NS1ZB5rRO2cA5D13MqRm56ab7ik2ixftXW/aqEyq', - 'roles':'User'} + 'roles':'User', 'disabled':False} ] SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" @@ -56,18 +56,18 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None): encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt -async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): +async def get_current_user(token_str: 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]) + payload = jwt.decode(token_str, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception - token_data = TokenData(username=username) + token_data = token.TokenData(username=username) except JWTError: raise credentials_exception user = get_user(fake_users, username=token_data.username) diff --git a/app/models/users.py b/app/models/users.py index 1888557..de11fcd 100644 --- a/app/models/users.py +++ b/app/models/users.py @@ -6,6 +6,7 @@ class User(BaseModel): username: str password: str roles: str + disabled: bool class UserInDB(User): password: str \ No newline at end of file diff --git a/app/routers/users.py b/app/routers/users.py index c6a7e31..3dc18db 100644 --- a/app/routers/users.py +++ b/app/routers/users.py @@ -12,4 +12,4 @@ async def read_users(): @router.get("/users/me", response_model=users.User) async def read_users_me(current_user: Annotated[users.User, Depends(get_current_active_user)]): - return [{"item_id": "Foo", "owner": current_user.username}] \ No newline at end of file + return current_user \ No newline at end of file