Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

authorization resolver #4798

Merged
merged 7 commits into from
Dec 20, 2024
Merged

authorization resolver #4798

merged 7 commits into from
Dec 20, 2024

Conversation

valentinyanakiev
Copy link
Member

@valentinyanakiev valentinyanakiev commented Dec 19, 2024

image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new GraphQL object type for querying user privileges.
    • Added a new resolver class to handle user privilege queries across various entities.
    • Implemented multiple methods to retrieve user privileges for different resources.
  • Bug Fixes

    • Ensured proper authorization checks are performed when querying privileges.

Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces a new system for querying user privileges through GraphQL. It adds a new TypeScript class LookupMyPrivilegesQueryResults to define the structure of privilege data. Additionally, a new resolver class LookupMyPrivilegesResolverFields is created to handle various privilege queries across different entity types, including methods for checking user privileges. The LookupModule is updated to include the new resolver, enhancing the overall functionality of user privilege lookups within the application.

Changes

File Change Summary
src/services/api/lookup/dto/lookup.query.my.privileges.results.ts New DTO class LookupMyPrivilegesQueryResults defining GraphQL object type for user privileges
src/services/api/lookup/lookup.module.ts Added LookupMyPrivilegesResolverFields to module providers
src/services/api/lookup/lookup.resolver.fields.ts Added myPrivileges() method and import for LookupMyPrivilegesQueryResults
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts New resolver class LookupMyPrivilegesResolverFields with multiple methods for checking privileges across various entity types

Possibly Related PRs

Suggested Reviewers

  • Comoque1

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@techsmyth techsmyth marked this pull request as ready for review December 20, 2024 18:09
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (2)

44-74: Constructor has too many dependencies.

This large constructor with many injected services can become difficult to maintain and test. Consider refactoring into smaller services or employing a dedicated facade to reduce complexity and improve readability.


92-427: Consider abstracting repetitive field resolvers.

Multiple resolvers follow the same pattern of retrieving the entity with authorization relations and returning privileges. Extracting a generic method or leveraging a map-based approach could eliminate duplication and reduce boilerplate.

src/services/api/lookup/dto/lookup.query.my.privileges.results.ts (1)

4-17: Consider adding documentation for each field.

Though the fields are self-explanatory, adding short JSDoc or GraphQL field descriptions would clarify how each privilege array is intended to be used. This can reduce ambiguity for clients and future maintainers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6dabcba and a91aabc.

📒 Files selected for processing (4)
  • src/services/api/lookup/dto/lookup.query.my.privileges.results.ts (1 hunks)
  • src/services/api/lookup/lookup.module.ts (2 hunks)
  • src/services/api/lookup/lookup.resolver.fields.ts (2 hunks)
  • src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
src/services/api/lookup/dto/lookup.query.my.privileges.results.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs.

Context Files (Do Not Review):

  • docs/Design.md - Design overview of the project
  • docs/Pagination.md - Pagination design overview
  • docs/Developing.md - Development setup overview
  • docs/graphql-typeorm-usage.md - overview of GraphQL and TypeORM usage and how they are used together with NestJS in the project
  • docs/database-definitions.md - guidelines for creating TypeORM entity defnitions
  • src/core/error-handling/graphql.exception.filter.ts - GraphQL error handling
  • src/core/error-handling/http.exception.filter.ts - HTTP error handling
  • src/core/error-handling/rest.error.response.ts - REST error response
  • src/core/error-handling/unhandled.exception.filter.ts - Global exception handler

Guidelines:

  • Our project uses global exception handlers (UnhandledExceptionFilter), so avoid suggesting additional try/catch blocks unless handling specific cases.
  • Use NestJS latest documentation from https://docs.nestjs.com/ for reference on NestJS best practices.
  • Use TypeORM latest documentation from https://typeorm.io/ for reference on TypeORM best practices.
  • Refer to the design overview in the context files for better understanding.
src/services/api/lookup/lookup.module.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs.

Context Files (Do Not Review):

  • docs/Design.md - Design overview of the project
  • docs/Pagination.md - Pagination design overview
  • docs/Developing.md - Development setup overview
  • docs/graphql-typeorm-usage.md - overview of GraphQL and TypeORM usage and how they are used together with NestJS in the project
  • docs/database-definitions.md - guidelines for creating TypeORM entity defnitions
  • src/core/error-handling/graphql.exception.filter.ts - GraphQL error handling
  • src/core/error-handling/http.exception.filter.ts - HTTP error handling
  • src/core/error-handling/rest.error.response.ts - REST error response
  • src/core/error-handling/unhandled.exception.filter.ts - Global exception handler

Guidelines:

  • Our project uses global exception handlers (UnhandledExceptionFilter), so avoid suggesting additional try/catch blocks unless handling specific cases.
  • Use NestJS latest documentation from https://docs.nestjs.com/ for reference on NestJS best practices.
  • Use TypeORM latest documentation from https://typeorm.io/ for reference on TypeORM best practices.
  • Refer to the design overview in the context files for better understanding.
src/services/api/lookup/lookup.resolver.fields.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs.

Context Files (Do Not Review):

  • docs/Design.md - Design overview of the project
  • docs/Pagination.md - Pagination design overview
  • docs/Developing.md - Development setup overview
  • docs/graphql-typeorm-usage.md - overview of GraphQL and TypeORM usage and how they are used together with NestJS in the project
  • docs/database-definitions.md - guidelines for creating TypeORM entity defnitions
  • src/core/error-handling/graphql.exception.filter.ts - GraphQL error handling
  • src/core/error-handling/http.exception.filter.ts - HTTP error handling
  • src/core/error-handling/rest.error.response.ts - REST error response
  • src/core/error-handling/unhandled.exception.filter.ts - Global exception handler

Guidelines:

  • Our project uses global exception handlers (UnhandledExceptionFilter), so avoid suggesting additional try/catch blocks unless handling specific cases.
  • Use NestJS latest documentation from https://docs.nestjs.com/ for reference on NestJS best practices.
  • Use TypeORM latest documentation from https://typeorm.io/ for reference on TypeORM best practices.
  • Refer to the design overview in the context files for better understanding.
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs.

Context Files (Do Not Review):

  • docs/Design.md - Design overview of the project
  • docs/Pagination.md - Pagination design overview
  • docs/Developing.md - Development setup overview
  • docs/graphql-typeorm-usage.md - overview of GraphQL and TypeORM usage and how they are used together with NestJS in the project
  • docs/database-definitions.md - guidelines for creating TypeORM entity defnitions
  • src/core/error-handling/graphql.exception.filter.ts - GraphQL error handling
  • src/core/error-handling/http.exception.filter.ts - HTTP error handling
  • src/core/error-handling/rest.error.response.ts - REST error response
  • src/core/error-handling/unhandled.exception.filter.ts - Global exception handler

Guidelines:

  • Our project uses global exception handlers (UnhandledExceptionFilter), so avoid suggesting additional try/catch blocks unless handling specific cases.
  • Use NestJS latest documentation from https://docs.nestjs.com/ for reference on NestJS best practices.
  • Use TypeORM latest documentation from https://typeorm.io/ for reference on TypeORM best practices.
  • Refer to the design overview in the context files for better understanding.
🔇 Additional comments (4)
src/services/api/lookup/lookup.module.ts (2)

36-36: Import statement for LookupMyPrivilegesResolverFields looks good.

No issues detected. It's properly aligned with the new provider usage.


72-77: Addition of LookupMyPrivilegesResolverFields to providers is consistent.

The new resolver is correctly added to the module’s providers array, ensuring it is available at runtime.

src/services/api/lookup/lookup.resolver.fields.ts (2)

70-70: Import of LookupMyPrivilegesQueryResults is well-defined.

No issues detected with the import statement.


149-156: Method myPrivileges is returning an empty object.

Currently, this resolver method returns an empty object cast to LookupMyPrivilegesQueryResults. Ensure correct data integration by either delegating to the new LookupMyPrivilegesResolverFields or implementing the privilege retrieval logic directly.

Comment on lines +80 to +85
if (!authorizable.authorization) {
throw new RelationshipNotFoundException(
`Unable to load Authorization for ${authorizable.constructor.name} with ID ${authorizable.id}`,
LogContext.API
);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Potential mismatch between the GraphQL return type annotation and actual return value.

The method is decorated with @ResolveField(() => IAuthorizationPolicy) but returns Promise<AuthorizationPrivilege[]>. This could lead to schema inconsistencies or confusion for clients expecting an object rather than an array of privileges.

Copy link
Member

@techsmyth techsmyth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually should help quite a bit with client lookups...

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (1)

91-105: Resolver method for 'space' is consistent but note repeated patterns.
The logic is correct for retrieving the entity and returning privileges. However, the same approach is repeated across many resolvers below, leading to duplication. Consider a generic or reusable approach to reduce boilerplate code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a91aabc and 0a85c98.

📒 Files selected for processing (1)
  • src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs.

Context Files (Do Not Review):

  • docs/Design.md - Design overview of the project
  • docs/Pagination.md - Pagination design overview
  • docs/Developing.md - Development setup overview
  • docs/graphql-typeorm-usage.md - overview of GraphQL and TypeORM usage and how they are used together with NestJS in the project
  • docs/database-definitions.md - guidelines for creating TypeORM entity defnitions
  • src/core/error-handling/graphql.exception.filter.ts - GraphQL error handling
  • src/core/error-handling/http.exception.filter.ts - HTTP error handling
  • src/core/error-handling/rest.error.response.ts - REST error response
  • src/core/error-handling/unhandled.exception.filter.ts - Global exception handler

Guidelines:

  • Our project uses global exception handlers (UnhandledExceptionFilter), so avoid suggesting additional try/catch blocks unless handling specific cases.
  • Use NestJS latest documentation from https://docs.nestjs.com/ for reference on NestJS best practices.
  • Use TypeORM latest documentation from https://typeorm.io/ for reference on TypeORM best practices.
  • Refer to the design overview in the context files for better understanding.
🔇 Additional comments (3)
src/services/api/lookup/lookup.resolver.my.privileges.fields.ts (3)

75-89: Exceptional handling strategy is well-defined, but confirm partial loads aren't needed.
You are throwing a RelationshipNotFoundException if the authorization relation is missing. This is acceptable since a missing relation indicates a broken use case. Just confirm you do not require a scenario to return partial data when the relation is absent.


79-84: Past Mismatch Issue No Longer Present
A previous review flagged a mismatch between the decorator return type and the actual return value. In the current version, the return type is an array of AuthorizationPrivilege while the decorator is set to [AuthorizationPrivilege], so this mismatch is resolved.


1-40: Ensure consistent import usage and remove any unused imports if necessary.
Although these service imports seem relevant, confirm that no import is unused or can be omitted. Maintaining a clean import list supports code clarity and prevents dead dependencies.

✅ Verification successful

All imported services are actively used in the resolver class

After reviewing the complete file content, all imported services are properly injected in the constructor and used in corresponding resolver methods. Each service is used to fetch entities and check privileges. There are no unused imports in this file.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if all imported services are used within this file.
# Utilizing 'rg' to search for references of these services.
rg "new (CommunityService|CollaborationService|ContextService|ProfileService|PostService|CalloutService|InnovationFlowService|RoomService|CalendarEventService|CalendarService|ApplicationService|InvitationService|WhiteboardService|DocumentService|StorageAggregatorService|UserService|SpaceService|CommunityGuidelinesService|VirtualContributorService|StorageBucketService|InnovationHubService|InnovationPackService|AccountService|TemplateService|TemplatesSetService|TemplatesManagerService|RoleSetService|LicenseService)\(" -A 5

Length of output: 528


Script:

#!/bin/bash
# Let's try a different approach to find service usage
# First, let's get the full content of the file to see the class implementation
cat src/services/api/lookup/lookup.resolver.my.privileges.fields.ts

# As a backup, let's also search for any usage of these services without the "new" keyword
rg -l "CommunityService|CollaborationService|ContextService|ProfileService|PostService|CalloutService|InnovationFlowService|RoomService|CalendarEventService|CalendarService|ApplicationService|InvitationService|WhiteboardService|DocumentService|StorageAggregatorService|UserService|SpaceService|CommunityGuidelinesService|VirtualContributorService|StorageBucketService|InnovationHubService|InnovationPackService|AccountService|TemplateService|TemplatesSetService|TemplatesManagerService|RoleSetService|LicenseService" src/services/api/lookup/lookup.resolver.my.privileges.fields.ts

Length of output: 19983

Comment on lines +91 to +521
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, room);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified InnovationFlow',
})
async innovationFlow(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const innovationFlow =
await this.innovationFlowService.getInnovationFlowOrFail(id, {
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, innovationFlow);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified Template',
})
async template(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const template = await this.templateService.getTemplateOrFail(id, {
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, template);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified TemplatesSet',
})
async templatesSet(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const templatesSet = await this.templatesSetService.getTemplatesSetOrFail(
id,
{ relations: { authorization: true } }
);

return this.getMyPrivilegesOnAuthorizable(agentInfo, templatesSet);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified TemplatesManager',
})
async templatesManager(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const templatesManager =
await this.templatesManagerService.getTemplatesManagerOrFail(id, {
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, templatesManager);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified Community guidelines',
})
async communityGuidelines(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const guidelines =
await this.guidelinesService.getCommunityGuidelinesOrFail(id, {
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, guidelines);
}

@ResolveField(() => [AuthorizationPrivilege], {
nullable: true,
description: 'Lookup myPrivileges on the specified License',
})
async license(
@CurrentUser() agentInfo: AgentInfo,
@Args('ID', { type: () => UUID }) id: string
): Promise<AuthorizationPrivilege[]> {
const license = await this.licenseService.getLicenseOrFail(id, {
relations: { authorization: true },
});

return this.getMyPrivilegesOnAuthorizable(agentInfo, license);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Reduce duplication across multiple resolver methods.
All the entity-specific resolvers follow the same pattern of:

  1. Fetching the entity with { relations: { authorization: true } }
  2. Returning getMyPrivilegesOnAuthorizable(agentInfo, entity).

Consider implementing a higher-order function or a generic approach that reuses this pattern, accepting the relevant service method and entity ID. This would consolidate logic, improve readability, and facilitate easier maintenance.

-  async space(@CurrentUser() agentInfo: AgentInfo, @Args('ID') id: string) {
-    const space = await this.spaceService.getSpaceOrFail(id, { relations: { authorization: true } });
-    return this.getMyPrivilegesOnAuthorizable(agentInfo, space);
-  }
-  ...
+  private async fetchPrivileges<T extends IAuthorizable>(
+    serviceMethod: (id: string, options?: any) => Promise<T>,
+    agentInfo: AgentInfo,
+    id: string,
+  ): Promise<AuthorizationPrivilege[]> {
+    const entity = await serviceMethod(id, { relations: { authorization: true } });
+    return this.getMyPrivilegesOnAuthorizable(agentInfo, entity);
+  }
+
+  @ResolveField(() => [AuthorizationPrivilege], { nullable: true })
+  async space(@CurrentUser() agentInfo: AgentInfo, @Args('ID') id: string) {
+    return this.fetchPrivileges(this.spaceService.getSpaceOrFail.bind(this.spaceService), agentInfo, id);
+  }
+  // ... apply pattern to other resolvers

Committable suggestion skipped: line range outside the PR's diff.

@techsmyth techsmyth merged commit 6c886d7 into develop Dec 20, 2024
3 checks passed
@techsmyth techsmyth deleted the authorization-lookup branch December 20, 2024 18:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants