63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
"""Module containing user related models."""
|
|
|
|
# vim: set tw=80 ts=4 sw=4 sts=4:
|
|
|
|
from passlib.hash import sha256_crypt as crypt
|
|
from itsdangerous import (URLSafeTimedSerializer as Serializer,
|
|
BadSignature, SignatureExpired)
|
|
|
|
from flask import current_app as app
|
|
|
|
from flask_login import UserMixin
|
|
|
|
# pylint: disable=no-member,too-few-public-methods
|
|
from . import db
|
|
|
|
|
|
class User(UserMixin, db.Model):
|
|
"""Class used to handle users."""
|
|
# pylint: disable=invalid-name
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
email = db.Column(db.String(200), nullable=False, unique=True, index=True)
|
|
password = db.Column(db.String(100), nullable=True)
|
|
active = db.Column(db.Boolean, nullable=False, default=True,
|
|
server_default=db.true())
|
|
|
|
def is_active(self):
|
|
return self.active
|
|
|
|
@classmethod
|
|
def query(cls):
|
|
"""Return a query for this class."""
|
|
return db.session.query(cls)
|
|
|
|
@classmethod
|
|
def hash_password(cls, password):
|
|
"""Password hash function."""
|
|
return crypt.encrypt(password)
|
|
|
|
def verify_password(self, password):
|
|
"""Verify password passed in argument with the user's one."""
|
|
return crypt.verify(password, self.password)
|
|
|
|
def generate_auth_token(self):
|
|
"""Generate authentication token used to identify the session."""
|
|
serializer = Serializer(app.secret_key)
|
|
|
|
return serializer.dumps({'id': self.id})
|
|
|
|
@classmethod
|
|
def verify_auth_token(cls, token):
|
|
"""Verify the authentication token and return the associated user."""
|
|
serializer = Serializer(app.config['SECRET_KEY'])
|
|
|
|
try:
|
|
data = serializer.loads(token, max_age=app.config["SESSION_TTL"])
|
|
except SignatureExpired:
|
|
return None
|
|
except BadSignature:
|
|
return None
|
|
|
|
user = cls.query().get(data['id'])
|
|
return user
|