diff --git a/monkey/monkey_island/cc/environment/user_creds.py b/monkey/monkey_island/cc/environment/user_creds.py index dbd7b7422..498511675 100644 --- a/monkey/monkey_island/cc/environment/user_creds.py +++ b/monkey/monkey_island/cc/environment/user_creds.py @@ -27,6 +27,12 @@ class UserCreds: def to_auth_user(self) -> User: return User(1, self.username, self.password_hash) + @classmethod + def from_cleartext(cls, username, cleartext_password): + password_hash = bcrypt.hashpw(cleartext_password.encode("utf-8"), bcrypt.gensalt()).decode() + + return cls(username, password_hash) + @staticmethod def get_from_new_registration_dict(data_dict: Dict) -> UserCreds: creds = UserCreds() diff --git a/monkey/tests/monkey_island/cc/environment/test_user_creds.py b/monkey/tests/monkey_island/cc/environment/test_user_creds.py index f295f245a..359bc3741 100644 --- a/monkey/tests/monkey_island/cc/environment/test_user_creds.py +++ b/monkey/tests/monkey_island/cc/environment/test_user_creds.py @@ -1,5 +1,9 @@ +import bcrypt + from monkey_island.cc.environment.user_creds import UserCreds +TEST_SALT = b"$2b$12$JA7GdT1iyfIsquF2cTZv2." + def test_to_dict_empty_creds(): user_creds = UserCreds() @@ -25,3 +29,10 @@ def test_to_auth_user_username_only(): assert auth_user.id == 1 assert auth_user.username == "Test" assert auth_user.secret == "" + + +def test_get_from_cleartext(monkeypatch): + monkeypatch.setattr(bcrypt, "gensalt", lambda: TEST_SALT) + + creds = UserCreds.from_cleartext("Test", "Test_Password") + assert creds.password_hash == "$2b$12$JA7GdT1iyfIsquF2cTZv2.NdGFuYbX1WGfQAOyHlpEsgDTNGZ0TXG"