예제 #1
0
    def has_roles(self, allowed=None, required=None):
        """checks the provided arguments against the roles assigned"""
        if not allowed and not required:
            return True

        allowed = split_and_extend(allowed)
        required = split_and_extend(required)

        logger.debug(
            "%(self)s.has_roles(allowed=%(allowed)s, required=%(required)s)"
            % locals())

        if allowed:
            # Ask the database if the user has any of the allowed roles.  For
            # smaller numbers of roles this is very slightly slower with
            # SQLite in :memory: but is a good amount faster over the network
            # or with large role sets.
            return bool(
                User.query.filter(
                    User.roles.any(
                        Role.name.in_(allowed))
                ).filter(User.id == self.id).count())

        if required:
            # Ask the database for all roles matching ``required``.  In order
            # for this to return True is the number of entries found must
            # be equal to len(required).
            count = Role.query.filter(
                Role.name.in_(required)).filter(User.id == self.id).count()
            return count == len(required)
 def test_split_and_extend(self):
     self.assertSetEqual(split_and_extend(["a.b.c.d"]),
                         set(["a", "a.b", "a.b.c", "a.b.c.d"]))
     self.assertIsNone(split_and_extend(None))
 def test_split_and_extend(self):
     self.assertSetEqual(
         split_and_extend(["a.b.c.d"]),
         set(["a", "a.b", "a.b.c", "a.b.c.d"]))
     self.assertIsNone(split_and_extend(None))