activation.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.auth.services.activation
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Handlers for activating accounts in FlaskBB
  6. :copyright: (c) 2014-2018 the FlaskBB Team
  7. :license: BSD, see LICENSE for more details
  8. """
  9. from flask_babelplus import gettext as _
  10. from ...core.auth.activation import AccountActivator as _AccountActivator
  11. from ...core.exceptions import ValidationError
  12. from ...core.tokens import Token, TokenActions, TokenError
  13. from ...email import send_activation_token
  14. class AccountActivator(_AccountActivator):
  15. def __init__(self, token_serializer, users):
  16. self.token_serializer = token_serializer
  17. self.users = users
  18. def initiate_account_activation(self, email):
  19. """
  20. Looks a user up via email and sends an activation token.
  21. Will raise a
  22. :class:`ValidationError<flaskbb.core.exceptions.ValidationError>`
  23. if either the email doesn't exist in the application or the account
  24. tied to the email is already activated.
  25. """
  26. user = self.users.query.filter_by(email=email).first()
  27. if user is None:
  28. raise ValidationError('email', _("Entered email doesn't exist"))
  29. if user.activated:
  30. raise ValidationError('email', _('Account is already activated'))
  31. token = self.token_serializer.dumps(
  32. Token(user_id=user.id, operation=TokenActions.ACTIVATE_ACCOUNT)
  33. )
  34. send_activation_token.delay(
  35. token=token, username=user.username, email=user.email
  36. )
  37. def activate_account(self, token):
  38. """
  39. Activates an account based on the supplied token.
  40. Will raise
  41. :class:`TokenError<flaskbb.core.tokens.TokenError>` if the supplied
  42. token is not an account activation token and a
  43. :class:`ValidationError<flaskbb.core.exceptions.ValidationError>`
  44. if the account is already activated.
  45. Otherwise marks the account as activated.
  46. """
  47. token = self.token_serializer.loads(token)
  48. if token.operation != TokenActions.ACTIVATE_ACCOUNT:
  49. raise TokenError.invalid()
  50. user = self.users.query.get(token.user_id)
  51. if user.activated:
  52. raise ValidationError(
  53. 'activated', _('Account is already activated')
  54. )
  55. user.activated = True