Home > Enterprise >  Check token validity before confirming email address on flask and flask-login
Check token validity before confirming email address on flask and flask-login

Time:02-02

I'm trying to add this email verification process in to my flask app.

Within app/models.py I have this:

def get_confirm_account_token(self, expires_in=600):
    return jwt.encode(
        {'confirm_account': self.id, 'exp': time()   expires_in},
        current_app.config['SECRET_KEY'], algorithm='HS256')

   @staticmethod
    def verify_confirm_account_token(token):
        try:
            id = jwt.decode(token, current_app.config['SECRET_KEY'],
                            algorithms=['HS256'])['confirm_account']
        except:
            return
        return User.query.get(id)

In my route.py I call send_account_verify_email(user) after the user registers which in turn generates a token:

token = user.get_confirm_account_token()

In my route.py I then have this:

@bp.route('/confirm/<token>')
@login_required
def confirm_email(token):
    if current_user.is_confirmed:
        flash('Account already confirmed')
        return redirect(url_for('main.index'))
    if not user:
        return redirect(url_for('main.index'))
    user = User.verify_confirm_account_token(token)
    # HOW DO I CHECK TOKEN VALIDITY BEFORE SETTING CONFIRMED?
        user.is_confirmed = True
        user.confirmed_on = datetime.now()
        db.session.add(user)
        db.session.commit()
    flash('You have confirmed your account')  
    else:
        flash('The confirmation link is invalid or has expired')
    return redirect(url_for('main.index'))

The part I'm struggling with is how to check if the token the user entered is correct - i.e what is stopping them from entering any old token - before I then mark them as confirmed?

CodePudding user response:

The jwt.decode() method will raise an ExpiredSignatureError if your token is expired.

This article explains it pretty good: https://auth0.com/blog/how-to-handle-jwt-in-python/

  • Related