Exemple #1
0
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User {}>'.format(self.username)
Exemple #2
0
class User(db.Model):
    # CREATE TABLE user (
    #   id INTEGER PRIMARY KEY AUTOINCREMENT,
    #   username TEXT UNIQUE NOT NULL,
    #   password TEXT NOT NULL
    # );
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(256), unique=True)
    password = db.Column(db.String(256), nullable=False)
    posts = db.relationship('Post', backref='user', lazy=True)
Exemple #3
0
class UserModel(db.Model):
    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    full_names = db.Column(db.String(80), nullable=False)

    email = db.Column(db.String(255), unique=True, nullable=False, index=True)
    password = db.Column(db.String(124), nullable=False, server_default="")
    posts = db.relationship("PostModel", lazy="dynamic")

    @classmethod
    def find_user_by_id(cls, _id: int) -> "UserModel":
        return cls.query.filter_by(id=_id).first()

    @classmethod
    def encrypt_password(cls, plaintext_password):
        """
        Hash a plaintext string using PBKDF2. This is good enough according
        to the NIST (National Institute of Standards and Technology).

        In other words while bcrypt might be superior in practice, if you use
        PBKDF2 properly (which we are), then your passwords are safe.

        :param plaintext_password: Password in plain text
        :type plaintext_password: str
        :return: str
        """
        if plaintext_password:
            return generate_password_hash(plaintext_password)

        return None

    @classmethod
    def find_user_by_email(cls, email: str) -> "UserModel":
        return cls.query.filter_by(email=email).first()

    @classmethod
    def authenticated(cls, old_password: str, new_password: str):
        """
        Ensure a user is authenticated, and check their password.

        :param with_password: Optionally check their password
        :type with_password: bool
        :type password: str
        :return: bool
        """
        return check_password_hash(old_password, new_password)

    def save_to_db(self) -> None:
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self) -> None:
        db.session.delete(self)
        db.session.commit()
class User(db.Model):

    __tablename__ = 'user'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    user_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    user_password = db.Column(db.String(120), nullable=False)
    user_sign = db.Column(db.Integer, nullable=False)

    def __init__(self, username, userpassward, user_sign):
        self.username = username
        self.user_password = userpassward
        self.user_sign = user_sign
Exemple #5
0
class Post(db.Model):
    # CREATE TABLE post (
    #   id INTEGER PRIMARY KEY AUTOINCREMENT,
    #   author_id INTEGER NOT NULL,
    #   created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    #   title TEXT NOT NULL,
    #   body TEXT NOT NULL,
    #   FOREIGN KEY (author_id) REFERENCES user (id)
    # );
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    created = db.Column(db.DateTime(), default=datetime.utcnow)
    title = db.Column(db.String(256), nullable=False)
    body = db.Column(db.String(256), nullable=False)
Exemple #6
0
class ImageModel(db.Model):

    __tablename__ = 'image'
    id = db.Column(db.Integer, primary_key=True)
    # TODO decide on proper length for giphy alpha-numeric ids
    external_id = db.Column(db.String(80))

    def __init__(self, external_id):
        self.external_id = external_id

    def json(self):
        return {"id": self.id, "external_id": self.external_id}

    @classmethod
    def find_by_external_id(cls, external_id):
        return cls.query.filter_by(external_id=external_id).first()

    def save_to_db(self):
        """ replaces insert and update"""
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Exemple #7
0
class CategoryModel(db.Model):

    __tablename__ = 'category'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

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

    def json(self):
        return {"id": self.id, "name": self.name}

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()

    def save_to_db(self):
        """ replaces insert and update"""
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
class Theme(db.Model):

    __tablename__ = 'theme'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    theme_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer, nullable=False)
    theme_created = db.Column(db.DateTime, default=datetime.datetime.now())
    theme_text = db.Column(db.String(50), unique=True, nullable=False)

    def __init__(self, author_id, theme_text):
        self.author_id = author_id
        self.theme_text = theme_text 
class Reply(db.Model):
    __tablename__ = 'reply'
    __table_args = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    reply_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer, nullable=False)
    post_id = db.Column(db.Integer, nullable=False)
    reply_created = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
    reply_text = db.Column(db.String(200), nullable=False)

    def __init__(self, author_id, post_id, reply_text):
        self.author_id = author_id
        self.post_id = post_id
        self.reply_text = reply_text
class Post(db.Model):

    __tablename__ = 'post'
    __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
    post_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer)
   
    post_created = db.Column(db.DateTime, default=datetime.datetime.now())
    theme_id = db.Column(db.Integer, nullable=False)
    post_title = db.Column(db.String(128), nullable=False)
    post_body = db.Column(db.Text, nullable=False)

    def __init__(self, author_id, theme_id, post_title, post_body):
        self.author_id = author_id
        self.theme_id = theme_id
        self.post_title = post_title
        self.post_body = post_body
