Ejemplo n.º 1
0
class UserModel(db.Model):
    __tablename__ = 'users'

    user_id = db.Column(db.Integer, primary_key=True)
    login = db.Column(db.String(40))
    password = db.Column(db.String(40))

    def __init__(self, login, password):
        self.login = login
        self.password = password

    def json(self):
        return {'user_id': self.user_id, 'login': self.login}

    @classmethod
    def find_user(cls, user_id):
        user = cls.query.filter_by(user_id=user_id).first()
        if user:
            return user
        return None

    @classmethod
    def find_by_login(cls, login):
        user = cls.query.filter_by(login=login).first()
        if user:
            return user
        return None

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

    def delete_user(self):
        db.session.delete(self)
        db.session.commit()
Ejemplo n.º 2
0
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    name = db.Column(db.String(86), nullable=False)
    email = db.Column(db.String(84), nullable=False, unique=True)
    password = db.Column(db.String(128), nullable=False)

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

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

    def __repr__(self):
        return f"< User : {self.email}>"
Ejemplo n.º 3
0
class Tasks(db.Model):
    __tablename__ = 'tasks'
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    descricao = db.Column(db.String(128), nullable=False)
    doneAt = db.Column(db.String(84), nullable=True)
    estimateAt = db.Column(db.String(84), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    user = db.relationship("User", foreign_keys=user_id)

    def __init__(self, descricao, doneAt, estimateAt, user_id):
        self.descricao = descricao
        self.doneAt = doneAt
        self.estimateAt = estimateAt
        self.user_id = user_id

    def __repr__(self):
        return f"< demanda : {self.descricao}>"
Ejemplo n.º 4
0
class Restaurant(db.Model):
    __tablename__ = 'restaurants'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    category = db.Column(db.String(255), nullable=False)
    deliveryEstimate = db.Column(db.String(20))
    rating = db.Column(db.Float())
    imagePath = db.Column(db.String(255))
    about = db.Column(db.Text(), nullable=False)
    hours = db.Column(db.String(255), nullable=False)

    def __repr__(self):
        return '<Restaurant %r>' % self.name

    def __str__(self):
        return self.name

    def save(self):
        db.session.add(self)
        db.session.commit()
Ejemplo n.º 5
0
class CustomerModel(db.Model):

    __tablename__ = 'customers'

    customer_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    email = db.Column(db.String(80))
    phone = db.Column(db.String(9))
    doc = db.Column(db.String(11))

    def __init__(self, customer_id, name, email, phone, doc):
        self.customer_id = customer_id
        self.name = name
        self.email = email
        self.phone = phone
        self.doc = doc

    def json(self):
        return {
            'customer_id': self.customer_id,
            'name': self.name,
            'email': self.email,
            'phone': self.phone,
            'doc': self.doc
        }

    @classmethod
    def find_customer(cls, customer_id):
        customer = cls.query.filter_by(customer_id=customer_id).first()
        if customer:
            return customer
        return None

    def save_customer(self):
        db.session.add(self)
        db.session.commit()
Ejemplo n.º 6
0
class Report(db.Model):
    __tablename__ = "report"

    id_report = db.Column(db.Integer, primary_key=True)
    id_post = db.Column(db.Integer,
                        db.ForeignKey("post.id_post"),
                        nullable=False)
    content = db.Column(db.String(120), nullable=False, default="")
    reg_student = db.Column(db.Integer, db.ForeignKey("student.reg_student"))
    id_professor = db.Column(db.Integer,
                             db.ForeignKey("professor.id_professor"))
    offensive = db.Column(db.Boolean, nullable=False)
    prejudice = db.Column(db.Boolean, nullable=False)
    unrelated = db.Column(db.Boolean, nullable=False)
    others = db.Column(db.Boolean, nullable=False)
Ejemplo n.º 7
0
class Role(db.Model):
    __tablename__ = 'role'  # Nome da tabela no banco

    id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True, unique=True)
    name = db.Column(db.String(100))  # "Nome" do papel/funcao
    # Coluna principal para a pesquisa de permissao, a maioria dos usuarios terao essa permissao como padrao
    default = db.Column(db.Boolean, default=False, index=True)  
    permissions = db.Column(db.Integer)

    # Relacionar os dados da aula levando em consideração o id obtido
    users = db.relationship("User", backref="role", lazy='dynamic')

    def __init__(self, **kwargs):
        super(Role, self).__init__(**kwargs)

        if self.permissions is None:
            self.permissions = 0
    
    #Adicionar novas permissoes ao papel
    def add_permission(self, perm):
        if not self.has_permission(perm):
            self.permissions += perm
    
    #Remover permissoes
    def remove_permission(self, perm):
        if self.has_permission(perm):
            self.permissions -= perm
    
    #Resetar_permissoes
    def reset_permission(self):
        self.permissions = 0

    #Verifica se as permissoes combinadas inclui a permissao base
    def has_permission(self, perm):
        return self.permissions & perm == perm

    # Representação das consultas no banco, como irão ser apresentadas
    def __repr__(self):
        return "<Role %r>" % self.name
