'permission_obj' param should be a string. 
                e.g. '[{"access":"d_u_list","oid":{"id":"1576946496","type":"Domain"}}]'

        http://docs.exosite.com/portals/#add-user-permission
347674
def create_token(self, user_id, permission_obj):
        

        headers = {
                'User-Agent': self.user_agent(),
                'Content-Type': self.content_type()
        }
        headers.update(self.headers())

        url = self.portals_url()+'/users/{0}/permissions'.format(user_id)
        # print("URL: {0}".format(url))
        r = requests.post(  url,
                            data=permission_obj,
                            headers=headers,
                            auth=self.auth())
    
        if HTTP_STATUS.OK == r.status_code:
            return r.json()
        else:
            print("create_token: Something went wrong: <{0}>: {1}".format(
                        r.status_code, r.reason))
            r.raise_for_status()
1370783
def _populate_permissions(resources, content_type_id):
    
    from django.contrib.auth.models import Permission
    # read the whole auth_permission table into memory
    db_perms = [perm.codename for perm in Permission.objects.all()]

    for resource in resources:
        # get all resource's permissions that are not already in db
        perms = [perm for perm in resource.access_controller.get_perm_names(resource) if perm not in db_perms]
        for perm in perms:
            _save_new_permission(perm, content_type_id)
61599
def set_permissions_mode_from_octal(file_path, code):
    
    # Unpack permissions tuple
    user, group, other = tuple(str(code[-3:])) if len(str(code)) > 3 else tuple(str(code))
    user, group, other = int(user), int(group), int(other)
    mode = get_permissions_mode(user,
                                'user') & get_permissions_mode(group, 'group') & get_permissions_mode(other, 'other')
    os.chmod(file_path, mode)
508096
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def add_permissions(user_field_permissions, content_type, name):

            p = None
            try:
                p = FieldPermission.objects.get(content_type=content_type, name=name)
            except ObjectDoesNotExist:
                p = FieldPermission(content_type=content_type, name=name)
                p.save()
            finally:
                user_field_permissions.permissions.add(p)



        if len(args) !=1:
             raise CommandError("Specifies a json file created by the fine_permissions_dump command")
        else:
            try:


                with open(args[0], 'r') as json_file:
                    myjson = json.load(json_file)

                    user = get_user(options.get('user')) if options['user'] else get_user(myjson['username'])
                    fields_permissions = myjson['fields_permissions']

                    user_field_permissions = UserFieldPermissions(user=user)
                    user_field_permissions.save()

                    for f in fields_permissions:
                        content_type = ContentType.objects.get(app_label=f["app_label"], model=f["model"])
                        add_permissions(user_field_permissions, content_type, f['name'])


            except Exception as e:
                raise CommandError(e)
1314633
def users_list(self, permission_set=None, role=None, **kwargs):
        ""
        api_path = "/api/v2/users.json"
        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)
973281
async def set_access_string(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))

		cid = int(params.get("cid", "0"))
		seller_access_string = params.get("seller_access_string")
		seller_pubkey = params.get("seller_pubkey")
		coinid = params.get("coinid")

		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass

		database = client[coinid]
		collection = database[settings.CONTENT]
		content = await collection.find_one({"cid":cid})

		if not content:
			return {"error":404, "reason":"Content not found"}

		if not all([cid, seller_access_string, seller_pubkey]):
			return {"error":400, "reason":"Missed required fields"}

		await collection.find_one_and_update({"cid":cid},
						{"$set":{"seller_access_string":seller_access_string}})

		await collection.find_one_and_update({"cid":cid},
						{"$set":{"seller_pubkey":seller_pubkey}})

		content = await collection.find_one({"cid":cid})
		return {i:content[i] for i in content if i != "_id"}
175676
def request_permission(cls, permissions):
        
        app = AndroidApplication.instance()
        f = app.create_future()

        def on_result(perms):
            allowed = True
            for p in permissions:
                allowed = allowed and perms.get(p, False)
            f.set_result(allowed)

        app.request_permissions(permissions).then(on_result)

        return f
264954
def has_perm(self, service, perm_name, obj, call_name):
        
        user = service.user
        if not (perm_name is False):
            if not user.has_perm(perm_name, obj=obj):
                LOG_PERM.warn(
                    u'User %s has no permission %s. Access to %s with obj=%s',
                    user, perm_name, call_name, obj)
                raise PermissionDenied(u'User %s has no permission %s for object %s' % (service.user, perm_name, obj))

            LOG_PERM.debug(
                u'User %s was authorized to access %s with permission %s with obj=%s',
                user, call_name, perm_name, obj)
976484
def print_permissions(permissions):
    """"""

    table = formatting.Table(['keyName', 'Description'])
    for perm in permissions:
        table.add_row([perm['keyName'], perm['name']])
    return table
