DEV Community

prasanna malla
prasanna malla

Posted on

Adding permissions for Vendure plugins

Adding permissions for your custom functionality is important for improving the security, compliance, customization, and control of an application. By adding custom permissions, you can create a more personalized and flexible experience for your users and helps you control access to specific features or functionality within your application. Manage user roles, delegating tasks, and ensure that only authorized individuals have access to sensitive data and specified functionality.

In Vendure we can create PermissionDefinitions to create new permissions and require them to specific queries /mutations. Let's create a permission for setting an API key

// apikey-permission.ts

import { PermissionDefinition } from '@vendure/core';

export const apiKey = new PermissionDefinition({
    name: 'SetApiKey',
    description: 'Allows setting API key',
});
Enter fullscreen mode Exit fullscreen mode

Now, we can use @Allow() decorator to limit access to the mutation

// apikey.resolver.ts

import { Allow } from '@vendure/core';
import { Mutation, Resolver } from '@nestjs/graphql';
import { apiKey } from './apikey-permission';

@Resolver()
export class ApiKeyResolver {

  @Allow(apiKey.Permission)
  @Query()
  apiKey() {
    // ...
  }

  @Allow(apiKey.Permission)
  @Mutation()
  setApiKey() {
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

And to register apiKey permission in Vendure we pass it to VendureConfig

// apikey.plugin.ts

import gql from 'graphql-tag';
import { VendurePlugin } from '@vendure/core';
import { ApiKeyResolver } from './apikey.resolver'
import { apiKey } from './apiKey-permission';

@VendurePlugin({
  adminApiExtensions: {
    schema: gql`
      type ApiKey {
        id: ID!
        apiKey: String!
      }

      input ApiKeyInput {
        apiKey: String
      }

      extend type Query {
          apiKey: ApiKey
      }

      extend type Mutation {
        setApiKey(input: ApiKeyInput!): ApiKey!
      }
    `,
    resolvers: [ApiKeyResolver]
  },
  configuration: config => {
    config.authOptions.customPermissions.push(apiKey);
    return config;
  },
})
export class ApiKeyPlugin {}
Enter fullscreen mode Exit fullscreen mode

Finally, apiKey permission can be found in the Role detail view of the Admin UI for superadmin, and can be assigned to other Roles as required.

When requiring separate permissions for create, read, update and delete we can use CrudPermissionDefinition which simplifies the creation of the set of 4 CRUD permissions.👌

Top comments (0)