import { ClientRepository, CollectionRepository, ItemRepository, PermissionTypeEnum, PieContentRepository, SearchSchemaRepository, } from "@pie-api-gcp/datastore/repositories"; import { AuthInfo, getScopeVal } from "@pie-api-gcp/shared/auth"; import { getLogger } from "@pie-api-gcp/shared/logging"; import { gql } from "apollo-server"; import { DocumentNode } from "graphql"; import { PermissionEvaluatorService, CollectionService, CollectionMemberService, } from "@pie-api-gcp/datastore/services"; import { ItemSerializer, PieContentSerializer } from "@pie-api-gcp/datastore/serializers"; import { forEachAsync } from "@pie-api-gcp/shared/util"; import { argShouldMatchScope } from "../auth"; import { AuthorizationError, ExposedError } from "../errors"; import { GraphQLSchemaFactory, ResultFunctionContext, GraphQLSchemaElements } from "../types"; import { protectedResolver, adminOnlyResolver } from "../resolver"; const logger = getLogger(); const Schema = gql` type Collection { id: ID! name: String! } extend type Organization { collections: [Collection] } input CreateCollectionInput { id: ID name: String! organizationId: String } input ContentItemCollectionInput { collectionId: String! contentItemId: String! } input StimulusCollectionInput { collectionId: String! stimulusId: String! } extend type Query { collection(id: ID!): Collection allCollections: [Collection] contentItemsForCollection(collectionId: ID!): [ContentItem] isContentItemInCollection(collectionId: ID!, contentItemId: ID!): Boolean stimuliForCollection(collectionId: ID!): [ContentItem] isStimulusInCollection(collectionId: ID!, stimulusId: ID!): Boolean schemasForCollection(collectionId: ID!): [SearchSchema] isSchemaInCollection(collectionId: ID!, schemaId: ID!): Boolean } extend type Mutation { createCollection(input: CreateCollectionInput): Collection deleteCollection(id: ID!): Boolean addSchemaToCollection(collectionId: String!, schemaId: SchemaIdInput!): Boolean removeSchemaFromCollection(collectionId: String!, schemaId: SchemaIdInput!): Boolean addContentItemToCollection(input: ContentItemCollectionInput): Boolean removeContentItemFromCollection(input: ContentItemCollectionInput): Boolean addStimulusToCollection(input: StimulusCollectionInput): Boolean removeStimulusFromCollection(input: StimulusCollectionInput): Boolean } `; interface ContentItemCollectionInput { collectionId: string; contentItemId: string; } interface StimulusCollectionInput { collectionId: string; stimulusId: string; } interface SchemaCollectionInput { collectionId: string; schemaId: string; } const collection = protectedResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { id } = args; const { apiClientId, organizationId, admin } = authInfo; const collection = await CollectionRepository.findById(id); if (admin) { return collection; } // NOTE [Eelco] while this could be put in an authorization function, that would mean // the collection would have to be loaded twice. It also doesn't improve the readability // that much, so having this kind of authorization code in result functions directly is fine. if (!(await CollectionRepository.isCollectionInOrganizationScope(id, organizationId))) { throw new AuthorizationError("You are not authorized for this resource"); } const client = await ClientRepository.findById(apiClientId); const permissionService = new PermissionEvaluatorService(); if (!(await permissionService.checkRules(client, collection, PermissionTypeEnum.READ))) { throw new AuthorizationError("You don't have access to this resource"); } return collection; }, argShouldMatchScope("id", "api.collectionId")); const allCollections = protectedResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { apiClientId, organizationId, admin } = authInfo; const collectionIdInScope = getScopeVal(authInfo.scopes, "api.collectionId"); const collectionService = new CollectionService(); const permissionService = new PermissionEvaluatorService(); if (collectionIdInScope) { const collection = await CollectionRepository.findById(collectionIdInScope); if (!admin) { const client = await ClientRepository.findById(apiClientId); if ( !(await permissionService.checkRules(client, collection, PermissionTypeEnum.READ)) || !(await CollectionRepository.isCollectionInOrganizationScope(collectionIdInScope, organizationId)) ) { throw new AuthorizationError(`client does not have access to collection ${collectionIdInScope}`); } } return [collection]; } // for admins return all collections // TODO [Eelco] we absolutely need paging here! const collections = await collectionService.findAllByOrganization(organizationId); if (admin) { return collections; } // for regular users get only collections with appropriate READ access; const client = await ClientRepository.findById(apiClientId); return Promise.all( collections.filter(async (collection) => permissionService.checkRules(client, collection, PermissionTypeEnum.READ)) ); }); const createCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { input } = args; if (!input.organizationId) { input.organizationId = authInfo.organizationId; } return CollectionRepository.upsert(input); }); const deleteCollection = adminOnlyResolver(async (root, args, context) => { const { id } = args; return CollectionRepository.delete(id); }); const isContentItemInCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { collectionId, contentItemId } = args; // note that contentItemId should be the baseId const item = await ItemRepository.findWithVersion(contentItemId); const collectionMemberSvc = new CollectionMemberService(); return collectionMemberSvc.isMemberInCollection(collectionId, item); }); const contentItemsForCollection = protectedResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { collectionId } = args; const collectionMemberSvc = new CollectionMemberService(); const items = await collectionMemberSvc.getMembersInCollection(collectionId, ItemRepository.TYPE); return forEachAsync(items, async (i) => ItemSerializer.serialize(i)); }); const isStimulusInCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { collectionId, stimulusId } = args; // note that stimulusId should be the baseId const item = await PieContentRepository.findWithVersion(stimulusId); const collectionMemberSvc = new CollectionMemberService(); return collectionMemberSvc.isMemberInCollection(collectionId, item); }); const stimuliForCollection = protectedResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { collectionId } = args; const collectionMemberSvc = new CollectionMemberService(); const stimuli = await collectionMemberSvc.getMembersInCollection(collectionId, PieContentRepository.TYPE); return forEachAsync(stimuli, async (s) => PieContentSerializer.serialize(s)); }); const isSchemaInCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { collectionId, schemaId } = args; const schema = await SearchSchemaRepository.findById(schemaId); const collectionMemberSvc = new CollectionMemberService(); return collectionMemberSvc.isMemberInCollection(collectionId, schema); }); const schemasForCollection = protectedResolver(async (root, args, context) => { const { collectionId } = args; const collectionMemberSvc = new CollectionMemberService(); const schemas = await collectionMemberSvc.getMembersInCollection(collectionId, SearchSchemaRepository.TYPE); return schemas; }); const addContentItemToCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: ContentItemCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const item = await ItemRepository.findWithVersion(input.contentItemId); logger.debug(`[addContentItemToCollection] adding item ${item.baseId} to collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.addMemberToCollection(collection.id, item); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const removeContentItemFromCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: ContentItemCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const item = await ItemRepository.findWithVersion(input.contentItemId); logger.debug(`[removeContentItemFromCollection] removing item ${item.baseId} from collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.removeMemberFromCollection(collection.id, item); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const addStimulusToCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: StimulusCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const c = await PieContentRepository.findWithVersion(input.stimulusId); logger.debug(`[addStimulusToCollection] adding stimulus ${c.baseId} to collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.addMemberToCollection(collection.id, c); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const removeStimulusFromCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: StimulusCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const c = await PieContentRepository.findWithVersion(input.stimulusId); logger.debug(`[removeStimulusFromCollection] removing stimulus ${c.baseId} from collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.removeMemberFromCollection(collection.id, c); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const addSchemaToCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: SchemaCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const schema = await SearchSchemaRepository.findById(input.schemaId); logger.debug(`[addSchemaToCollection] adding search schema ${schema.id} from collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.addMemberToCollection(collection.id, schema); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const removeSchemaFromCollection = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const input: SchemaCollectionInput = args.input; const collection = await CollectionRepository.findById(input.collectionId); if (collection) { const schema = await SearchSchemaRepository.findById(input.schemaId); logger.debug(`[removeSchemaFromCollection] removing search schema ${schema.id} from collection ${collection.id}`); const collectionMemberSvc = new CollectionMemberService(); await collectionMemberSvc.removeMemberFromCollection(collection.id, schema); return true; } throw new ExposedError(`collection ${input.collectionId} not found`); }); const getSchemaIdStruct = async (token: AuthInfo): Promise => { const searchSchemas = await token.searchSchemas(); // logger.debug(`searchSchemas: ${JSON.stringify(searchSchemas, null, 2)}`); return gql(` enum SchemaIdInput { ${"".concat(...searchSchemas.map((s) => `\n\t${s.id}`))} } `); }; const Organization = { async collections(organization, _, context) { const svc = new CollectionService(); return svc.findAllByOrganization(organization.id); }, }; const schemaFactory: GraphQLSchemaFactory = async (token: AuthInfo): Promise => ({ typeDefs: [Schema, await getSchemaIdStruct(token)], resolvers: { Query: { collection, allCollections, isContentItemInCollection, contentItemsForCollection, isStimulusInCollection, stimuliForCollection, isSchemaInCollection, schemasForCollection, }, Mutation: { createCollection, deleteCollection, addContentItemToCollection, removeContentItemFromCollection, addStimulusToCollection, removeStimulusFromCollection, addSchemaToCollection, removeSchemaFromCollection, }, Organization, }, }); export default schemaFactory;