Authenticating a user's password

We will now implement an authenticate method that will use the get method we just created.

First, let's create a new exception class that will be raised if there is a password mismatch:

class AuthenticationError(Exception): 
    pass 

We can now create another method for our UserWrapper to authenticate users:

def authenticate(self, email, password): 
    user = self.get(email) # ① 
 
    if not bcrypt.checkpw(password.encode(), user.password): # ② 
        message = 'Incorrect password for {}'.format(email) 
        raise AuthenticationError(message) # ③ 
  1. We start by using our recently created get method to retrieve the user we want to authenticate from our database.
  2. We then use bcrypt.checkpw to check that the attempted password matches the ...

Get Python Programming Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.