Authenticating users
We can now look at how to authenticate users. This is a very simple process:
- Retrieve the user we want to authenticate from the database.
- Perform a
bcrypt.checkpw
giving it the attempted password and the password hash of the user. - Raise an exception if the result is
False
. - Return the user if it's
True
.
Retrieving users from the database
Starting with the first point, we will need to add a new dependency method, get
, which returns the user, given the email, if it exists.
First, add a new exception class in users.py
:
class UserNotFound(Exception): pass
This is what we will raise in the event of the user not being found. Now we will update our imports to include the following:
from sqlalchemy.orm.exc import NoResultFound
NoResultFound
, as the name implies, is raised by SQLAlchemy when a requested object is not found in the database. Now we can add a new method to our UserWrapper
class:
def get(self, email): query = self.session.query(User) # â‘ try: user...