Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ethanholda/dc69549baac431af2cdf555465568634 to your computer and use it in GitHub Desktop.
Save ethanholda/dc69549baac431af2cdf555465568634 to your computer and use it in GitHub Desktop.
pre_save on user model
@classmethod
@pre_save
def handle_user_save(cls, sender, document, **kwargs):
# Don't save user if Roles are not defined
if Roles.objects(name__in=['authenticated', 'admin']).count() != 2:
message = "Missing required base roles"
raise ValidationError(message)
if not document.is_new() and \
not (getattr(document, 'confirm_password', None) and getattr(document, 'password')):
document.password = sender.objects.get(id=document.id).password
# This means it's an update and the password has not changed
# Otherwise it would have been trapped in the front-end validation
return
if hasattr(document, 'confirm_password'):
if document.confirm_password != document.password:
raise ValidationError("Password confirmation does not match")
if document.is_new():
# Only encrypt if new! Otherwise flask-security will handle this part
if document.password:
document.password = encrypt_password(document.password)
else:
if 'password' in getattr(document, '_changed_fields', []):
if getattr(document, 'password', None) and getattr(document, 'confirm_password', None):
# If the password is coming from a password-reset request,
# then the password is already encrypted, so don't re-encrypt!
already_encrypted = [x for x in app.url_map._rules_by_endpoint.items()
if ('forgot_password' in x[0] or 'reset_password' in x[0]) and
request.path.startswith(str(x[1][0].rule))]
if not already_encrypted:
document.password = encrypt_password(document.password)
if hasattr(document, 'confirm_password'):
delattr(document, 'confirm_password')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment