Example #1
0
def login(store, username, password, client_using_tor):
    """
    login returns a tuple (user_id, state, pcn)
    """
    user = store.find(
        User, And(User.username == username, User.state != u'disabled')).one()

    if not user or not security.check_password(password, user.salt,
                                               user.password):
        log.debug("Login: Invalid credentials")
        GLSettings.failed_login_attempts += 1
        raise errors.InvalidAuthentication

    if not client_using_tor and not GLSettings.memory_copy.accept_tor2web_access[
            user.role]:
        log.err("Denied login request over Web for role '%s'" % user.role)
        raise errors.TorNetworkRequired

    log.debug("Login: Success (%s)" % user.role)
    user.last_login = datetime_now()
    return user.id, user.state, user.role, user.password_change_needed
Example #2
0
    def _getPackageBranch(self, owner, distribution, distroseries,
                          sourcepackagename, branch):
        """Find a source package branch given its path segments.

        Only gets unofficial source package branches, that is, branches with
        names like ~jml/ubuntu/jaunty/openssh/stuff.
        """
        origin = [
            Branch,
            Join(Person, Branch.owner == Person.id),
            Join(SourcePackageName,
                 Branch.sourcepackagename == SourcePackageName.id)
        ]
        return IStore(Branch).using(*origin).find(
            Branch, Person.name == owner, Branch.distroseriesID == Select(
                DistroSeries.id,
                And(DistroSeries.distribution == Distribution.id,
                    DistroSeries.name == distroseries,
                    Distribution.name == distribution)),
            SourcePackageName.name == sourcepackagename,
            Branch.name == branch).one()
Example #3
0
    def get_total_confirmed_value(self):
        """Returns the sum of all confirmed payments values

        This will consider all payments ignoring cancelled and preview
        ones, that is, if a payment is confirmed/reviewing/paid it will
        be summed.

        If you want to consider the preview ones too, use
        :meth:`.get_total_value` instead

        :returns: the total confirmed payments value
        """
        payments = self.store.find(
            Payment,
            And(
                Payment.group_id == self.id,
                Not(
                    In(Payment.status,
                       [Payment.STATUS_CANCELLED, Payment.STATUS_PREVIEW]))))

        return self._get_payments_sum(payments, Payment.value)
Example #4
0
    def _create_main_query(self, state):
        item = state.value
        if item is None:
            return None
        kind, value = item.value.split(':')
        payment_view = self.search_spec
        if kind == 'status':
            if value == 'paid':
                return payment_view.status == Payment.STATUS_PAID
            elif value == 'not-paid':
                return payment_view.status == Payment.STATUS_PENDING
            elif value == 'late':
                tolerance = api.sysparam.get_int('TOLERANCE_FOR_LATE_PAYMENTS')
                return And(
                    payment_view.status == Payment.STATUS_PENDING,
                    payment_view.due_date <
                    localtoday() - relativedelta(days=tolerance))
        elif kind == 'category':
            return payment_view.category == value

        raise AssertionError(kind, value)
Example #5
0
    def has_late_payments(cls, store, person):
        """Checks if the provided person has unpaid payments that are overdue

        :param person: A :class:`person <stoqlib.domain.person.Person>` to
          check if has late payments
        :returns: True if the person has overdue payments. False otherwise
        """
        tolerance = sysparam.get_int('TOLERANCE_FOR_LATE_PAYMENTS')

        query = And(
            cls.person_id == person.id, cls.status == Payment.STATUS_PENDING,
            cls.due_date < localtoday() - relativedelta(days=tolerance))

        for late_payments in store.find(cls, query):
            sale = late_payments.sale
            # Exclude payments for external sales as they are handled by an
            # external entity (e.g. a payment gateway) meaning that they be
            # out of sync with the Stoq database.
            if not sale or not sale.is_external():
                return True

        return False
