diff --git a/mealie/core/security.py b/mealie/core/security.py new file mode 100644 index 000000000..f6cc9a805 --- /dev/null +++ b/mealie/core/security.py @@ -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) diff --git a/mealie/routes/deps.py b/mealie/routes/deps.py index eda883299..09b580af4 100644 --- a/mealie/routes/deps.py +++ b/mealie/routes/deps.py @@ -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 diff --git a/mealie/routes/users/auth.py b/mealie/routes/users/auth.py index a849d9e23..2d6c06ae1 100644 --- a/mealie/routes/users/auth.py +++ b/mealie/routes/users/auth.py @@ -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)) diff --git a/mealie/routes/users/crud.py b/mealie/routes/users/crud.py index 6ed4e9e6c..909a6626c 100644 --- a/mealie/routes/users/crud.py +++ b/mealie/routes/users/crud.py @@ -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())