Reputation: 5226
I have a nestjs app that currently has a user and company entity and each company has an owner user.
In my case, I want to write a custom decorator to use in each controller method to see if the user is the owner of that company or not.
so I start writing custom Guard like this:
@Injectable()
export class CompanyGuard implements CanActivate {
constructor() { }
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const user = request.user;
if (user) {
console.log(user);
return true;
} else {
throw new HttpException('you have no access to this company', HttpStatus.UNAUTHORIZED)
}
}
}
and I use it like this:
@UseGuards(JwtAuthGuard, CompanyGuard)
@Post('get-data/:companyId/')
getData(@Req() request){}
i want to access mongoose database in CompanyGuard and check the access in database how can i do that?
Upvotes: 0
Views: 2352
Reputation: 60357
Dependency injection works in Guards
the same way it does in any other provider (service). So you can just inject the model you want via the constructor:
constructor(@InjectModel(Company.name) private companyModel: Model<company>) {}
Upvotes: 4