Skip to content

Commit

Permalink
update security file
Browse files Browse the repository at this point in the history
  • Loading branch information
Lopkop committed Mar 14, 2024
1 parent b663f70 commit 5c4afb8
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions backend/security.py → backend/auth/security.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
from datetime import datetime

from passlib.context import CryptContext
from jose import JWTError, jwt
from config import settings

from config import settings
from db.dbapi import DatabaseService
from auth.exceptions import LoginFailed, UserExpired

db = DatabaseService()

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ALGORITHM = "HS256"


def authenticate_user(session, name: str, password: str):
user = db.fetch_user_by_name(session, name)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
if not (user and verify_password(password, user.hashed_password)):
raise LoginFailed("Either username or password is incorrect")
return user


def token_expired_check(session, username):
user = db.fetch_user_by_name(session, username)
access_token = db.fetch_token_by_username(session, username)
if (access_token.expires_at - datetime.now()).total_seconds() < 0:
db.remove_user(session, user)
raise UserExpired("Token has expired")


def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)

Expand All @@ -28,11 +36,10 @@ def hash_password(password):


def create_access_token(data: dict):
encoded_jwt = jwt.encode(data, settings.SECRET_KEY, algorithm=ALGORITHM)
encoded_jwt = jwt.encode(data, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt


def decode_access_token(token: str):
decoded = jwt.decode(token, key=settings.SECRET_KEY, algorithms=ALGORITHM)
print(decoded)
decoded = jwt.decode(token, key=settings.SECRET_KEY, algorithms=settings.ALGORITHM)
return decoded

0 comments on commit 5c4afb8

Please sign in to comment.