I have a guard that checks the ownership of a resource. If the user is the owner (created that resource), then he can access (update, read, delete).
Each resource is handled by its own service (comments is handled by the CommentsModule which has the CommentsService and so on). Each service that handles a resource with ownership implements a function called hasOwnership and the guard will call said function.
If possible, I would like my guard to inject the correct service depending on the controller that is calling it. So, if CommentsController is calling the guard, then it should inject and use CommentsService.hasOwnership.
I have tried using dynamic modules to inject the correct module/service on the imports of ACModule which hosts the guard, but that seems to be a no go as I can't properly handle the circular dependencies.
Injecting every service into the guard and selecting the correct will be very troublesome to mantain, due to the circular dependencies.
Is there a better way? This would be the desirable behavior.
#Injectable()
export default class ACGuard implements CanActivate {
constructor(
#Inject('SERVICE_KEY') private correctService
) {}
canActivate(context: ExecutionContext) {
return await correctService.hasOwnership();
}
}
Because you need a different service at run time (instead of at compile time) you are going to need to take a factory approach. It is a little troublesome to maintain as new resources are added but that's the trade-off you have to make.
First thing I would do is create a factory class to determine which service is the correct service to use based on the ExecutionContext:
export interface IService {
hasOwnership() : Promise<boolean>;
}
#Injectable()
export class ServiceFactory {
//Make sure every service returned from this method implements the "IService" interface
public getCorrectService(context: ExecutionContext) : IService {
if(context...) {
return new CommentsService();
} else if(context...) {
return new SomeOtherService();
}
}
}
Now you can inject that factory into your guard to get the correct service:
#Injectable()
export default class ACGuard implements CanActivate {
constructor(private serviceFactory: ServiceFactory) {}
canActivate(context: ExecutionContext) {
//Here's where the magic of this happens...
const correctService: Iservice = this.serviceFactory.getCorrectService(context);
return await correctService.hasOwnership();
}
}
Related
In angular we can manually access and inject dependencies using the built in Injector class. By which you can access Injectables and Inject them without actually passing them in the constructor. Basically I want to inject a service to another service without passing it as an arg to the constructor.
This is the angular equivalent Inject a service manually
I wanted to achieve similar thing in nestjs
Note : The service to be injected also has a dependency, so I can't just instantiate it
I believe what you're looking for is Nest's ModuleRef class, where you can do something like the following:
#Injectable()
export class CatsService implements OnModuleInit {
private service: Service;
constructor(private moduleRef: ModuleRef) {}
onModuleInit() {
this.service = this.moduleRef.get(Service);
}
}
Where Service should actually be the class you are wanting to inject.
I think #Inject('token') should work as you expected
import { Injectable, Inject } from '#nestjs/common';
#Injectable()
export class HttpService<T> {
#Inject('HTTP_OPTIONS')
private readonly httpClient: T;
}
ref: https://docs.nestjs.com/providers#property-based-injection
I am working with Nest.js + TypeORM and hit a snag when trying to add inheritance to service classes.
I want to have a User service class that extends off of a Base service class, inheriting all the methods the it has.
This is what I've done:
export class BaseService<T> {
private repo;
constructor(repo: Repository<T>){
this.repo = repo;
}
async findAll(opts?): Promise<T[]> {
return this.repo.find(opts);
}
......
}
Then on my User service:
export class UserService extends BaseService<User> {
constructor(
#InjectRepository(User)
private userRepository: Repository<User>,
private readonly mailerService: MailerService,
) {
super(userRepository);
}
}
This works fine where I just need a single repository in the Service class but once I need more such as productRepository, as you can see it would fail due to constructor being hardcoded to accept a single repository.
I can't seem to figure out what would be the most elegant way of achieving something like this.
Does anyone know?
It is an old thread, anyways I meat this same problem and this answer may help someone else...
You can have an abstract class with common functions and boilerplate that you wich to be available in all your repositories to maintain patterns and so on...
export abstract class BaseService<T extends ObjectLiteral> {
protected repo: Repository<T>;
async findAll(opts?): Promise<T[]> {
return this.repo.find(opts);
}
......
}
Observe that constructor is omitted here and as an abstract class you should never have an instance of it, it is meant to be just an extension with common boilerplates and features that you don't want to write every single time you need a new service with the same features like a CRUD service or so...
Then you will use it like this:
export class UserService extends BaseService<User> {
constructor(
#InjectRepository(User) protected readonly repo: Repository<User>,
private readonly mailerService: MailerService,
) {
super();
}
...... extended stuff
}
I'm not sure if you need to inject repo with the same name and visibility but as it worked for me I didn't dive any further to get to know...
The bad side of this approach to me is that even if you don't have anything else to inject via constructor in your service you need to declare constructor and inject the base repository... it is a boilerplate that could be avoided too but I couldn't achieve this right now...
I have a controller like this:
#ApiBearerAuth()
#UseGuards(AuthGuard('jwt'))
#ApiTags('books')
#Controller('books')
export class BooksController {
#Post()
async create(#Body() createBookVm: CreateBookVm) {
//........
}
#Get()
async all() {
//........
}
}
When I access all() rout in above controller without accessToken I get the foloowing error:
{"statusCode":401,"error":"Unauthorized"}
It is a correct behavior but I want ignore all() action from general #UseGuards of the controller. I want access it as a public rout without authorization.
The easiest way is to change Guards to routes:
#ApiBearerAuth()
#ApiTags('books')
#Controller('books')
export class BooksController {
#Post()
#UseGuards(AuthGuard('jwt'))
async create(#Body() createBookVm: CreateBookVm) {
//........
}
#Get()
async all() {
//........
}
}
To provide another answer, albeit one that requires more code, is you could create a custom decorator that assigns metadata to the class and/or the class method. This metadata, in theory, would be for telling the guard to skip the auth check on this entire class, or on this route (depending on how you set the metadata up), and return true so that the request can still flow.
I've got a decorator like this set up here that sets up metadata if you'd like to take a look at how it works.
With this kind of approach, you could bind the guard globally, and then add the #AuthSkip() (or whatever you call it) decorator to the routes or classes you don't want to authorize.
Now you'll need to extend the AuthGuard('jwt') and update the canActivate() method to check for this metadata in the current context. This means that you'll need to add the Reflector as a dependency to the guard class and use it to get the metadata from both the class and the current route (if you went so far as to make it work for ignoring classes and not just routes), and if the metadata exists, then the route was to be skipped, return true from the guard. I make that kind of check here if you'd like to see an example of that in action.
Assuming you have used the app.useGlobalGuards() method inside main.ts file, add the following code inside the auth.guard.ts file:
import { ExecutionContext, Injectable } from '#nestjs/common';
import { Reflector } from '#nestjs/core';
import { AuthGuard as PassportAuthGaurd } from '#nestjs/passport';
#Injectable()
export class AuthGuard extends PassportAuthGaurd('jwt') {
constructor(private readonly reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.get<boolean>(
'isPublic',
context.getHandler()
);
if (isPublic) {
return true;
}
return super.canActivate(context);
}
}
I had used pssport jwt method here, but you can alter it according to you, just remember to keep constructor and the logic of canActivate same.
Now in your main.ts modify global guard so we can use Reflectors in it:
const reflector = app.get(Reflector);
app.useGlobalGuards(new AuthGuard(reflector));
Now in order to make routes public we would use a custom decorator, for that create a file named public.decorator.ts and add the following code:
import { SetMetadata } from '#nestjs/common';
export const Public = () => SetMetadata('isPublic', true);
Here we have added a custom metadata value which is same value that we used inside our auth.guard.ts file. Now just add this #Public() decorator on the route that you want to make public:
#Get()
#Public()
async all() {
//........
}
Now your all function won't check for the token authentication.
I found this blog which does the same thing, you can check it out.
I'm writing webAPI using NestJS framework. I was not able to override global scoped guard with the one placed on method or controller level. All of my endpoints will use JWT verification guard except one used for logging into the system. Is it possible to create one guard on root level and only override this global guard with #UseGuard() decorator on single method level?
I tried to use guard before listen function call and also use APP_GUARDprovider, but in both cases I'm not able to override this behavior.
Code example:
https://codesandbox.io/embed/nest-yymkf
Just to add my 2 cents.
Instead of defining 2 guards (reject and accept) as the OP have done, I have defined a custom decorator:
import { SetMetadata } from '#nestjs/common'
export const NoAuth = () => SetMetadata('no-auth', true)
The reject guard (AuthGuard) uses Reflector to be able to access the decorator's metadata and decides to activate or not based on it.
import { CanActivate, ExecutionContext, Injectable } from '#nestjs/common'
import { Reflector } from '#nestjs/core'
import { Observable } from 'rxjs'
#Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler())
if(noAuth) return true
// else your logic here
}
}
I then bind the reject guard globally in some module:
#Module({
providers: [{
provide: APP_GUARD,
useClass: AuthGuard
}]
})
and proceed to use the decorator where needed:
#NoAuth()
#Get() // anyone can access this
getHello(): string {
return 'Hello Stranger!'
}
#Get('secret') // protected by the global guard
getSecret(): string {
return 'ssshhh!'
}
After a posting the question I figured out the solution for my problem. I should add some custom meta-data into my controller and put a logic inside the guard to read that meta-data.
I have updated the code sample.
I need to access a service (provided by Nest TypeOrmModule) inside the intercept function (important note: not as constructor parameter!!!) because it depends of the passed options (entity in this case).
The service injection token is provided by the getRepositoryToken function.
export class PaginationInterceptor {
constructor(private readonly entity: Function) {}
intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
// Here I want to inject the TypeORM repository.
// I know how to get the injection token, but not HOW to
// get the "injector" itself.
const repository = getRepositoryToken(this.entity);
// stuff...
return call$;
}
}
Is any concept of "service container" in Nest? This github issue didn't help me.
Example usage (controller action):
#Get()
#UseInterceptors(new PaginationInterceptor(Customer))
async getAll() {
// stuff...
}
Regarding dependency injection (if you really want/need it), I guess using a mixin class can do the trick. See the v4 documentation (Advanced > Mixin classes).
import { NestInterceptor, ExecutionContext, mixin, Inject } from '#nestjs/common';
import { getRepositoryToken } from '#nestjs/typeorm';
import { Observable } from 'rxjs';
import { Repository } from 'typeorm';
export function mixinPaginationInterceptor<T extends new (...args: any[]) => any>(entityClass: T) {
// declare the class here as we can't give it "as-is" to `mixin` because of the decorator in its constructor
class PaginationInterceptor implements NestInterceptor {
constructor(#Inject(getRepositoryToken(entityClass)) private readonly repository: Repository<T>) {}
intercept(context: ExecutionContext, $call: Observable<any>) {
// do your things with `this.repository`
return $call;
}
}
return mixin(PaginationInterceptor);
}
Disclaimer: this is valid TypeScript code but I didn't had the chance to test it in a real project, so it might need a bit of rework. The idea is to use it like this:
#UseInterceptors(mixinPaginationInterceptor(YourEntityClass))
Let me know if you have any question about the code. But I think the doc about mixin is pretty good!
OR You can also use getRepository from typeorm (passing the entity class). This is not DI, thus, it will oblige you to spyOn the getRepository function in order to do proper testing.
Regarding the container, I'm almost sure that the only way to access it is using the Execution Context, as pointed by Kim.