reauthentication.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.auth.services.reauthentication
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Tools for handling reauthentication needs inside FlaskBB.
  6. :copyright: (c) 2014-2018 the FlaskBB Team
  7. :license: BSD, see LICENSE for more details
  8. """
  9. import logging
  10. from flask_babelplus import gettext as _
  11. from werkzeug.security import check_password_hash
  12. from ...core.auth.authentication import (PostReauthenticateHandler,
  13. ReauthenticateFailureHandler,
  14. ReauthenticateManager,
  15. ReauthenticateProvider,
  16. StopAuthentication)
  17. from ...utils.helpers import time_utcnow
  18. logger = logging.getLogger(__name__)
  19. class DefaultFlaskBBReauthProvider(ReauthenticateProvider):
  20. def reauthenticate(self, user, secret):
  21. if check_password_hash(user.password, secret): # pragma: no branch
  22. return True
  23. class ClearFailedLoginsOnReauth(PostReauthenticateHandler):
  24. def handle_post_reauth(self, user):
  25. user.login_attempts = 0
  26. class MarkFailedReauth(ReauthenticateFailureHandler):
  27. def handle_reauth_failure(self, user):
  28. user.login_attempts += 1
  29. user.last_failed_login = time_utcnow()
  30. class PluginReauthenticationManager(ReauthenticateManager):
  31. def __init__(self, plugin_manager, session):
  32. self.plugin_manager = plugin_manager
  33. self.session = session
  34. def reauthenticate(self, user, secret):
  35. try:
  36. result = self.plugin_manager.hook.flaskbb_reauth_attempt(
  37. user=user, secret=secret
  38. )
  39. if not result:
  40. raise StopAuthentication(_("Wrong password."))
  41. self.plugin_manager.hook.flaskbb_post_reauth(user=user)
  42. except StopAuthentication as e:
  43. self.plugin_manager.hook.flaskbb_reauth_failed(user=user)
  44. raise
  45. finally:
  46. try:
  47. self.session.commit()
  48. except Exception:
  49. logger.exception("Exception while processing login")
  50. self.session.rollback()
  51. raise