Ejemplo n.º 8
0
class Usuario(UserMixin, db.Model):
    __tablename__ = 'usuario'

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    nome = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    senha = db.Column(db.String(100), nullable=False)
    endereco = db.Column(db.String(100), nullable=False)
    cpf = db.Column(db.String(11), nullable=False, unique=True)
    data_nasc = db.Column(db.Date, nullable=False)
    email_verificado = db.Column(db.Integer, nullable=False, default=0)
    cargo = db.Column(db.String(100), default='cliente')
    comprador_vendas = db.relationship('Venda',
                                       backref='comprador',
                                       lazy='select')

    @staticmethod
    def salvar(usuario):
        try:
            if usuario.id:
                db.session.merge(usuario)
            else:
                db.session.add(usuario)

            db.session.commit()

            return True
        except exc.SQLAlchemyError:
            return False

    @staticmethod
    def excluir(id):
        try:
            usuario = Usuario.query.get(id)
            db.session.delete(usuario)
            db.session.commit()

            return True
        except exc.SQLAlchemyError:
            return False
Ejemplo n.º 9
0
class Produto(db.Model):
    __tablename__ = 'produto'

    id = db.Column(db.Integer, primary_key=True)
    nome = db.Column(db.String(100), nullable=False)
    descricao = db.Column(db.String(200), nullable=False)
    preco = db.Column(db.Float, nullable=False)
    quantidade = db.Column(db.Integer, nullable=False)
    arquivo = db.Column(db.String(400), nullable=False)
    item_vendas = db.relationship('ItemVenda',
                                  backref='produto',
                                  lazy='select')

    @staticmethod
    def buscar(palavra):
        try:
            if palavra:
                palavra = '%{}%'.format(palavra)
                produtos = Produto.query.filter(
                    Produto.nome.ilike(palavra)).order_by(Produto.id).all()
            else:
                produtos = Produto.query.order_by(Produto.id).all()

            return produtos
        except exc.SQLAlchemyError:
            return False

    @staticmethod
    def salvar(produto, foto=None):
        try:
            if foto:
                nome_foto = Foto.salvar(foto)

                if nome_foto:
                    produto.arquivo = 'uploads/' + nome_foto

            if produto.id:
                db.session.merge(produto)

            else:
                db.session.add(produto)

            db.session.commit()

            return True
        except exc.SQLAlchemyError:
            return False

    @staticmethod
    def excluir(produto):
        try:
            foto_removida = Foto.excluir(produto.arquivo)

            if foto_removida:
                db.session.delete(produto)
                db.session.commit()

                return True
            else:
                return False

        except exc.SQLAlchemyError:
            return False

    @staticmethod
    def get_dict_produto(id):
        produto = Produto.query.get(id)

        return produto.to_dict()

    def to_dict(self):
        dictionary = self.__dict__
        dictionary.pop('_sa_instance_state')

        return dictionary
Ejemplo n.º 10
0
class User(db.Model):
    __tablename__ = 'user'  # Nome da tabela no banco

    id = db.Column(db.Integer, nullable=False, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password_hash = db.Column(db.String(200), nullable=False)
    created_on = db.Column(db.DateTime, default=datetime.datetime.now(
        pytz.timezone("America/Sao_Paulo")))
    last_seen = db.Column(db.DateTime)
    first_seen = db.Column(db.DateTime)
    role_id = db.Column(db.Integer, db.ForeignKey("role.id"))


    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

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

    def get_id(self):
        return str(self.id)

    # Token para sessao
    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)

        return s.dumps({'confirm': self.id}).decode('utf-8')

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False

        if data.get('confirm') != self.id:
            return False

        return True

    # API
    def generate_auth_token(self, expiration):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)

        return s.dumps({'id': self.id}).decode('utf-8')

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None

        return User.query.get(data['id'])

    #permissao de acesso
    def can(self, perm):
        return self.role is not None and self.role.has_permission(perm)
    
    def is_administrator(self):
        return self.can(Permission.ADMIN)

    # Representação das consultas no banco, como irão ser apresentadas
    def __repr__(self):
        return "<User %r>" % self.username