Refactor crud module
This commit is contained in:
52
src/crud/authentication.py
Normal file
52
src/crud/authentication.py
Normal file
@@ -0,0 +1,52 @@
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from crud.users import get_user_by_username, pwd_context
|
||||
from models import User
|
||||
from schemas.users import UserCreate
|
||||
|
||||
DEFAULT_NR_HIGH_SCORES = 10
|
||||
|
||||
# JWT authentication setup
|
||||
jwt_secret = "secret_key"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 44640 # One month
|
||||
|
||||
|
||||
def authenticate_user(db: Session, user: UserCreate):
|
||||
"""Checks whether the provided credentials match with an existing User"""
|
||||
db_user = get_user_by_username(db=db, username=user.username)
|
||||
if not db_user:
|
||||
return False
|
||||
hashed_password = db_user.hashed_password
|
||||
if not hashed_password or not pwd_context.verify(user.password, hashed_password):
|
||||
return False
|
||||
return db_user
|
||||
|
||||
|
||||
def register(db: Session, username: str, password: str):
|
||||
"""Register a new user"""
|
||||
db_user = get_user_by_username(db, username)
|
||||
if db_user:
|
||||
raise HTTPException(status_code=400, detail="Username already registered")
|
||||
db_user = User(username=username, hashed_password=pwd_context.hash(password))
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def login(db: Session, user: UserCreate):
|
||||
user = authenticate_user(db, user)
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Invalid username or password")
|
||||
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token_payload = {
|
||||
"sub": user.username,
|
||||
"exp": datetime.utcnow() + access_token_expires,
|
||||
}
|
||||
access_token = jwt.encode(access_token_payload, jwt_secret, algorithm=ALGORITHM)
|
||||
return {"access_token": access_token}
|
||||
Reference in New Issue
Block a user