From c424a6cd8a32aa948130f267acab34b8e5491f1a Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Thu, 18 Jul 2024 10:27:31 -0500 Subject: [PATCH] fix: add `check_user_password()` method for auth handler --- src/wuttjamaican/auth.py | 31 +++++++++++++++++++++---------- tests/test_auth.py | 11 +++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/wuttjamaican/auth.py b/src/wuttjamaican/auth.py index c005f94..d9300ed 100644 --- a/src/wuttjamaican/auth.py +++ b/src/wuttjamaican/auth.py @@ -84,19 +84,30 @@ class AuthHandler(GenericHandler): :returns: :class:`~wuttjamaican.db.model.auth.User` instance, or ``None``. """ - model = self.app.model - - if isinstance(username, model.User): - user = username - else: - user = session.query(model.User)\ - .filter_by(username=username)\ - .first() - + user = self.get_user(username, session=session) if user and user.active and user.password: - if password_context.verify(password, user.password): + if self.check_user_password(user, password): return user + def check_user_password(self, user, password, **kwargs): + """ + Check a user's password. + + This will hash the given password and compare it to the hashed + password we have on file for the given user account. + + This is normally part of the login process, so the + ``password`` param refers to the password entered by a user; + this method will determine if it was correct. + + :param user: :class:`~wuttjamaican.db.model.auth.User` instance. + + :param password: User-entered password in plain text. + + :returns: ``True`` if password matches; else ``False``. + """ + return password_context.verify(password, user.password) + def get_role(self, session, key, **kwargs): """ Locate and return a :class:`~wuttjamaican.db.model.auth.Role` diff --git a/tests/test_auth.py b/tests/test_auth.py index b5b5f76..e8d5e15 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -60,6 +60,17 @@ else: user = self.handler.authenticate_user(self.session, 'barney', 'goodpass') self.assertIsNone(user) + def test_check_user_password(self): + model = self.app.model + barney = model.User(username='barney') + self.handler.set_user_password(barney, 'goodpass') + self.session.add(barney) + self.session.commit() + + # basics + self.assertTrue(self.handler.check_user_password(barney, 'goodpass')) + self.assertFalse(self.handler.check_user_password(barney, 'BADPASS')) + def test_get_role(self): model = self.app.model myrole = model.Role(name="My Role")