Esempio n. 1
0
class Review(db.Model):
    '''Review Model'''

    __tablename__ = "reviews"

    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(250), index=False, nullable=False)
    business_id = db.Column(db.Integer,
                            db.ForeignKey('businesses.id'),
                            nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.now(), nullable=False)
    updated_at = db.Column(db.DateTime,
                           default=db.func.now(),
                           server_onupdate=db.func.now(),
                           nullable=False)

    @classmethod
    def save(cls, data):
        '''
            Save method
        '''
        review = cls(user_id=data['user_id'],
                     description=data['description'],
                     business_id=data['business_id'])
        db.session.add(review)
        db.session.commit()
        return review

    @classmethod
    def serializer(cls, datum):
        ''' Serialize model object array (Convert into a list) '''
        results = []
        for data in datum:
            obj = {
                'id': hashid(data.id),
                'user': User.query.get(data.user_id).username.capitalize(),
                'description': data.description,
                'created_at': data.created_at,
            }
            results.append(obj)
        return results

    @property
    def serialize_one(self):
        ''' Serialize model object array (Convert into a list) '''
        obj = {
            'id': hashid(self.id),
            'user': User.query.get(self.user_id).username.capitalize(),
            'description': self.description,
            'created_at': self.created_at,
        }
        return obj

    @classmethod
    def delete_all(cls, business_id):
        '''
            Delete All reviews about business
        '''
        cls.query.filter_by(business_id=business_id).delete()
Esempio n. 2
0
class Game(db.Model, Model):
    __tablename__ = 'games'

    id = db.Column(db.Integer, primary_key=True)

    start = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    end = db.Column(db.DateTime)
    finished = db.Column(db.Boolean, default=False)

    x_player_id = db.Column(
                        db.Integer, db.ForeignKey('users.id'), nullable=False)
    x_player = db.relationship(
                        'User', foreign_keys=[x_player_id], backref='x_games')

    o_player_id = db.Column(
                        db.Integer, db.ForeignKey('users.id'), nullable=False)
    o_player = db.relationship(
                        'User', foreign_keys=[o_player_id], backref='o_games')

    winner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    winner = db.relationship(
                        'User', foreign_keys=[winner_id], backref='won_games')

    @hybrid_property
    def serialized(self):
        return {'id': self.id,
                'x_player_id': self.x_player_id,
                'o_player_id': self.o_player_id,
                'start': str(self.start),
                'end': str(self.end),
                'finished': self.finished,
                'winner_id': self.winner_id}
Esempio n. 3
0
class Token(db.Model):
    '''Access tokens Model'''

    __tablename__ = "access_tokens"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    access_token = db.Column(db.String, nullable=False)
    expires_at = db.Column(
        db.DateTime, default=db.func.now(), nullable=False)
    created_at = db.Column(
        db.DateTime, default=db.func.now(), nullable=False)
    updated_at = db.Column(db.DateTime, default=db.func.now(),
                           server_onupdate=db.func.now(), nullable=False)

    @classmethod
    def save(cls, data):
        '''
            Save access token
        '''
        token = cls(
            user_id=data['user_id'],
            access_token=data['access_token'],
        )
        db.session.add(token)
        db.session.commit()

    @classmethod
    def delete(cls, token_id):
        '''
            Delete token
        '''
        token = Token.query.get(token_id)
        db.session.delete(token)
        db.session.commit()
Esempio n. 4
0
class PasswordReset(db.Model):
    '''assword reset Model class'''

    __tablename__ = "password_reset_tokens"

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    reset_token = db.Column(db.String, nullable=False)
    expires_at = db.Column(db.DateTime, default=db.func.now(), nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.now(), nullable=False)
    updated_at = db.Column(db.DateTime,
                           default=db.func.now(),
                           server_onupdate=db.func.now(),
                           nullable=False)

    @classmethod
    def save(cls, user_id, token):
        '''
            Save reset token
        '''
        reset_token = cls(user_id=user_id, reset_token=token)
        db.session.add(reset_token)
        db.session.commit()

    @classmethod
    def delete(cls, token_id):
        '''
            Delete reset token
        '''
        reset_token = cls.query.get(token_id)
        db.session.delete(reset_token)
        db.session.commit()
Esempio n. 5
0
class UserModel(db.Model):
    __tablename__ = "api_auth_user"

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), nullable=False, unique=True)
    password = db.Column(db.String, nullable=False, default='SOME_SECRET')
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    email = db.Column(db.String(255), unique=True)
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())

    creation_date = db.Column(db.DateTime, default=datetime.utcnow)
    modification_date = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    roles = db.relationship('RoleModel', secondary=api_auth_roles_users, lazy='subquery',
                             backref=db.backref('users', lazy=True))
    company_id = db.Column(db.Integer, db.ForeignKey('api_auth_company.id'))  # Each user has one company
    company = db.relationship("CompanyModel")


    @classmethod
    def find_by_username(cls, username):
        return cls.query.filter_by(username=username).first()

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

    @classmethod
    def find_all(cls):
        return cls.query.all()

    @classmethod
    def find_by_company(cls, _id):
        return cls.query.filter_by(company_id=_id).all()

    def set_password(self, pw):
        pwhash = bcrypt.generate_password_hash(pw.encode('utf8'))
        self.password = pwhash.decode('utf8')

    def check_password(self, pw):
        return bcrypt.check_password_hash(self.password, pw)

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

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

    def update(self):
        return db.session.commit()
