Skip to content

Instantly share code, notes, and snippets.

@valdergallo
Created April 26, 2018 20:05
Show Gist options
  • Save valdergallo/56e079cb0ff968894958c688f53e3703 to your computer and use it in GitHub Desktop.
Save valdergallo/56e079cb0ff968894958c688f53e3703 to your computer and use it in GitHub Desktop.
BaseAuth using passlib with itsdangerous lib in python to be used as mixin in User model
# -*- coding: utf-8 -*-
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
SECRET_KEY = 'top-secret'
class AuthUser(object):
def __init__(self, id=None, *args, **kwargs):
self.id = id
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
def generate_auth_token(self, expiration=600):
s = Serializer(SECRET_KEY, expires_in=expiration)
return s.dumps({'id': self.id})
@staticmethod
def parse_auth_token(token):
serializer = Serializer(SECRET_KEY)
try:
data = serializer.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment