Get or set permissions API endpoint.
969415
def detail_permissions(self, request, pk=None):
        """"""
        obj = self.get_object()

        if request.method == 'POST':
            content_type = ContentType.objects.get_for_model(obj)
            payload = request.data
            share_content = strtobool(payload.pop('share_content', 'false'))
            user = request.user
            is_owner = user.has_perm('owner_{}'.format(content_type), obj=obj)

            allow_owner = is_owner or user.is_superuser
            check_owner_permission(payload, allow_owner)
            check_public_permissions(payload)
            check_user_permissions(payload, request.user.pk)

            with transaction.atomic():
                update_permission(obj, payload)

                owner_count = UserObjectPermission.objects.filter(
                    object_pk=obj.id,
                    content_type=content_type,
                    permission__codename__startswith='owner_'
                ).count()

                if not owner_count:
                    raise exceptions.ParseError('Object must have at least one owner.')

            if share_content:
                self.set_content_permissions(user, obj, payload)

        return Response(get_object_perms(obj))
268988
def get_permissions(self, obj):
        
        # TODO: Optimize this for bulk running
        filters = {
            'object_pk': obj.id,
            'content_type': ContentType.objects.get_for_model(obj),
            'permission__codename__startswith': 'view',
        }
        return {
            'users': list(
                UserObjectPermission.objects.filter(**filters).distinct('user').values_list('user_id', flat=True)
            ),
            'groups': list(
                GroupObjectPermission.objects.filter(**filters).distinct('group').values_list('group', flat=True)
            ),
            'public': UserObjectPermission.objects.filter(user__username=ANONYMOUS_USER_NAME, **filters).exists(),
        }
1163699
def get_permissions(FunctionName, Qualifier=None,
                    region=None, key=None, keyid=None, profile=None):
    '''
    
    '''

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        kwargs = {}
        if Qualifier is not None:
            kwargs['Qualifier'] = Qualifier
        # The get_policy call is not symmetric with add/remove_permissions. So
        # massage it until it is, for better ease of use.
        policy = conn.get_policy(FunctionName=FunctionName,
                                 **kwargs)
        policy = policy.get('Policy', {})
        if isinstance(policy, six.string_types):
            policy = salt.utils.json.loads(policy)
        if policy is None:
            policy = {}
        permissions = {}
        for statement in policy.get('Statement', []):
            condition = statement.get('Condition', {})
            principal = statement.get('Principal', {})
            if 'AWS' in principal:
                principal = principal['AWS'].split(':')[4]
            else:
                principal = principal.get('Service')
            permission = {
                'Action': statement.get('Action'),
                'Principal': principal,
            }
            if 'ArnLike' in condition:
                permission['SourceArn'] = condition[
                    'ArnLike'].get('AWS:SourceArn')
            if 'StringEquals' in condition:
                permission['SourceAccount'] = condition[
                    'StringEquals'].get('AWS:SourceAccount')
            permissions[statement.get('Sid')] = permission
        return {'permissions': permissions}
    except ClientError as e:
        err = __utils__['boto3.get_error'](e)
        if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
            return {'permissions': None}
        return {'permissions': None, 'error': err}
813871
def has_permission(self):
        """"""
        objs = [None]
        if hasattr(self, 'get_perms_objects'):
            objs = self.get_perms_objects()
        else:
            if hasattr(self, 'get_object'):
                try:
                    objs = [self.get_object()]
                except Http404:
                    raise
                except:
                    pass
            if objs == [None]:
                objs = self.get_queryset()

        if (hasattr(self, 'permission_filter_queryset') and
           self.permission_filter_queryset is not False and
           self.request.method == 'GET'):
            if objs != [None]:
                self.perms_filter_queryset(objs)
            return True
        else:
            return check_perms(self.request.user,
                               self.get_permission_required(),
                               objs, self.request.method)
1335715
def organization_users(self, id, permission_set=None, role=None, **kwargs):
        ""
        api_path = "/api/v2/organizations/{id}/users.json"
        api_path = api_path.format(id=id)
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if permission_set:
            api_query.update({
                "permission_set": permission_set,
            })
        if role:
            api_query.update({
                "role": role,
            })
        return self.call(api_path, query=api_query, **kwargs)
835392
def endpoint(f):
    """"""

    def check_authentication(self, **kwargs):
        """If the `authentication` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 401 authentication error"""
        if getattr(self, 'authentication', None) is None:
            current_app.logger.debug("No authentication method")
            return

        a = self.authentication()
        if not hasattr(a, 'is_authenticated'):
            current_app.logger.debug("No is_authenticated method")
            return

        if not a.is_authenticated(**kwargs):
            msg = getattr(g, 'authentication_error', 'Authentication failed')
            current_app.logger.warning("Authentication failed: {}".format(msg))
            return self._make_response(401, msg, abort=True)
        current_app.logger.debug("Authentication successful")

    def check_authorization(self):
        """If the `authorization` variable is defined and not None, the
           specified method will be run. On True the request will continue
           otherwise it will fail with a 403 authorization error"""
        current_app.logger.info("Checking authentication/authorization")
        auth_class = getattr(self, 'authorization',
                             getattr(self, 'authentication', None))
        if auth_class is None:
            current_app.logger.debug("No authorization class")
            return

        a = auth_class()
        if not hasattr(a, 'is_authorized'):
            current_app.logger.debug("No is_authorized method")
            return

        if not a.is_authorized(record=g._resource_instance):
            current_app.logger.warning("Authorization failed")
            return self._make_response(403, "Authorization failed", abort=True)
        current_app.logger.debug("Authorization successful")

    def validate_request(self, **kwargs):
        """Call the validator class and validate the request_data. This method
           returns True or False. On False, a 400 will be returned with the
           reasons for the validation error. On True, the operation will
           continue."""
        current_app.logger.info(
            "Checking {} validation".format(request.method))
        if getattr(self, 'validation', None) is None:
            current_app.logger.warning("No validation specified")
            return

        v = self.validation()
        method = 'validate_{}'.format(request.method.lower())

        if not hasattr(v, method):
            current_app.logger.warning("No validation method specified")
            return
        errors = getattr(v, method)(**kwargs)
        current_app.logger.debug("Validation errors: {}".format(errors))

        if errors is not None and len(errors) > 0:
            current_app.logger.warning("Validation errors found")
            self._make_response(400, errors, abort=True)

    def load_request_data(self):
        if request.method in ['GET', 'DELETE']:
            return
        current_app.logger.info("Saving json payload in memory")
        # For now we assume JSON. Later in life we can make this more
        # payload agnostic
        try:
            d = request.data.decode('utf-8')
            g._rq_data = {} if d.strip() == "" else json.loads(d)
        except ValueError:
            return self._make_response(400, "Malformed JSON in request body",
                                       abort=True)

        if self.enforce_json_root and g._rq_data != {} and \
                list(g._rq_data.keys()) != [self._payload_root()]:
            msg = "Invalid JSON root in request body"
            current_app.logger.error(msg)
            current_app.logger.debug(
                "Found {}, expecting {}".format(
                    list(g._rq_data.keys()), self._payload_root()))
            return self._make_response(400, msg, abort=True)
        elif self._payload_root() in list(g._rq_data.keys()):
                current_app.logger.debug("Removing JSON root from rq payload")
                g._rq_data = g._rq_data[self._payload_root()]
        current_app.logger.debug("g._rq_data: {}".format(g._rq_data))
        return g._rq_data

    @wraps(f)
    def decorator(self, *args, **kwargs):
        current_app.logger.info("Got {} request".format(request.method))
        current_app.logger.info("Endpoint: {}".format(request.url))
        if request.method not in self.allowed_methods:
            msg = "Request method {} is unavailable".format(request.method)
            current_app.logger.error(msg)
            return self._make_response(405, msg, abort=True)

        current_app.logger.info("Checking db table/collection is defined")
        if self.enforce_payload_collection and self.db_collection is None:
            msg = "No DB collection defined"
            current_app.logger.error(msg)
            return make_response(Response(msg, 424))

        if request.method in ['POST', 'PUT', 'PATCH']:
            load_request_data(self)

        check_authentication(self, **kwargs)
        if kwargs.get('obj_id', False):
            kwargs['obj_id'] = self.fiddle_id(kwargs['obj_id'])
            self._get_instance(**kwargs)
        else:
            g._resource_instance = {}

        if request.method in ['POST', 'PUT', 'PATCH']:
            check_authorization(self)
            r = self.transform_record(g._rq_data.get(self._payload_root(),
                                                     g._rq_data))
            g._saveable_record = dict(self.merge_record_data(
                r, dict(getattr(g, '_resource_instance', r))))
            validate_request(self, data=g._saveable_record)
        else:
            check_authorization(self)
            validate_request(self)
        return f(self, *args, **kwargs)
    return decorator
