2022-04-02 19:33:15 -08:00
|
|
|
from functools import lru_cache
|
|
|
|
|
from typing import Protocol
|
|
|
|
|
|
2024-01-24 22:03:16 +00:00
|
|
|
import bcrypt
|
2022-04-02 19:33:15 -08:00
|
|
|
|
|
|
|
|
from mealie.core.config import get_app_settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Hasher(Protocol):
|
|
|
|
|
def hash(self, password: str) -> str:
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
def verify(self, password: str, hashed: str) -> bool:
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FakeHasher:
|
|
|
|
|
def hash(self, password: str) -> str:
|
|
|
|
|
return password
|
|
|
|
|
|
|
|
|
|
def verify(self, password: str, hashed: str) -> bool:
|
|
|
|
|
return password == hashed
|
|
|
|
|
|
|
|
|
|
|
2024-01-24 22:03:16 +00:00
|
|
|
class BcryptHasher:
|
2022-04-02 19:33:15 -08:00
|
|
|
def hash(self, password: str) -> str:
|
2024-01-24 22:03:16 +00:00
|
|
|
password_bytes = password.encode("utf-8")
|
|
|
|
|
hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
|
|
|
|
|
return hashed.decode("utf-8")
|
2022-04-02 19:33:15 -08:00
|
|
|
|
|
|
|
|
def verify(self, password: str, hashed: str) -> bool:
|
2024-01-24 22:03:16 +00:00
|
|
|
password_bytes = password.encode("utf-8")
|
|
|
|
|
hashed_bytes = hashed.encode("utf-8")
|
|
|
|
|
return bcrypt.checkpw(password_bytes, hashed_bytes)
|
2022-04-02 19:33:15 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
|
|
|
def get_hasher() -> Hasher:
|
|
|
|
|
settings = get_app_settings()
|
|
|
|
|
|
|
|
|
|
if settings.TESTING:
|
|
|
|
|
return FakeHasher()
|
|
|
|
|
|
2024-01-24 22:03:16 +00:00
|
|
|
return BcryptHasher()
|