Exemple #11
0
class UserModel(db.Model):

    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    external_id = db.Column(db.String(80))

    # liked images relationship
    likes = db.relationship('ImageModel',
                            secondary=user_image,
                            backref=db.backref('likes', lazy='dynamic'))

    # image category relationship
    # categories = db.relationship('CategoryModel', backref='owner')

    def __init__(self, external_id):
        self.external_id = external_id

    def __str__(self):
        """ readable representation of the user model"""
        return self.external_id

    @classmethod
    def find_by_external_id(cls, external_id):
        return cls.query.filter_by(external_id=external_id).first()

    @classmethod
    def find_by_id(cls, _id):
        return cls.query.filter_by(id=_id).first()

    def save_to_db(self):
        """ replaces insert and update"""
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Exemple #12
0
class User(db.Model):
    """Represents blog user database table."""

    id_ = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(120), unique=False, nullable=False)
    first_name = db.Column(db.String(80),
                           unique=False,
                           nullable=False,
                           default='')
    last_name = db.Column(db.String(80),
                          unique=False,
                          nullable=False,
                          default='')
    api_token = db.Column(db.String(32), unique=True, index=True)
    api_token_expiration = db.Column(db.DateTime)
    posts = db.relationship('Post', backref='author', lazy=True)

    def __repr__(self):
        return '<User(username={}, first_name={}, last_name={})>'.format(
            self.username,
            self.first_name,
            self.last_name,
        )

    def set_password(self, password):
        """Generate password hash and update `password_hash` field.

        :param str password: not hashed user's password.
        """
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        """Check that given password's hash matches with one stored in database.

        :param str password: not hashed user's password.
        :return: True if passwords matches, False otherwise.
        """
        return check_password_hash(self.password_hash, password)

    def get_api_token(self, expires_in_sec=3600):
        """
        Set user's token if it doesn't exist or expired, and return it.

        :param int expires_in_sec: a period of time in seconds when the
        token is valid.
        :return: API token string.
        """
        now = datetime.utcnow()
        if self.api_token and self.api_token_expiration > now + timedelta(
                seconds=60):
            return self.api_token
        self.api_token = base64.b64encode(os.urandom(24)).decode('utf-8')
        self.api_token_expiration = now + timedelta(seconds=expires_in_sec)
        db.session.add(self)
        return self.api_token

    def revoke_api_token(self):
        """Make the token be expired."""
        self.api_token_expiration = datetime.utcnow() - timedelta(seconds=1)

    @staticmethod
    def check_api_token(token):
        """
        Check if API token exists or expired.
        
        :param str token: REST API token.
        :return: `User` object the `token` belongs to if such exists
        and not expired, `None` otherwise.
        """
        user = User.query.filter_by(api_token=token).first()
        if user is None or user.api_token_expiration < datetime.utcnow():
            return None
        return user

    def to_dict(self):
        """Convert `User` object to dictionary."""
        user_dict = {
            'id': self.id_,
            'username': self.username,
            'first_name': self.first_name,
            'last_name': self.last_name,
            'post_count': len(self.posts),
        }
        return user_dict

    def from_dict(self, user_dict, new_user=False):
        """
        Populate `User` object with values from dictionary `user_dict`.
        If `new_user` is True, set password as well.

        :param dict user_dict: dictionary containing user attributes.
        :param bool new_user: we don't have `password` field in `User`
        class, but if we create a user, we should set a password.
        """

        for field in ('username', 'first_name', 'last_name'):
            if field in user_dict:
                setattr(self, field, user_dict[field])
        if new_user and 'password' in user_dict:
            self.set_password(user_dict['password'])

    @staticmethod
    def to_collection_dict():
        """
        Create a dictionary of User's dictionaries.

        :return: a dictionary with `User` class attributes.
        """
        users = [user.to_dict() for user in User.query.all()]
        users_collection = {
            'users': users,
            'count': len(users),
        }
        return users_collection
Exemple #13
0
class Post(db.Model):
    """Represents user's blog posts database table."""

    id_ = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer,
                          db.ForeignKey('user.id_'),
                          nullable=False)
    created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    title = db.Column(db.String(80), nullable=False)
    body = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return '<Post(id={}, author_id={}, created={}, title={})>'.format(
            self.id_,
            self.author_id,
            self.created,
            self.title,
        )

    def to_dict(self):
        """
        Convert `Post` object into dictionary.

        :return: a dictionary with `Post` class attributes as dictionary and some
        `User` fields under `author` key.
        """
        author = db.session.query(
            User.username,
            User.first_name,
            User.last_name,
        ).filter(self.author_id == User.id_).first()

        post_dict = {
            'id': self.id_,
            'author_id': self.author_id,
            'author': dict(zip(('username', 'first_name', 'last_name'),
                               author)),
            'created': str(self.created),
            'title': self.title,
            'body': self.body,
        }
        return post_dict

    @staticmethod
    def to_collection_dict():
        """
        Create a dictionary of Post's dictionaries.

        :return: a dictionary with `Post` class attributes as dictionary.
        """
        posts = [post.to_dict() for post in Post.query.all()]
        posts_collection = {
            'posts': posts,
            'count': len(posts),
        }
        return posts_collection

    def from_dict(self, post_dict):
        """
        Populate `Post` object with values from dictionary `post_dict`.

        :param dict post_dict: a dictionary of `Post` class attributes.
        """
        for field in ('authod_id', 'created', 'title', 'body'):
            if field in post_dict:
                setattr(self, field, post_dict[field])