683091
def check(self, user, permission, obj=_nothing):
        
        if not self.allows(user, permission, obj):
            raise AuthorizationError(
                'Can\'t {} object of class {}'.format(
                    permission, type(obj)))
311455
def _assert_valid_permission(self, perm_str):
        """"""
        if perm_str not in ORDERED_PERM_LIST:
            raise d1_common.types.exceptions.InvalidRequest(
                0,
                'Permission must be one of {}. perm_str="{}"'.format(
                    ', '.join(ORDERED_PERM_LIST), perm_str
                ),
            )
496539
def has_edit_permission(self, request, obj=None, version=None):
        
        # Has the edit permission for this object type
        permission_name = '{}.edit_{}'.format(self.opts.app_label, self.opts.model_name)
        has_permission = request.user.has_perm(permission_name)

        if obj is not None and has_permission is False:
            has_permission = request.user.has_perm(permission_name, obj=obj)

        if has_permission and version is not None:
            # Version must not be saved, and must belong to this user
            if version.version_number or version.owner != request.user:
                has_permission = False

        return has_permission
278204
def permissions(self):
        
        # TODO: optimize this, it's kind of a bad solution for listing a mostly
        # static set of files.
        # We could either add a permissions dict as an attribute or cache this
        # in some way. Creating a dict would be another place we have to define
        # the permission, so I'm not a huge fan, but it would definitely be the
        # easier option.
        permissions_dict = {"self": {}, "parent": {}}

        for field in self.properties._meta.get_fields():
            split_field = field.name.split('_', 1)
            if len(split_field) <= 0 or split_field[0] not in ['self', 'parent']:
                continue
            permissions_dict[split_field[0]][split_field[1]] = getattr(self.properties, field.name)

        return permissions_dict
591784
def permission_required(perm, *lookup_variables, **kwargs):
    
    login_url = kwargs.pop('login_url', settings.LOGIN_URL)
    redirect_field_name = kwargs.pop('redirect_field_name', REDIRECT_FIELD_NAME)
    redirect_to_login = kwargs.pop('redirect_to_login', True)

    def decorate(view_func):
        def decorated(request, *args, **kwargs):
            if request.user.is_authenticated():
                params = []
                for lookup_variable in lookup_variables:
                    if isinstance(lookup_variable, string_types):
                        value = kwargs.get(lookup_variable, None)
                        if value is None:
                            continue
                        params.append(value)
                    elif isinstance(lookup_variable, (tuple, list)):
                        model, lookup, varname = lookup_variable
                        value = kwargs.get(varname, None)
                        if value is None:
                            continue
                        if isinstance(model, string_types):
                            model_class = apps.get_model(*model.split("."))
                        else:
                            model_class = model
                        if model_class is None:
                            raise ValueError(
                                "The given argument '%s' is not a valid model." % model)
                        if (inspect.isclass(model_class) and
                                not issubclass(model_class, Model)):
                            raise ValueError(
                                'The argument %s needs to be a model.' % model)
                        obj = get_object_or_404(model_class, **{lookup: value})
                        params.append(obj)
                check = get_check(request.user, perm)
                granted = False
                if check is not None:
                    granted = check(*params)
                if granted or request.user.has_perm(perm):
                    return view_func(request, *args, **kwargs)
            if redirect_to_login:
                path = urlquote(request.get_full_path())
                tup = login_url, redirect_field_name, path
                return HttpResponseRedirect('%s?%s=%s' % tup)
            return permission_denied(request)
        return wraps(view_func)(decorated)
    return decorate
257773
def get_permissions(self, user_id):
        """"""
        response = self.request(
            "{0}/{1}/permissions".format(self.version, user_id), {}
        )["data"]
        return {x["permission"] for x in response if x["status"] == "granted"}
158716
def get_details_permissions(self):
        
        l = {}

        for i in self.permissions:
            if i in self.permission_module:
                x = self.permission_module[i]
                l[i] = [x["protectionLevel"], x["label"], x["description"]]
            else:
                # FIXME: the permission might be signature, if it is defined by the app itself!
                l[i] = ["normal", "Unknown permission from android reference",
                        "Unknown permission from android reference"]
        return l
770340
def get_permissions_assignments(self, obj=None, permission=None):
        
        session = None
        if obj is not None:
            assert isinstance(obj, Entity)
            session = object_session(obj)

            if obj.id is None:
                obj = None

        if session is None:
            session = db.session()

        pa = session.query(
            PermissionAssignment.permission, PermissionAssignment.role
        ).filter(PermissionAssignment.object == obj)

        if permission:
            pa = pa.filter(PermissionAssignment.permission == permission)

        results = {}
        for permission, role in pa.yield_per(1000):
            results.setdefault(permission, set()).add(role)

        return results