Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Building Custom Comparator for SQLAlchemy for the password property #51

Open
devraj opened this issue Oct 21, 2022 · 2 comments
Open

Building Custom Comparator for SQLAlchemy for the password property #51

devraj opened this issue Oct 21, 2022 · 2 comments
Assignees

Comments

@devraj
Copy link
Member

devraj commented Oct 21, 2022

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

@devraj devraj self-assigned this Oct 21, 2022
@devraj
Copy link
Member Author

devraj commented Apr 25, 2023

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

@devraj
Copy link
Member Author

devraj commented Apr 25, 2023

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

devraj added a commit that referenced this issue Apr 25, 2023
the commit remvoes the event that encrypted the password and uses a custom sqlalchemy
type to achieve the same result, in theory we should be able to use
on the TypeDecorator to compare values and thus achieve what we set out to

the experiments performed so far don't seem to be able to use compare_values as intended
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant