当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript tyranid.Tyr类代码示例

本文整理汇总了TypeScript中tyranid.Tyr的典型用法代码示例。如果您正苦于以下问题:TypeScript Tyr类的具体用法?TypeScript Tyr怎么用?TypeScript Tyr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Tyr类的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: findEntitiesWithPermissionAccessToResource

  public static async findEntitiesWithPermissionAccessToResource(
    accessType: 'allow' | 'deny',
    permissions: string[],
    doc: Tyr.Document
  ) {
    const plugin = PermissionsModel.getGraclPlugin();
    validateAsResource(plugin, doc.$model);

    if (!permissions.length) {
      plugin.error(
        `No permissions provided to findEntitiesWithPermissionAccessToResource()!`
      );
    }

    /**
     * Get hierarchy of permissions stemming from provided list
     */
    const permHierarchy = permissions.map(p => {
      const components = parsePermissionString(plugin, p);

      const formatted = formatPermissionType(plugin, {
        action: components.action,
        collection:
          components.collection ||
          (isCrudPermission(plugin, p) && doc.$model.def.name) ||
          undefined
      });

      validatePermissionExists(plugin, formatted);

      return [formatted, ...getPermissionParents(plugin, formatted)];
    });

    const permissionsAsResource = (await plugin.permissionsModel.findAll({
      query: {
        $and: [
          // for the given resource...
          { resourceId: doc.$uid },
          // get any permission docs with any of the possible permTypes
          {
            $or: permHierarchy.map(list => ({
              $or: list.map(permission => ({
                [`access.${permission}`]: { $exists: true }
              }))
            }))
          }
        ]
      }
    })) as Permission[];

    // get all subjects with direct permissions set for this resource,
    // does not yet include _all_ subjects down the heirarchy
    const subjectDocuments = await Tyr.byUids(permissionsAsResource.map(
      p => p.subjectId
    ) as string[]);

    const subjectsByCollection: Hash<Tyr.Document[]> = {};
    _.each(subjectDocuments, subject => {
      const colName = subject.$model.def.name;
      if (!subjectsByCollection[colName]) {
        subjectsByCollection[colName] = [];
      }
      subjectsByCollection[colName].push(subject);
    });

    const permsBySubjectId: Hash<Permission> = {};
    _.each(permissionsAsResource, perm => {
      permsBySubjectId[perm.subjectId] = perm;
    });

    // test if a given subject satisfies all required permissions
    const accessCache: Hash<boolean> = {};
    function filterAccess(subject: Tyr.Document, explicit = false) {
      const uid = subject.$uid;
      const hashKey = `${uid}-${explicit}`;

      if (hashKey in accessCache) {
        return accessCache[hashKey];
      }

      const perm = permsBySubjectId[uid] || { access: {} };

      return (accessCache[hashKey] = _.every(permHierarchy, list => {
        // check for explicit denies
        if (explicit) {
          const access = accessType === 'allow' ? false : true;
          return _.every(list, p => _.get(perm, `access.${p}`) !== access);
        } else {
          const access = accessType === 'allow' ? true : false;
          return _.some(list, p => _.get(perm, `access.${p}`) === access);
        }
      }));
    }

    interface Hierarchy {
      [key: string]: Hierarchy;
    }

    async function traverse(
      hierarchy: Hierarchy,
//.........这里部分代码省略.........
开发者ID:tyranid-org,项目名称:tyranid,代码行数:101,代码来源:PermissionsModel.ts

示例2: updatePermissions

  /**
   * Create/update a permission edge document to
   * set a permission between a given resource and subject
   */
  public static async updatePermissions(
    resourceDocument: Tyr.Document | string,
    permissionChanges: { [key: string]: boolean },
    subjectDocument: Tyr.Document | string,
    attempt = 0
  ) {
    const plugin = PermissionsModel.getGraclPlugin();

    const $set: { [key: string]: boolean } = {};

    _.each(permissionChanges, (access, permissionType) => {
      if (permissionType) {
        validatePermissionExists(plugin, permissionType);
        $set[`access.${permissionType}`] = access;
      }
    });

    if (!resourceDocument) {
      throw new TypeError(`no resource given to updatePermissions`);
    }
    if (!subjectDocument) {
      throw new TypeError(`no subject given to updatePermissions`);
    }

    const resourceComponents = extractIdAndModel(plugin, resourceDocument);
    const subjectComponents = extractIdAndModel(plugin, subjectDocument);

    validateAsResource(plugin, resourceComponents.$model);

    // set the permission
    try {
      await PermissionsModel.db.findOneAndUpdate(
        {
          subjectId: subjectComponents.$uid,
          resourceId: resourceComponents.$uid
        },
        {
          $setOnInsert: {
            subjectId: subjectComponents.$uid,
            resourceId: resourceComponents.$uid,
            subjectType: subjectComponents.$model.def.name,
            resourceType: resourceComponents.$model.def.name
          },
          $set
        },
        { upsert: true }
      );
    } catch (error) {
      // hack for https://jira.mongodb.org/browse/SERVER-14322
      if (attempt < 10 && /E11000 duplicate key error/.test(error.message)) {
        return (await new Promise<Tyr.Document | null>((resolve, reject) => {
          setTimeout(() => {
            PermissionsModel.updatePermissions(
              resourceDocument,
              permissionChanges,
              subjectDocument,
              attempt++
            )
              .then(resolve)
              .catch(reject);
          }, 100);
        })) as Tyr.Document;
      } else if (/E11000 duplicate key error/.test(error.message)) {
        plugin.error(
          `Attempted to update permission 10 times, but recieved "E11000 duplicate key error" on each attempt`
        );
      }
      throw new Error(error);
    }

    if (typeof resourceDocument === 'string') {
      return Tyr.byUid(resourceDocument);
    } else {
      return resourceDocument;
    }
  }
开发者ID:CrossLead,项目名称:tyranid-gracl,代码行数:80,代码来源:PermissionsModel.ts

示例3: query

export async function query(
  plugin: GraclPlugin,
  queriedCollection: Tyr.CollectionInstance,
  permissionType: string,
  subjectDocument = Tyr.local.user
): Promise<boolean | {}> {
  const queriedCollectionName = queriedCollection.def.name;

  if (plugin.unsecuredCollections.has(queriedCollectionName)) {
    plugin.log(
      `skipping query modification for ${queriedCollectionName} as it is flagged as unsecured`
    );
    return {};
  }

  if (!permissionType) {
    plugin.error(`No permissionType given to GraclPlugin.query()`);
  }

  if (!plugin.graclHierarchy) {
    plugin.error(
      `Must call GraclPlugin.boot() before using GraclPlugin.query()`
    );
  }

  // ensure that permission exists before trying to filter query
  validatePermissionExists(plugin, permissionType);

  const components = parsePermissionString(plugin, permissionType);

  if (components.action) {
    permissionType = formatPermissionType(plugin, {
      action: components.action,
      collection: components.collection || queriedCollectionName
    });
  } else {
    plugin.error(`no action for permission ${permissionType}`);
  }

  // if no subjectDocument, no restriction...
  if (!subjectDocument) {
    plugin.log(
      `No subjectDocument passed to GraclPlugin.query() (or found on Tyr.local) -- no documents allowed`
    );
    return false;
  }

  if (!subjectDocument.$model) {
    plugin.error(
      `The subjectDocument passed to GraclPlugin.query() must be a tyranid document!`
    );
  }

  if (!plugin.graclHierarchy.resources.has(queriedCollectionName)) {
    plugin.log(
      `Querying against collection (${queriedCollectionName}) with no resource class -- no restriction enforced`
    );
    return {};
  }

  // get all permission actions in order...
  const permissionTypes = [permissionType].concat(
    getPermissionParents(plugin, permissionType)
  );

  /**
   *  Iterate through permissions action hierarchy, getting access
   */
  const getAccess = (permission: Permission) => {
    let perm: boolean | undefined;
    for (const type of permissionTypes) {
      if (permission.access && type && permission.access[type] === true) {
        // short circuit on true
        return true;
      } else if (
        permission.access &&
        type &&
        permission.access[type] === false
      ) {
        // continue on false, as superior permissions may be true
        perm = false;
      }
    }
    return perm;
  };

  // extract subject and resource Gracl classes
  const ResourceClass = plugin.graclHierarchy.getResource(
    queriedCollectionName
  );
  const SubjectClass = plugin.graclHierarchy.getSubject(
    subjectDocument.$model.def.name
  );
  const subject = new SubjectClass(subjectDocument);

  plugin.log(
    `restricting query for collection = ${queriedCollectionName} ` +
      `permissionType = ${permissionType} ` +
      `subject = ${subject.toString()}`
  );
//.........这里部分代码省略.........
开发者ID:CrossLead,项目名称:tyranid-gracl,代码行数:101,代码来源:query.ts


注:本文中的tyranid.Tyr类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。