get token fonctionnel
This commit is contained in:
parent
08758aa12f
commit
e8d2670024
@ -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)
|
||||
|
@ -6,6 +6,7 @@ class User(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
roles: str
|
||||
disabled: bool
|
||||
|
||||
class UserInDB(User):
|
||||
password: str
|
@ -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}]
|
||||
return current_user
|
Loading…
x
Reference in New Issue
Block a user