當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。