From 4ae5c52de95e70f3301dac73c18055dce7f86864 Mon Sep 17 00:00:00 2001 From: Michael Genson <71845777+michael-genson@users.noreply.github.com> Date: Wed, 24 Jan 2024 22:03:16 +0000 Subject: [PATCH] refactor to use bcrypt directly --- mealie/core/security/hasher.py | 17 +++++++++-------- tests/unit_tests/core/test_security.py | 4 ++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/mealie/core/security/hasher.py b/mealie/core/security/hasher.py index aed59bf47ec8..638a36a463e4 100644 --- a/mealie/core/security/hasher.py +++ b/mealie/core/security/hasher.py @@ -1,7 +1,7 @@ from functools import lru_cache from typing import Protocol -from passlib.context import CryptContext +import bcrypt from mealie.core.config import get_app_settings @@ -22,15 +22,16 @@ class FakeHasher: return password == hashed -class PasslibHasher: - def __init__(self) -> None: - self.ctx = CryptContext(schemes=["bcrypt"], deprecated="auto") - +class BcryptHasher: def hash(self, password: str) -> str: - return self.ctx.hash(password) + password_bytes = password.encode("utf-8") + hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt()) + return hashed.decode("utf-8") def verify(self, password: str, hashed: str) -> bool: - return self.ctx.verify(password, hashed) + password_bytes = password.encode("utf-8") + hashed_bytes = hashed.encode("utf-8") + return bcrypt.checkpw(password_bytes, hashed_bytes) @lru_cache(maxsize=1) @@ -40,4 +41,4 @@ def get_hasher() -> Hasher: if settings.TESTING: return FakeHasher() - return PasslibHasher() + return BcryptHasher() diff --git a/tests/unit_tests/core/test_security.py b/tests/unit_tests/core/test_security.py index 688157cab7b6..911e8f36998c 100644 --- a/tests/unit_tests/core/test_security.py +++ b/tests/unit_tests/core/test_security.py @@ -1,7 +1,7 @@ from pytest import MonkeyPatch from mealie.core.config import get_app_settings -from mealie.core.security.hasher import FakeHasher, PasslibHasher, get_hasher +from mealie.core.security.hasher import BcryptHasher, FakeHasher, get_hasher def test_get_hasher(monkeypatch: MonkeyPatch): @@ -16,7 +16,7 @@ def test_get_hasher(monkeypatch: MonkeyPatch): hasher = get_hasher() - assert isinstance(hasher, PasslibHasher) + assert isinstance(hasher, BcryptHasher) get_app_settings.cache_clear() get_hasher.cache_clear()