password hashing

This commit is contained in:
hay-kot 2021-02-21 13:50:17 -09:00
commit a376699063
4 changed files with 37 additions and 3 deletions

29
mealie/core/security.py Normal file
View file

@ -0,0 +1,29 @@
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Compares a plain string to a hashed password
Args:
plain_password (str): raw password string
hashed_password (str): hashed password from the database
Returns:
bool: Returns True if a match return False
"""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""Takes in a raw password and hashes it. Used prior to saving
a new password to the database.
Args:
password (str): Password String
Returns:
str: Hashed Password
"""
return pwd_context.hash(password)

View file

@ -1,4 +1,4 @@
from app_config import SECRET
from core.config import SECRET
from db.database import db
from db.db_setup import create_session
from fastapi_login import LoginManager

View file

@ -1,3 +1,4 @@
from core.security import verify_password
from db.db_setup import generate_session
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
@ -17,9 +18,10 @@ def token(
password = data.password
user = query_user(email, session)
print(user)
if not user:
raise InvalidCredentialsException # you can also use your own HTTPException
elif password != user["password"]:
elif not verify_password(password, user["password"]):
raise InvalidCredentialsException
access_token = manager.create_access_token(data=dict(sub=email))

View file

@ -1,3 +1,4 @@
from core.security import get_password_hash
from db.database import db
from db.db_setup import generate_session
from fastapi import APIRouter, Depends
@ -16,8 +17,9 @@ async def create_user(
):
""" Returns a list of all user in the Database """
new_user.password = get_password_hash(new_user.password)
data = db.users.create(session, new_user.dict())
print(data)
return data
@ -47,6 +49,7 @@ async def update_user(
session: Session = Depends(generate_session),
):
current_user_id = current_user.get("id")
new_data.password = get_password_hash(new_data.password)
is_superuser = current_user.get("is_superuser")
if current_user_id == id or is_superuser:
return db.users.update(session, id, new_data.dict())