Esempio n. 6
0
class TokenModel(db.Model, CRUDMixin):
    __tablename__ = "api_auth_token"

    id = db.Column(db.Integer, primary_key=True)
    jti = db.Column(db.String, nullable=False, unique=True)
    token_type = db.Column(db.String, nullable=False)
    fresh = db.Column(db.Boolean, nullable=False, default=False)
    blacklisted = db.Column(db.Boolean, nullable=False, default=False)
    never_expire = db.Column(db.Boolean, nullable=False, default=False)

    creation_date = db.Column(db.DateTime, default=datetime.utcnow)
    expiration_date = db.Column(db.DateTime)

    user_id = db.Column(db.Integer, db.ForeignKey(
        'api_auth_user.id'))  # Each token has one user
    user = db.relationship("UserModel")

    @classmethod
    def find_by_jti(cls, _jti):
        return cls.query.filter_by(jti=_jti).first()
Esempio n. 7
0
class Book(db.Model):
    __tablename__ = "books"

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128), nullable=False)
    yearOfPublication = db.Column(db.String(4), nullable=False)
    genre = db.Column(db.String(64), nullable=False)
    authorID = db.Column(db.Integer, db.ForeignKey("authors.id"))

    def __init__(self, title: str, yearOfPublication: str, genre: str,
                 authorID: int):
        self.title = title
        self.yearOfPublication = yearOfPublication
        self.genre = genre
        self.authorID = authorID

    def serialize(self):
        return {
            "id": self.id,
            "yearOfPublication": self.yearOfPublication,
            "genre": self.genre,
            "author": self.author.serialize()
        }
Esempio n. 8
0
class Skill(db.Model):
    __tablename__ = 'skill'
    id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), index=True)
    rating = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
Esempio n. 9
0
class Business(db.Model):
    '''Business Model'''

    __tablename__ = "businesses"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(180), index=False, nullable=False)
    description = db.Column(db.Text, index=False, nullable=False)
    country = db.Column(db.String(128), index=False, nullable=False)
    city = db.Column(db.String(128), index=False, nullable=False)
    category = db.Column(db.String(128), index=False, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=db.func.now(), nullable=False)
    updated_at = db.Column(db.DateTime,
                           default=db.func.now(),
                           server_onupdate=db.func.now(),
                           nullable=False)

    def hashid(self):
        '''
            Generate hashid
        '''
        return hashid(self.id)

    @classmethod
    def get(cls, business_id):
        '''
            Get business by hashid
        '''
        found_id = get_id(business_id)
        if found_id is not None:
            return cls.query.get(found_id)

    @classmethod
    def serializer(cls, datum):
        '''
            Serialize model object array (Convert into a list
        '''
        results = []
        for data in datum:
            obj = {
                'id':
                hashid(data.id),
                'user_id':
                hashid(data.user_id),
                'name':
                data.name,
                'description':
                data.description,
                'category':
                data.category,
                'country':
                data.country,
                'city':
                data.city,
                'reviews_count':
                Review.query.filter_by(business_id=data.id).count(),
                'created_at':
                data.created_at,
            }
            results.append(obj)
        return results

    @classmethod
    def get_by_user(cls, business_id, user_id):
        ''' Get user businesses '''
        found_business_id = get_id(business_id)
        if get_id(business_id) is not None:
            return cls.query.filter_by(user_id=user_id,
                                       id=found_business_id).first()

    @classmethod
    def serialize_obj(cls, data):
        ''' Convert model object to dictionary '''
        return {
            'id': hashid(data.id),
            'user_id': hashid(data.user_id),
            'name': data.name,
            'description': data.description,
            'category': data.category,
            'country': data.country,
            'city': data.city,
            'reviews_count':
            Review.query.filter_by(business_id=data.id).count(),
            'created_at': data.created_at,
        }

    @classmethod
    def has_two_same_business(cls, user_id, business_name, business_id):
        '''
            Check if the user has the two same busines name #nt
            from the one to update
        '''
        if cls.query.filter(cls.user_id == user_id,
                            func.lower(cls.name) == func.lower(business_name),
                            cls.id != get_id(business_id)).first() is not None:
            return True
        return False

    @classmethod
    def update(cls, business_id, data):
        ''' Update business'''
        business = cls.query.filter_by(id=get_id(business_id)).first()
        business.name = data['name']
        business.description = data['description']
        business.category = data['category']
        business.city = data['city']
        business.country = data['country']
        db.session.add(business)
        db.session.commit()

    @classmethod
    def save(cls, data):
        '''
            Save method
        '''
        business = cls(user_id=data['user_id'],
                       name=data['name'],
                       description=data['description'],
                       category=data['category'],
                       country=data['country'],
                       city=data['city'])
        db.session.add(business)
        db.session.commit()

    @classmethod
    def delete(cls, business_id):
        '''
            Delete method
        '''
        business = cls.query.get(business_id)
        db.session.delete(business)
        db.session.commit()
Esempio n. 10
0
 def company_id(cls):
     return db.Column(db.Integer, db.ForeignKey('api_auth_company.id'))
Esempio n. 11
0
from datetime import datetime

from flask import request, abort, jsonify
from flask_jwt_extended import get_jwt_claims

from sqlalchemy import event
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm.query import Query

from api.models import db, CRUDMixin
from api import bcrypt


api_auth_roles_users = db.Table(
    'api_auth_roles_users',
    db.Column('user_id', db.Integer, db.ForeignKey('api_auth_user.id'), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('api_auth_role.id'), primary_key=True),
    db.PrimaryKeyConstraint('user_id', 'role_id')
)


class CompanyQuery(Query):
    current_company_constrained = True

    def company_unconstrained_unsafe(self):
        rv = self._clone()
        rv.current_company_constrained = False
        return rv


class CompanyBoundMixin(object):