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.guard";
@Query(() => ShowCoreMembersObj)
@UseGuards(AuthGuards)
async core_members__show(@Args() args: ShowCoreMembersArgs): Promise<ShowCoreMembersObj> {
return await this.service.show(args);
}
Admin protected route
If you need to protect a route with admin
permissions you need to use the @UseGuards(AdminAuthGuards)
decorator.
import { AdminAuthGuards } from "@/utils/guards/admin-auth.guard";
@Query(() => ShowCoreMembersObj)
@UseGuards(AdminAuthGuards)
async core_members__show(@Args() args: ShowCoreMembersArgs): Promise<ShowCoreMembersObj> {
return await this.service.show(args);
}
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 without 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.guard";
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);
}