class AccessToken(db.Model): access_token_id = db.Column(db.Integer, primary_key=True) identity_token_id = db.Column(db.Integer, db.ForeignKey(IdentityToken.identity_token_id), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(User.user_id), nullable=False, index=True) token = db.Column(db.String(256), nullable=False, unique=True) enabled = db.Column(db.Boolean, nullable=False) client_addr = db.Column(db.String(256), nullable=False) client_timestamp = db.Column(db.DateTime, nullable=False) server_addr = db.Column(db.String(256), nullable=True) server_timestamp = db.Column(db.DateTime, nullable=True) identity_token = db.relationship(IdentityToken, backref=db.backref('access_tokens', lazy='dynamic')) user = db.relationship(User, backref=db.backref('access_tokens', lazy='dynamic')) def __init__(self, identity_token, user, token, enabled, client_addr, client_timestamp, server_addr, server_timestamp): self.identity_token = identity_token self.user = user self.token = token self.enabled = enabled self.client_addr = client_addr self.client_timestamp = client_timestamp self.server_addr = server_addr self.server_timestamp = server_timestamp @property def server_addr_str(self): known_servers = { '162.243.195.82': 'michaelfogleman.com', } return known_servers.get(self.server_addr, self.server_addr) @property def age(self): return datetime.datetime.utcnow() - self.client_timestamp def check_token(self, token, max_age): print("checking token:", token) if self.age > max_age: return False return check_password_hash(self.token, token)
class IdentityToken(db.Model): identity_token_id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey(User.user_id), nullable=False, index=True) name = db.Column(db.String(256), nullable=False) token = db.Column(db.String(256), nullable=False) enabled = db.Column(db.Boolean, nullable=False) created = db.Column(db.DateTime, nullable=False) touched = db.Column(db.DateTime, nullable=False) user = db.relationship(User, backref=db.backref('identity_tokens', lazy='dynamic')) def __init__(self, user, name, token, enabled): self.user = user self.name = name self.token = token self.enabled = enabled self.created = datetime.datetime.utcnow() self.touched = self.created def check_token(self, token): return check_password_hash(self.token, token) def touch(self): self.touched = datetime.datetime.utcnow() db.session.commit()
class User(UserMixin, db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False, unique=False) username = db.String(20) email = db.Column( db.String(40), primary_key=False, unique=False, nullable=False) password = db.Column( db.String(200), primary_key=False, unique=False, nullable=False ) posts = db.relationship("Post", backref="author") def set_password(self, password): self.password = generate_password_hash(password, method="sha256") def check_password_hash(self, password): return check_password_hash(self.password, password) def get_password(self): return self.password def __repr__(self): return "<User {}>".format(self.name)
class Stream(db.Model): """ Model for storing Stream related details. """ __tablename__ = "streams" stream_id = db.Column(db.Integer, primary_key=True, autoincrement=True) stream_name = db.Column(db.VARCHAR(60), unique=True, nullable=False) stream_desc = db.Column(db.String(255), nullable=True) date_added = db.Column(db.DateTime, nullable=False) created_by = db.Column(db.Integer, db.ForeignKey('users.id')) questions = db.relationship('Question', backref='stream', lazy='dynamic') def __init__(self, stream_name, created_by, stream_desc=""): self.stream_name = stream_name self.stream_desc = stream_desc self.created_by = created_by self.date_added = datetime.datetime.now()
class User(db.Model): """ User Model for storing user related details """ __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.VARCHAR(16), unique=True, nullable=False) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) registered_on = db.Column(db.DateTime, nullable=False) admin = db.Column(db.Boolean, nullable=False, default=False) last_login = db.Column(db.DateTime, nullable=True) streams = db.relationship('Stream', backref='user', lazy='dynamic') def as_dict(self): return {c.name: getattr(self, c.name) for c in self.__table__.columns} def __init__(self, email, username, password, admin=False): self.email = email self.username = username self.password = bcrypt.generate_password_hash( password, app.config.get('BCRYPT_LOG_ROUNDS')).decode() self.registered_on = datetime.datetime.now() self.admin = admin @staticmethod def encode_access_token(user_id): """ Generates the Access Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=5), 'iat': datetime.datetime.utcnow(), 'sub': user_id, 'type': 'access' } return jwt.encode(payload, app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e def encode_refresh_token(self, user_id): """ Generates the Refresh Token :return: string """ try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1, seconds=5), 'iat': datetime.datetime.utcnow(), 'sub': user_id, 'type': 'refresh' } return jwt.encode(payload, app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e @staticmethod def decode_token(token, type_of_token): """ Validates the access token :param auth_token: :return: integer|string """ try: payload = jwt.decode(token, app.config.get('SECRET_KEY')) if type_of_token != payload['type']: return 'Provide Valid ' + type_of_token + ' token.' if payload['type'] == 'refresh': is_blacklisted_token = BlacklistToken.check_blacklist(token) if is_blacklisted_token: return 'Blacklisted' return {'sub': payload['sub'], 'type': payload['type']} except jwt.ExpiredSignatureError: return 'Expired' except jwt.InvalidTokenError: return 'Invalid'