Created
April 26, 2018 20:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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