From a35d16f9a191afbb31e2c185e87e5eec5e23122f Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Wed, 8 Mar 2023 11:42:04 +0300 Subject: auth: users: Use the same basic functions for password hashing To avoid repeating the same thing in multiple places, leading to errors and breakages, reuse the same basic functions for password hashing. --- gn3/auth/authentication/users.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'gn3/auth') diff --git a/gn3/auth/authentication/users.py b/gn3/auth/authentication/users.py index 5ee148f..17e89ae 100644 --- a/gn3/auth/authentication/users.py +++ b/gn3/auth/authentication/users.py @@ -61,9 +61,8 @@ def valid_login(conn: db.DbConnection, user: User, password: str) -> bool: if row is None: return False - hasher = PasswordHasher() # TODO: Maybe tune the parameters here... try: - return hasher.verify(row["password"], password) + return hasher().verify(row["password"], password) except VerifyMismatchError as _vme: return False @@ -81,11 +80,27 @@ def save_user(cursor: db.DbCursor, email: str, name: str) -> User: (str(user_id), email, name)) return User(user_id, email, name) +def hasher(): + """Retrieve PasswordHasher object""" + # TODO: Maybe tune the parameters here... + # Tuneable Parameters: + # - time_cost (default: 2) + # - memory_cost (default: 102400) + # - parallelism (default: 8) + # - hash_len (default: 16) + # - salt_len (default: 16) + # - encoding (default: 'utf-8') + # - type (default: ) + return PasswordHasher() + +def hash_password(password): + """Hash the password.""" + return hasher().hash(password) + def set_user_password( cursor: db.DbCursor, user: User, password: str) -> Tuple[User, bytes]: """Set the given user's password in the database.""" - hasher = PasswordHasher() # TODO: Maybe tune the parameters here... - hashed_password = hasher.hash(password) + hashed_password = hash_password(password) cursor.execute( ("INSERT INTO user_credentials VALUES (:user_id, :hash) " "ON CONFLICT (user_id) DO UPDATE SET password=:hash"), -- cgit v1.2.3