from datetime import datetime, timedelta from app import db class Token(db.Model): __tablename__ = 'tokens' # Primary key id = db.Column(db.Integer, primary_key=True) # Foreign keys user_id = db.Column(db.Integer, db.ForeignKey('users.id')) # Fields access_token = db.Column(db.String(64), index=True) access_expiration = db.Column(db.DateTime) refresh_token = db.Column(db.String(64), index=True) refresh_expiration = db.Column(db.DateTime) # Relationships user = db.relationship('User', back_populates='tokens') def expire(self): self.access_expiration = datetime.utcnow() self.refresh_expiration = datetime.utcnow() def to_json_serializeable(self, backrefs=False, relationships=False): json_serializeable = { 'id': self.hashid, 'access_token': self.access_token, 'access_expiration': ( None if self.access_expiration is None else f'{self.access_expiration.isoformat()}Z' ), 'refresh_token': self.refresh_token, 'refresh_expiration': ( None if self.refresh_expiration is None else f'{self.refresh_expiration.isoformat()}Z' ) } if backrefs: json_serializeable['user'] = \ self.user.to_json_serializeable(backrefs=True) if relationships: pass return json_serializeable @staticmethod def clean(): """Remove any tokens that have been expired for more than a day.""" yesterday = datetime.utcnow() - timedelta(days=1) Token.query.filter(Token.refresh_expiration < yesterday).delete()