Improve readability of password management

This commit is contained in:
coolneng 2021-01-04 21:09:00 +01:00
parent e2f17743b7
commit 6c7a561fef
Signed by: coolneng
GPG Key ID: 9893DA236405AF57
1 changed files with 15 additions and 6 deletions

View File

@ -8,8 +8,6 @@ from constants import SHA1_SALT
from database import SessionLocal
from database.models import *
pwd_context = CryptContext(schemes=["bcrypt", "hex_sha1"], deprecated=["hex_sha1"])
def get_db():
db = SessionLocal()
@ -49,7 +47,7 @@ def fetch_user_by_email(data, db):
def create_user(data, db):
data.password = pwd_context.hash(secret=data.password)
data.password = create_password_hash(secret=data.password)
user = insert_data(model="Users", data=data, db=db)
return user
@ -61,8 +59,14 @@ def update_otp(data, db):
db.commit()
def create_password_hash(secret):
pwd_context = CryptContext(schemes=["bcrypt", "hex_sha1"], deprecated=["hex_sha1"])
password_hash = pwd_context.hash(secret=secret)
return password_hash
def update_password_hash(user, password, db):
new_hash = pwd_context.hash(secret=password)
new_hash = create_password_hash(secret=password)
db.query(Users).filter(Users.email == user.email).update({Users.password: new_hash})
db.commit()
db.refresh(user)
@ -82,9 +86,14 @@ def construct_secret(db_hash, password):
return password, legacy_hash
def verify_password_hash(secret, hash):
pwd_context = CryptContext(schemes=["bcrypt", "hex_sha1"], deprecated=["hex_sha1"])
return pwd_context.verify(secret=secret, hash=hash)
def verify_password(user, password, db):
secret, legacy_hash = construct_secret(db_hash=user.password, password=password)
correct_password = pwd_context.verify(secret=secret, hash=user.password)
correct_password = verify_password_hash(secret=secret, hash=user.password)
if correct_password:
if legacy_hash:
update_password_hash(user=user, password=password, db=db)
@ -159,4 +168,4 @@ def verify_password_reset(data, db):
unset_forgot_password(user=user, db=db)
return user
else:
raise HTTPException(status_code=400, detail="The OTP is not correct")
raise HTTPException(status_code=400, detail="An error has ocurred")