Authorization
In VitNode we're implementing a custom authorization system, which gives us more flexibility and control over the authorization process. Our system use Guards (opens in a new tab) from NestJS to protect routes.
Portected route
To protect a route, you need to add the @UseGuards(AuthGuards)
decorator to the route handler. This will make sure that the user is authenticated before accessing the route.
Here is an example for resolver:
import { AuthGuards } from '@/utils/guards/auth.guards';
@Query(() => ShowCoreMembersObj)
@UseGuards(AuthGuards)
async core_members__show(@Args() args: ShowCoreMembersArgs): Promise<ShowCoreMembersObj> {
return await this.service.show(args);
}
If you need to protected a route with admin permissions you need to use the
@UseGuards(AdminAuthGuards)
decorator.
Current user data
Whan you are using AuthGuards
you can access to the current user in the resolver by using the @CurrentUser()
decorator as param route.
import { CurrentUser, User } from '@/utils/decorators/user.decorator';
@Query(() => ShowCoreMembersObj)
@UseGuards(AuthGuards)
async core_members__show(
@Args() args: ShowCoreMembersArgs,
@CurrentUser() user: User
): Promise<ShowCoreMembersObj> {
return await this.service.show(args);
}
Current user data withouth protected route
If you need to access to the current user in a route you need use the @OptionalAuth()
decorator in route. You need change @CurrentUser()
decorator to optional param route.
import { AuthGuards, OptionalAuth } from '@/utils/guards/auth.guards';
import { CurrentUser, User } from '@/utils/decorators/user.decorator';
@Query(() => ShowCoreMembersObj)
@OptionalAuth()
@UseGuards(AuthGuards)
async core_members__show(
@Args() args: ShowCoreMembersArgs,
@CurrentUser() user: User | null
): Promise<ShowCoreMembersObj> {
return await this.service.show(args);
}