Exemple #1
0
class User(db.Model):
    """This class represents the user table"""

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32))
    email = db.Column(db.String(68))
    password_hash = db.Column(db.String(255))
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=datetime.now(kenyan_time),
                              onupdate=datetime.now(kenyan_time))
    bucketlists = db.relationship('Bucketlist',
                                  backref='user',
                                  cascade="all,delete")

    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password_hash = self.hash_password(password)

    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=3600):
        s = Serializer(Config.SECRET, expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(Config.SECRET)
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user

    def save(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def get_all():
        return User.query.all()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def __repr__(self):
        return "<User: {}>".format(self.name)
class User(db.Model):
    """This class represents the user table."""

    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True)
    email = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(128))
    bucketlist = db.relationship('Bucketlist', backref='user', lazy='dynamic')

    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = self.set_password(password)

    def set_password(self, password):
        """Hash the password."""
        pw_hash = generate_password_hash(password)
        return pw_hash

    def generate_auth_token(self, id):
        """Generate the Auth Token."""
        try:
            payload = {
                'expiration_date':
                datetime.datetime.utcnow() +
                datetime.timedelta(days=0, minutes=10),
                'time_token_is_generated':
                datetime.datetime.utcnow(),
                'user':
                id
            }
            return jwt.encode(payload,
                              app.config.get(os.getenv('SECRET')),
                              algorithm='HS256')
        except Exception as e:
            return e

    @staticmethod
    def verify_signature(auth_token):
        """Decode the auth token and verify the signature."""
        try:
            payload = jwt.decode(auth_token, os.getenv('SECRET'))
            return payload['user']
        except jwt.ExpiredSignatureError:
            return 'Signature Expired. Try log in again'
        except jwt.InvalidTokenError:
            return 'Invalid Token. Try log in again'
Exemple #3
0
class Bucketlist(db.Model):
    """This class represents the bucketlist table."""

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())
    created_by = db.Column(db.Integer, db.ForeignKey('user.id'))
    items = db.relationship('Item', backref='bucketlist', cascade="all,delete")

    def __init__(self, name, created_by):
        """initialize with name."""
        self.name = name
        self.created_by = created_by

    def save(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def get_all():
        return Bucketlist.query.all()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def __repr__(self):
        return "{}".format(self.name)
Exemple #4
0
class BucketListItems(db.Model):
    """This class represents the items in the bucketlists"""

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
    date_modified = db.Column(db.DateTime,
                              default=db.func.current_timestamp(),
                              onupdate=db.func.current_timestamp())
    achieved = db.Column(db.Boolean, default=False)
    bucketlist_id = db.Column(db.Integer, db.ForeignKey('bucketlist.id'))

    def __init__(self, name, achieved, bucketlist_id):
        self.name = name
        self.achieved = achieved
        self.bucketlist_id = bucketlist_id

    def save(self):
        db.session.add(self)
        db.session.commit()

    @staticmethod
    def get_all():
        return BucketListItems.query.all()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def __repr__(self):
        return "<Bucketlist Item: {}>".format(self.name)
class Bucketlist(db.Model):
    """This class represents the bucketlist table."""

    __tablename__ = 'bucketlists'

    id = db.Column(db.Integer, primary_key=True)
    bucketlist_title = db.Column(db.String(100))
    date_created = db.Column(db.DateTime, default=datetime.now)
    date_modified = db.Column(db.DateTime,
                              default=datetime.now,
                              onupdate=datetime.now)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    created_by = db.relationship('User',
                                 backref=db.backref('user', lazy='dynamic'))
    items = db.relationship('Item',
                            backref=db.backref('bucketlists'),
                            cascade="all, delete-orphan")

    def __repr__(self):
        """Return printable representation of the object."""
        return "Bucketlist: %d" % self.bucketlist_title

    def save(self):
        """Save a bucketlist."""
        db.session.add(self)
        db.session.commit()

    def delete(self):
        """Delete a bucketlist."""
        db.session.delete(self)
        db.session.commit()
class Users(db.Model):
    """
    Users Model
    """
    __tablename__ = 'users'

    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(250), nullable=False)
    password_hash = db.Column(db.String(64), nullable=False)
    email = db.Column(db.String(250), nullable=False, unique=True)

    def hash_password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_auth_token(self, expiration=36000):
        """Expires in 36 minutes"""
        S = Serializer('SECRET_KEY', expires_in=expiration)
        return S.dumps({'user_id': self.user_id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer('SECRET_KEY')
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        user = Users.query.get(data['user_id'])
        return user

    def __repr__(self):
        return "<Users: %r>" % self.username
class Item(db.Model):
    """This class represents the items table."""

    __tablename__ = 'items'
    id = db.Column(db.Integer, primary_key=True)
    item_name = db.Column(db.String(100))
    description = db.Column(db.Text)
    is_completed = db.Column(db.Boolean, default=False)
    created_date = db.Column(db.DateTime, default=datetime.now)
    modified_date = db.Column(db.DateTime,
                              default=datetime.now,
                              onupdate=datetime.now)
    bucketlist_id = db.Column(db.Integer, db.ForeignKey('bucketlists.id'))

    def __repr__(self):
        """Return printable representation of the object."""
        return "Item: %d" % self.item_name
class BucketList(db.Model):
    """Bucketlist model"""
    __tablename__ = 'bucketlist'

    list_id = db.Column(db.Integer, primary_key=True)
    list_title = db.Column(db.String(255))
    list_description = db.Column(db.Text)
    date_created = db.Column(db.DateTime, default=datetime.now)
    date_modified = db.Column(db.DateTime,
                              default=datetime.now,
                              onupdate=datetime.now)
    # This Value is constrained to be  the one of the remote column which is user.id (PK)
    created_by = db.Column(db.Integer, db.ForeignKey("users.user_id"))
    items = db.relationship("BucketlistItem", backref=db.backref("bucketlist"))
    users = db.relationship("Users",
                            backref=db.backref("users", lazy="dynamic"))

    def __repr__(self):
        return "<BucketList: %r>" % self.list_title
class BucketlistItem(db.Model):
    """
    BucketlistItem model
    """
    __tablename__ = 'items'

    item_id = db.Column(db.Integer, primary_key=True)
    item_title = db.Column(db.String(255))
    item_description = db.Column(db.Text)
    done = db.Column(db.Boolean(), default=False)
    date_created = db.Column(db.DateTime, default=datetime.now)
    date_modified = db.Column(db.DateTime,
                              default=datetime.now,
                              onupdate=datetime.now)
    created_by = db.Column(db.Integer, db.ForeignKey("users.user_id"))
    user = db.relationship("Users",
                           backref=db.backref("items", lazy="dynamic"))
    bucketlist_id = db.Column(db.Integer, db.ForeignKey("bucketlist.list_id"))

    def __repr__(self):
        return "<BucketListItem: %r>" % self.item_title