Authentication
You can authorize your generated APIs by defining decorators
in your DryerModule.register
.
Below is an example of using NestJS
Guard
to authorize your APIs.
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
@Injectable()
export class AdminOnly implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
return (
GqlExecutionContext.create(context)
.getContext()
.req.header('user-role') === 'admin'
);
}
}
@Injectable()
export class UserOnly implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const role = GqlExecutionContext.create(context)
.getContext()
.req.header('user-role');
return role === 'admin' || role === 'user';
}
}
@Definition()
class Announcement {
@Id()
id: ObjectId;
@Property()
name: string;
}
@Module({
imports: [
// will be other imports as well
DryerModule.register({
definitions: [
{
definition: Announcement,
decorators: {
write: [UseGuards(AdminOnly)],
read: [UseGuards(UserOnly)],
},
},
],
}),
],
})
export class AppModule {}
The example above will:
- Get user role from
user-role
header - Only allow
admin
towrite
Announcement
- Only allow
user
toread
Announcement
You can use default
, write
, read
to reduce the amount of decorators you need to write.
More specific decorators will override less specific decorators.
Below is the definition of decorators
:
decorators?: {
default?: MethodDecorator | MethodDecorator[];
write?: MethodDecorator | MethodDecorator[];
read?: MethodDecorator | MethodDecorator[];
findOne?: MethodDecorator | MethodDecorator[];
list?: MethodDecorator | MethodDecorator[];
findAll?: MethodDecorator | MethodDecorator[];
paginate?: MethodDecorator | MethodDecorator[];
remove?: MethodDecorator | MethodDecorator[];
update?: MethodDecorator | MethodDecorator[];
create?: MethodDecorator | MethodDecorator[];
bulkCreate?: MethodDecorator | MethodDecorator[];
bulkUpdate?: MethodDecorator | MethodDecorator[];
bulkRemove?: MethodDecorator | MethodDecorator[];
}
💡
DryerJS
totally relies on NestJS
to implement Authentication & Authentication. Learn more:
Example
There is an more real-world example on JWT recipe.
Other decorators
decorators
is not for authentication only. You can use it to add other decorators to your generated resolvers.
import { UseInterceptors } from '@nestjs/common';
@Definition()
class Announcement {}
@Module({
imports: [
// will be other imports as well
DryerModule.register({
definitions: [
{
definition: Announcement,
decorators: {
default: [UseInterceptors(LoggingInterceptor)],
},
},
],
}),
],
})
export class AppModule {}
You can find LoggingInterceptor implementation here (opens in a new tab)