1004176
def set_access_control(self, mode, onerror = None):
        """"""
        request.SetAccessControl(display = self.display,
                                 onerror = onerror,
                                 mode = mode)
592594
def get_api_root_view(self, **kwargs):
        """"""
        class API(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                directory_list = get_directory(request)
                result = OrderedDict()
                for group_name, url, endpoints, _ in directory_list:
                    if url:
                        result[group_name] = url
                    else:
                        group = OrderedDict()
                        for endpoint_name, url, _, _ in endpoints:
                            group[endpoint_name] = url
                        result[group_name] = group
                return Response(result)

        return API.as_view()
1282302
def endpoint_access(self, method):
        
        if method == 'OPTIONS':
            # The CORS pre-flight checks should not require authentication
            return self.UNAUTHENTICATED_ACCESS
        elif method not in self.METHOD_ACCESS:
            logging.error('Cannot determine access needed for %s method', method)
            raise HTTPError(500, 'Internal Server Error')

        return self.METHOD_ACCESS[method]
285465
def _access_token_endpoint(self, grantType, extraParams={}):
        
        response = requests.post(
            self._format_url(OAUTH2_ROOT + 'access_token'),
            data = _extend({
                'grant_type': grantType,
                'client_id': self.client.get('client_id', ''),
                'client_secret': self.client.get('client_secret', ''),
                'redirect_uri': self.client.get('redirect_uri', '')
            }, extraParams))
        
        data = response.json()
        if 'error' in data or 'error_description' in data:
            raise _token_error_from_data(data)
        else:
            return self.set_creds(data)
612133
public function checkEndpointAccess()
    {
        UserOnline::refreshUser($this->userAuthClass()->identity, $this->id);
        
        if (!Yii::$app->auth->matchApi($this->userAuthClass()->identity->id, $this->id, false)) {
            throw new ForbiddenHttpException('Unable to access this action due to insufficient permissions.');
        }
    }
696542
def create_api_object_group_permission_general(self):
        """"""

        return ApiObjectGroupPermissionGeneral(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
317087
def _permission_trees(permissions):
        """"""
        treecache = PermissionTreeCache()
        cached = treecache.get()
        if not cached:
            tree = PermissionTreeBuilder()
            for permission in permissions:
                tree.insert(permission)
            result = tree.serialize()
            treecache.set(result)
            return result
        return cached
1197813
def user_disable_throw_rest_endpoint(self, username, url='rest/scriptrunner/latest/custom/disableUser',
                                         param='userName'):
        """"""
        url = "{}?{}={}".format(url, param, username)
        return self.get(path=url)
862853
def get_all_permissions(self, user, obj=None):
        
        if user.is_anonymous or obj is not None:
            return set()
        # TODO(gabrielhurley): Integrate policy-driven RBAC
        #                      when supported by Keystone.
        role_perms = {utils.get_role_permission(role['name'])
                      for role in user.roles}

        services = []
        for service in user.service_catalog:
            try:
                service_type = service['type']
            except KeyError:
                continue
            service_regions = [utils.get_endpoint_region(endpoint) for endpoint
                               in service.get('endpoints', [])]
            if user.services_region in service_regions:
                services.append(service_type.lower())
        service_perms = {"openstack.services.%s" % service
                         for service in services}
        return role_perms | service_perms
557192
public static void getPermission(@NonNull Activity context, String permissions, @NonNull Response response) {
        getPermission(context, new String[]{permissions}, response);
    }
968361
def set(self, permissions):
        
        parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
        target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'PUT', 'multi')
        r = self.client.request('PUT', target_url, json=permissions)
        if r.status_code != 201:
            raise exceptions.ServerError("Expected 201 response, got %s: %s" % (r.status_code, target_url))
        return self.list()