给用户(user_id)授于权限(permission)
198419
async def grant(self, user_id, *permissions):
        "  "

        prefix = f"{self._prefix_perm}/{user_id}/"

        perm_names = [str(p) for p in permissions]        
        checkings = [
            KV.put.txn(prefix + p, b'\0', prev_kv=True) for p in perm_names
        ]
        success, response = await self._client.txn(compare=[], success=checkings)
        if not success:
            errmsg = f"无法授予用户({user_id})的权限: {{{', '.join(perm_names)}}}"
            raise Unprocessable(errmsg)

        if logger.isEnabledFor(logging.DEBUG):
            granted, ignored = set(), set()
            for i, (perm, _)  in enumerate(response):
                if perm is None:
                    granted.add(perm_names[i])
                else:
                    ignored.add(perm_names[i])
            
            logger.debug(f"授予用户({user_id})权限({', '.join(granted)}), "
                            f"忽略已授权({', '.join(ignored)})")
638735
public function permissionFetchById($permission_id)
    {
        $multi = is_array($permission_id);
        if (!$multi) {
            $permission_id = [$permission_id];
        }
        $in_query = join(',', $permission_id);
        $query = "
            SELECT
                permission_id, `name`, description, added_on, updated_on
            FROM
                auth_permission
            WHERE
                permission_id IN ($in_query)
            ";
        $cur = $this->db->prepare($query);
        try {
            $cur->execute();
            if ($multi) {
                $permissions = $cur->fetchAll(PDO::FETCH_CLASS, self::CLASS_PERMISSION);
            } else {
                $permissions = $cur->fetchObject(self::CLASS_PERMISSION);
            }
        } catch (PDOException $db_err) {
            if ($this->logger) {
                $this->logger->error("Error trying to fetch permission by ID", ['exception' => $db_err]);
            }
            $permissions = ($multi) ? [] : false;
        }
        return $permissions;
    }
145412
def permissions(cls, instance, db_session=None):
        
        db_session = get_db_session(db_session, instance)
        query = db_session.query(
            cls.models_proxy.GroupPermission.group_id.label("owner_id"),
            cls.models_proxy.GroupPermission.perm_name.label("perm_name"),
            sa.literal("group").label("type"),
        )
        query = query.filter(
            cls.models_proxy.GroupPermission.group_id
            == cls.models_proxy.UserGroup.group_id
        )
        query = query.filter(
            cls.models_proxy.User.id == cls.models_proxy.UserGroup.user_id
        )
        query = query.filter(cls.models_proxy.User.id == instance.id)

        query2 = db_session.query(
            cls.models_proxy.UserPermission.user_id.label("owner_id"),
            cls.models_proxy.UserPermission.perm_name.label("perm_name"),
            sa.literal("user").label("type"),
        )
        query2 = query2.filter(cls.models_proxy.UserPermission.user_id == instance.id)
        query = query.union(query2)
        groups_dict = dict([(g.id, g) for g in instance.groups])
        return [
            PermissionTuple(
                instance,
                row.perm_name,
                row.type,
                groups_dict.get(row.owner_id) if row.type == "group" else None,
                None,
                False,
                True,
            )
            for row in query
        ]
25950
public boolean permissionsContainOwnKeyword(User user, ParaObject object) {
		if (user == null || object == null) {
			return false;
		}
		String resourcePath1 = object.getType();
		String resourcePath2 = object.getObjectURI().substring(1); // remove first '/'
		String resourcePath3 = object.getPlural();
		return hasOwnKeyword(App.ALLOW_ALL, resourcePath1)
				|| hasOwnKeyword(App.ALLOW_ALL, resourcePath2)
				|| hasOwnKeyword(App.ALLOW_ALL, resourcePath3)
				|| hasOwnKeyword(user.getId(), resourcePath1)
				|| hasOwnKeyword(user.getId(), resourcePath2)
				|| hasOwnKeyword(user.getId(), resourcePath3);
	}
207260
public boolean getWriteAccess(String userId) {
    if (StringUtil.isEmpty(userId)) {
      return false;
    }
    Permissions permissions = permissionsById.get(userId);
    return permissions != null && permissions.getWritePermission();
  }
1153433
def queryUser(self, groupId):
        

        desc = {
            "name": "GroupUserQueryReslut",
            "desc": "groupUserQuery返回结果",
            "fields": [{
                "name": "code",
                "type": "Integer",
                "desc": "返回码，200 为正常。"
            }, {
                "name": "id",
                "type": "String",
                "desc": "群成员用户Id。"
            }, {
                "name": "users",
                "type": "List<GroupUser>",
                "desc": "群成员列表。"
            }]
        }
        r = self.call_api(
            method=('API', 'POST', 'application/x-www-form-urlencoded'),
            action='/group/user/query.json',
            params={"groupId": groupId})
        return Response(r, desc)
