Skip to content

Building Custom Comparator for SQLAlchemy for the password property #51

Description

@devraj

Extending from the pattern that allows developers to simply set the password property and a setter hashes it on the way in. The User model class has substantial documentation on this. The general approach is to declare the property as:

_password = Column("password",
    String,
    nullable=True)

followed by exposing the password property as:

@property
def password(self):
    return self._password

and finally overriding the setter to hash the password on the way in:

@password.setter
def password(self, password):
    self._password = hash_password(password)

The Building Custom Comparator guide outlines how we can override the comparator of hybrid_property in SQLAlchemy, if we adopt this paradigm then we can achieve comparing password as:

user.password == password

as opposed using check_password method

Activity

  1. self-assigned this
    on Oct 21, 2022
  2. devraj commented on Apr 25, 2023

    @devraj
    MemberAuthor

    The effort seem to be having diminishing returns:

    • SQLAlchemy has custom comparators for hybrid methods but they are for in use with the ORM queries
    • from prestans days it's a lot more work if you wish to implement a __eq__ override on the object level and would seem to be an overkill given this will be called in very few spots
    • SQLAlchemy events on the attribute allow us to hash the password when it's set so we are sort of half way there
  3. devraj commented on Apr 25, 2023

    @devraj
    MemberAuthor

    Found this blog post which is going down the same route as what we want to. Important to note that the blog post is SQLAlchemy 1.4 but there are still valid points in there.

    Turns out that we have to look at TypeDecorator, study this and implement a solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions