Adding permissions for Vendure plugins
prasanna malla
Posted on April 27, 2023
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',
});
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() {
// ...
}
}
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 {}
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.👌
Posted on April 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.