1310203
@Override
    public boolean checkUserPermission(String pattern, RequestMethod method) {
        // 获取用户角色
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor == null) {
            return false;
        }

        String urlPattarn = pattern;
        if (!urlPattarn.endsWith(RoleResourceConstant.URL_SPLITOR)) {
            urlPattarn += RoleResourceConstant.URL_SPLITOR;
        }

        Integer roleId = visitor.getRoleId();

        Map<String, Map<RequestMethod, List<Integer>>> roleResMap = getAllAsMap();
        Map<RequestMethod, List<Integer>> methodMap = roleResMap.get(urlPattarn);
        if (methodMap == null) {
            return false;
        }

        List<Integer> roleIdList = methodMap.get(method);
        if (roleIdList == null) {
            return false;
        }

        if (!roleIdList.contains(roleId)) {
            return false;
        }
        return true;
    }
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
15389
public function getPermissions($user_id = null)
    {
        static $permissions = array();

        if (!isset($user_id)) {
            $user_id = $this->uid;
        }

        if (isset($permissions[$user_id])) {
            return $permissions[$user_id];
        }

        $user = $this->get($user_id);

        if (empty($user['role_id'])) {
            return $permissions[$user_id] = array();
        }

        $role = array();
        if (isset($user['role_permissions'])) {
            $role['permissions'] = $user['role_permissions'];
        } else {
            $role = $this->role->get($user['role_id']);
        }

        if (empty($role['permissions'])) {
            return $permissions[$user_id] = array();
        }

        return $permissions[$user_id] = (array) $role['permissions'];
    }
156027
def get_user_info(self, user_id, lang="zh_CN"):
        
        return self.get(
            url="https://api.weixin.qq.com/cgi-bin/user/info",
            params={
                "access_token": self.token,
                "openid": user_id,
                "lang": lang
            }
        )
975141
public function groupEdit($group_id, $group_name = "", $group_description = "", $max_user = 0)
    {
        $url    = $this->url.'chatgroups/'.$group_id;
        $option = [
            "groupname"   => self::stringReplace($group_name),
            "description" => self::stringReplace($group_description),
            "maxusers"    => $max_user,
        ];
        $option = array_filter($option);
        if (empty($option)) {
            throw new EasemobError('提交修改的参数，不修改提交空！');
        }

        $access_token = $this->getToken();
        $header []    = 'Authorization: Bearer '.$access_token;

        return Http::postCurl($url, $option, $header, 'PUT');
    }
680789
public function encode($user_id)
    {
        $user_id = str_pad($user_id, $this->length, '0', STR_PAD_LEFT);

//        $salt_rand = mt_rand(0, 9);
        //由MOD10算法生成校验码
        $salt_rand = $this->generateNumber($user_id);
        $rand      = substr(str_shuffle($this->salt[$salt_rand]), 0, 4);

        $str = $this->fixed_code . $salt_rand;

        $len  = strlen($user_id);
        $rlen = strlen($rand);
        $slen = count($this->salt);

        //对用户ID加密
        for ($i = 0; $i < $len; $i++) {
            $k1 = $i % $rlen;
            $k2 = $i % $slen;

            $rval1 = $rand[$k1];

            $user_id[$i] = ($user_id[$i] + $this->salt[$k2][$rval1]) % 10;
        }

        //对随机码加密
        $sr = $salt_rand;
        for ($j = 0; $j < $rlen; $j++) {
            $rand[$j] = $sr = ($rand[$j] + $sr) % 10;
        }

        return $str . $rand . $user_id;
    }
848026
function UserPermissions() {
	//使用者帳號(索引用)
	this.strAccount = "";
	//控制錄影權限
	this.bVideo = false;
	//操作回放權限
	this.bPlayback = false;
	//設備位移縮放
	this.bMoveScale = false;
	//設定設備名稱
	this.bSetDevice = false;
	//警報事件處理
	this.bAlertEvent = false;
	//下載備份權限
	this.bBackup = false;
	//拍照畫面權限
	this.bPhotograph = false;
	//軟體更新權限
	this.bUpdate = false;
	//登入權限
	this.bLogin = true;
}
675435
function(objects, user, action, model, body) {
    if (!_.isArray(objects)) {
      return PermissionService.isAllowedToPerformSingle(user.id, action, model, body)(objects);
    }
    return Promise.all(objects.map(PermissionService.isAllowedToPerformSingle(user.id, action, model, body)))
      .then(function (allowedArray) {
        return allowedArray.every(function (allowed) {
          return allowed === true;
        });
      });
  }
540980
def has_permission(self, request, view):
        
        user_filter = self._get_user_filter(request)
        if not user_filter:
            # no user filters are present in the token to limit access
            return True

        username_param = get_username_param(request)
        allowed = user_filter == username_param
        if not allowed:
            log.warning(
                u"Permission JwtHasUserFilterForRequestedUser: user_filter %s doesn't match username %s.",
                user_filter,
                username_param,
            )
        return allowed
405007
public static List<Permission> id2Permissions(int id){
        List<Permission> list = new ArrayList<Permission>();
        if(id <= 0 || id > 31){
            list.add(Permission.NONE);
        }else{
            if((id & Permission.READ.getId())!=0){
                list.add(Permission.READ);
            }
            if((id & Permission.WRITE.getId())!=0){
                list.add(Permission.WRITE);
            }
            if((id & Permission.CREATE.getId())!=0){
                list.add(Permission.CREATE);
            }
            if((id & Permission.DELETE.getId())!=0){
                list.add(Permission.DELETE);
            }
            if((id & Permission.ADMIN.getId())!=0){
                list.add(Permission.ADMIN);
            }
        }
        return list;
    }
551162
def cli(env, identifier, enable, permission, from_user):
    """"""
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    result = False
    if from_user:
        from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
        result = mgr.permissions_from_user(user_id, from_user_id)
    elif enable:
        result = mgr.add_permissions(user_id, permission)
    else:
        result = mgr.remove_permissions(user_id, permission)

    if result:
        click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
    else:
        click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red')