Merge pull request 'login' (#1) from login into master

Reviewed-on: #1
This commit is contained in:
v4l3n71n 2023-10-12 21:57:26 +00:00
commit 95cfa7ff57
14 changed files with 184 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

0
app/__init__.py Normal file
View File

View File

View File

@ -0,0 +1,18 @@
from ..dependencies import users_active
from fastapi import Depends, HTTPException, status
from ..models import users
class PermissionChecker:
def __init__(self, roles: list[str]) -> None:
self.roles = roles
def __call__(self, user: users.User = Depends(users_active.get_current_active_user)) -> bool:
for role in self.roles:
if role == user.roles:
return True
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Roles unauthorized'
)

View File

@ -0,0 +1,83 @@
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
from ..models import users, token
fake_users = [
# password foo
{'id': 1, 'username': 'admin', 'password': '$2b$12$N.i74Kle18n5Toxhas.rVOjZreVC2WM34fCidNDyhSNgxVlbKwX7i',
'roles': 'Admin', 'disabled': False
},
# password bar
{'id': 2, 'username': 'client', 'password': '$2b$12$KUgpw1m0LF/s9NS1ZB5rRO2cA5D13MqRm56ab7ik2ixftXW/aqEyq',
'roles':'User', 'disabled':False}
]
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 users.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_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_str, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = token.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
async def get_current_active_user(
current_user: Annotated[users.User, Depends(get_current_user)]
):
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user

13
app/main.py Normal file
View File

@ -0,0 +1,13 @@
from fastapi import FastAPI
from .routers import users, token
app = FastAPI()
app.include_router(users.router)
app.include_router(token.router)
@app.get("/")
async def root():
return {"message": "Hello World !"}

0
app/models/__init__.py Normal file
View File

9
app/models/token.py Normal file
View File

@ -0,0 +1,9 @@
from pydantic import BaseModel
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: str | None = None

12
app/models/users.py Normal file
View File

@ -0,0 +1,12 @@
from pydantic import BaseModel
class User(BaseModel):
id: int
username: str
password: str
roles: str
disabled: bool
class UserInDB(User):
password: str

0
app/routers/__init__.py Normal file
View File

0
app/routers/events.py Normal file
View File

27
app/routers/token.py Normal file
View File

@ -0,0 +1,27 @@
from datetime import datetime, timedelta
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status, APIRouter
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from ..dependencies import users_active
from ..models import token
router = APIRouter()
@router.post("/token", response_model=token.Token, tags=["token"])
async def login_for_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
user = users_active.authenticate_user(users_active.fake_users, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=users_active.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = users_active.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}

15
app/routers/users.py Normal file
View File

@ -0,0 +1,15 @@
from fastapi import APIRouter, Depends
from ..dependencies import users_active, permissions_checker
from ..models import users
from typing import Annotated
router = APIRouter()
@router.get("/users/", tags=["users"], response_model=list[users.User])
async def read_users(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]):
return users_active.fake_users
@router.get("/users/me",tags=["users"], response_model=users.User)
async def read_users_me(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]):
return current_user

6
requierements.txt Normal file
View File

@ -0,0 +1,6 @@
fastapi
uvicorn[standard]
pydantic-mongo
python-jose[cryptography]
passlib[bcrypt]
python-multipart