Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Last active November 14, 2021 01:42
Show Gist options
  • Save kissgyorgy/6723fd4d879464fab4ef to your computer and use it in GitHub Desktop.
Save kissgyorgy/6723fd4d879464fab4ef to your computer and use it in GitHub Desktop.
Python: Password descriptor
class Password(str):
def __eq__(self, other):
if not isinstance(other, self.__class__):
other = bcrypt.hashpw(other, self)
return str.__eq__(self, other)
def __ne__(self, other):
return not self.__eq__(other)
def __get__(self, obj, type=None):
# that's pretty sick :D
return self.__class__(obj._password_hash)
def __set__(self, obj, plain):
# Hash a password for the first time, with a randomly-generated salt
# gensalt's log_rounds parameter determines the complexity.
# The work factor is 2**log_rounds, and the default is 12
obj._password_hash = bcrypt.hashpw(plain, bcrypt.gensalt())
def __delete__(self, obj):
del obj._password_hash
import mongoengine as me
class User(me.Document):
email = me.StringField(required=True)
password = Password()
_password_hash = me.StringField()
>>> user = User(email='[email protected]')
>>> user.password = 'example'
>>> user.password == 'example'
True
>>> user.password == 'Something else'
False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment