returns permissions that given user has for this resource
            without ones inherited from groups that user belongs to

        :param instance:
        :param user:
        :param db_session:
        :return:
199765
def direct_perms_for_user(cls, instance, user, db_session=None):
        
        db_session = get_db_session(db_session, instance)
        query = db_session.query(
            cls.models_proxy.UserResourcePermission.user_id,
            cls.models_proxy.UserResourcePermission.perm_name,
        )
        query = query.filter(cls.models_proxy.UserResourcePermission.user_id == user.id)
        query = query.filter(
            cls.models_proxy.UserResourcePermission.resource_id == instance.resource_id
        )

        perms = [
            PermissionTuple(user, row.perm_name, "user", None, instance, False, True)
            for row in query
        ]

        # include all perms if user is the owner of this resource
        if instance.owner_user_id == user.id:
            perms.append(
                PermissionTuple(user, ALL_PERMISSIONS, "user", None, instance, True)
            )
        return perms
631080
def user_packages(request, user):
    
    session = DBSession()
    owned = Package.by_owner(session, user)
    maintained = Package.by_maintainer(session, user)
    owned = [('Owner', p.name) for p in owned]
    maintained = [('Maintainer', p.name) for p in maintained]
    return owned + maintained
1282746
def revoke_user_access(self, user, db_names, strict=True):
        
        return self._user_manager.revoke_user_access(user, db_names,
                strict=strict)
1016086
async def permits(self, identity, permission, context=None):
        
        # pylint: disable=unused-argument
        user = self.user_map.get(identity)
        if not user:
            return False
        return permission in user.permissions
221845
def filter_(*permissions, **kwargs):
    
    bearer = kwargs['bearer']
    target = kwargs.get('target')
    bearer_cls = type_for(bearer)

    # We need a query object.  There are many ways to get one,  Either we can
    # be passed one, or we can make one from the session.  We can either be
    # passed the session, or we can grab the session from the bearer passed.

    if 'query' in kwargs:
        query = kwargs['query']
    elif 'session' in kwargs:
        query = kwargs['session'].query(target)
    else:
        query = object_session(bearer).query(target)

    getter = functools.partial(
        registry.retrieve,
        bearer=bearer_cls,
        target=target)

    try:
        # Generate a hash of {rulefn: permission} that we can use later
        # to collect all of the rules.
        if len(permissions):
            rules = {getter(permission=x): x for x in permissions}
        else:
            rules = {getter(): None}
    except KeyError:
        # No rules defined.  Default to no permission.
        return query.filter(sql.false())

    # Invoke all the rules and collect the results

    # Abusing reduce here to invoke each rule and send the return value (query)
    # from one rule to the next one.  In this way the query becomes
    # increasingly decorated as it marches through the system.

    # q == query
    # r = (rulefn, permission)
    reducer = lambda q, r: r[0](permission=r[1], query=q, bearer=bearer)

    return reduce(reducer, six.iteritems(rules), query)
1089482
def has_permission(user, *permissions, **role_kwargs):
    
    Role = get_model('role')
    Perm = get_model('permission')
    if isinstance(user, (unicode, str)):
        User = get_model('user')
        user = User.get(User.c.username==user)
        
    for name in permissions:
        perm = Perm.get(Perm.c.name==name)
        if not perm:
            continue
        
        flag = has_role(user, *list(perm.perm_roles.with_relation().all()), **role_kwargs)
        if flag:
            return flag
        
    return False
802882
def permissions(self, course_id, permissions=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # OPTIONAL - permissions
        """List of permissions to check against authenticated user"""
        if permissions is not None:
            params["permissions"] = permissions

        self.logger.debug("GET /api/v1/courses/{course_id}/permissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/permissions".format(**path), data=data, params=params, no_data=True)
1054386
def list_user_permissions(name, runas=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    res = __salt__['cmd.run_all'](
        [RABBITMQCTL, 'list_user_permissions', name, '-q'],
        reset_system_locale=False,
        runas=runas,
        python_shell=False)

    return _output_to_dict(res)
151274
def get_user_groups(user):
    """"""
    if user.is_active and user.is_authenticated():
        if user.is_superuser:
            return TenantGroup.objects.all()
        else:
            return TenantGroup.objects.filter(tenantrole__user=user).distinct()
    else:
        return TenantGroup.objects.none()
1369236
def has_permission(cls, user):
        
        # no login is needed, so its always fine
        if not cls.requires_login:
            return True

        # if user is somehow not logged in
        if not user.is_authenticated:
            return False

        # attribute permission_required is mandatory, returns tuple
        perms = cls.get_permission_required()
        # if perms are defined and empty, we skip checking
        if not perms:
            return True

        # get role of user, skip admin role
        role = user.urole.role.name
        if role == cls.ADMIN:
            return True

        # check if at least one permissions is valid
        for permission in perms:
            if cls.check_permission(role, permission):
                return True

        # permission denied
        return False
359629
def list_user_access(self, user):
        
        user = utils.get_name(user)
        uri = "/%s/%s/databases" % (self.uri_base, user)
        try:
            resp, resp_body = self.api.method_get(uri)
        except exc.NotFound as e:
            raise exc.NoSuchDatabaseUser("User '%s' does not exist." % user)
        dbs = resp_body.get("databases", {})
        return [CloudDatabaseDatabase(self, db) for db in dbs]
171262
def hasTablePermission(self, login, user, table, perm):
    
    self.send_hasTablePermission(login, user, table, perm)
    return self.recv_hasTablePermission()
1001636
def get_user_tenants(user, group):
    """"""
    if user.is_active and user.is_authenticated():
        if user.is_superuser or is_group_manager(user, group.pk):
            return Tenant.objects.filter(group=group)
        else:
            return Tenant.objects.filter(group=group, tenantrole__user=user).distinct()
    else:
        return Tenant.objects.none()
109016
def perm_by_group_and_perm_name(
        cls, resource_id, group_id, perm_name, db_session=None
    ):
        
        db_session = get_db_session(db_session)
        query = db_session.query(cls.models_proxy.GroupResourcePermission)
        query = query.filter(
            cls.models_proxy.GroupResourcePermission.group_id == group_id
        )
        query = query.filter(
            cls.models_proxy.GroupResourcePermission.perm_name == perm_name
        )
        query = query.filter(
            cls.models_proxy.GroupResourcePermission.resource_id == resource_id
        )
        return query.first()
699954
def setup_default_permissions(session, instance):
    
    if instance not in session.new or not isinstance(instance, Entity):
        return

    if not current_app:
        # working outside app_context. Raw object manipulation
        return

    _setup_default_permissions(instance)
865779
def get(cls, user_id, db_session=None):
        
        db_session = get_db_session(db_session)
        return db_session.query(cls.model).get(user_id)
261101
def required_role(req_role):
    
    def dec_wrapper(wfunc):
        @wraps(wfunc)
        def wrapped(*args, **kwargs):
            user_id = kwargs.get("user_id")
            try:
                res = db.DBSession.query(RoleUser).filter(RoleUser.user_id==user_id).join(Role, Role.code==req_role).one()
            except NoResultFound:
                raise PermissionError("Permission denied. User %s does not have role %s"%
                                (user_id, req_role))

            return wfunc(*args, **kwargs)

        return wrapped
    return dec_wrapper