Example #6
0
    def build_search_query(self, user, text):
        """Query parameters shared by search() and count_search_matches().

        :returns: Storm ResultSet object
        """
        # These classes are imported in this method to prevent an import loop.
        from lp.registry.model.product import Product, ProductSet
        from lp.registry.model.projectgroup import ProjectGroup
        from lp.registry.model.distribution import Distribution
        OtherPillarName = ClassAlias(PillarName)
        origin = [
            PillarName,
            LeftJoin(OtherPillarName,
                     PillarName.alias_for == OtherPillarName.id),
            LeftJoin(Product, PillarName.product == Product.id),
            LeftJoin(ProjectGroup, PillarName.projectgroup == ProjectGroup.id),
            LeftJoin(Distribution, PillarName.distribution == Distribution.id),
        ]
        conditions = SQL('''
            PillarName.active = TRUE
            AND (PillarName.name = lower(%(text)s) OR

                 Product.fti @@ ftq(%(text)s) OR
                 lower(Product.title) = lower(%(text)s) OR

                 Project.fti @@ ftq(%(text)s) OR
                 lower(Project.title) = lower(%(text)s) OR

                 Distribution.fti @@ ftq(%(text)s) OR
                 lower(Distribution.title) = lower(%(text)s)
                )
            ''' % sqlvalues(text=ensure_unicode(text)))
        columns = [
            PillarName, OtherPillarName, Product, ProjectGroup, Distribution
        ]
        return IStore(PillarName).using(*origin).find(
            tuple(columns),
            And(conditions, ProductSet.getProductPrivacyFilter(user)))
Example #7
0
 def add_attachment(self, mlist, msg_id, counter, name, content_type,
                    encoding, content):
     existing = self.db.find(
         Attachment.message_id,
         And(
             Attachment.list_name == unicode(mlist),
             Attachment.message_id == unicode(msg_id),
             Attachment.counter == counter,
         )).count()
     if existing:
         return
     attachment = Attachment()
     attachment.list_name = unicode(mlist)
     attachment.message_id = unicode(msg_id)
     attachment.counter = counter
     attachment.name = unicode(name)
     attachment.content_type = unicode(content_type)
     attachment.encoding = unicode(
         encoding) if encoding is not None else None
     attachment.content = content
     attachment.size = len(content)
     self.db.add(attachment)
     self.flush()
Example #8
0
    def delete_message_from_list(self, list_name, message_id):
        """Remove the given message for a specific list from the store.

        :param list_name: The fully qualified list name to which the
            message should be added.
        :param message: The Message-ID of the mesage to delete from the
            store.
        :raises LookupError: if there is no such message.
        """
        msg = self.get_message_by_id_from_list(list_name, message_id)
        if msg is None:
            raise MessageNotFound(list_name, message_id)
        self.db.remove(msg)
        # Remove the thread if necessary
        thread = self.db.find(
            Thread,
            And(
                Thread.list_name == msg.list_name,
                Thread.thread_id == msg.thread_id,
            )).one()
        if len(thread.emails) == 0:
            self.db.remove(thread)
        self.flush()
Example #9
0
def apply_patch(store):
    store.execute("""
        CREATE TABLE stock_transaction_history(
            id serial NOT NULL PRIMARY KEY,
            te_id bigint UNIQUE REFERENCES transaction_entry(id),
            date timestamp,
            stock_cost numeric(20, 8) CONSTRAINT positive_cost
                CHECK (stock_cost >= 0),
            quantity numeric(20, 3),
            type int CONSTRAINT type_range CHECK (type >= 0 and type <= 15),
            object_id bigint,
            responsible_id bigint NOT NULL REFERENCES login_user(id)
                ON UPDATE CASCADE,
            product_stock_item_id bigint NOT NULL REFERENCES product_stock_item(id)
                ON UPDATE CASCADE ON DELETE CASCADE
        );""")

    res = store.execute("""SELECT id FROM login_user WHERE
                           username='******'""").get_one()
    if not res:
        res = store.execute("""SELECT MIN(id) FROM login_user""").get_one()
    if res:
        user_id = res[0]

    # If the database is being created, there is no user and no stock items,
    # so this for will not be executed.
    for (item, sellable) in store.find((ProductStockItem, Sellable),
                                       And(ProductStockItem.storable_id == Storable.id,
                                           Storable.product_id == Product.id,
                                           Product.sellable_id == Sellable.id)):
        StockTransactionHistory(product_stock_item_id=item.id,
                                date=TransactionTimestamp(),
                                stock_cost=item.stock_cost,
                                quantity=item.quantity,
                                responsible_id=user_id,
                                type=StockTransactionHistory.TYPE_IMPORTED,
                                store=store)