Issue
I have an UserService
which is exported from user module like this:
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
MongooseModule.forFeature([{ name: Profile.name, schema: ProfileSchema }]),
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
RolesGaurd
@Injectable()
export class RolesGuard implements CanActivate {
constructor(
private reflector: Reflector,
@Inject(UserService) private readonly userService: UserService,
) {}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const roles = this.reflector.get(Roles, context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
const params = request.params;
if (!roles.includes(user.role)) {
throw new UnauthorizedException(
'You are not authorized to access this api endpoint',
);
}
if (user.role === Role.ACCOUNT_MANAGER && params.organization) {
// check if account manager is assigned a queried organization
const isAssigned = this.userService.hasAccessToOrganization(
user.userId,
params.organization,
);
if (!isAssigned)
throw new UnauthorizedException(
'You are not authorized to perform action for this organization',
);
}
return true;
}
}
When I inject user service in roles gaurd I start to get this error for every module in which I am using RolesGaurd:
Error: Nest can't resolve dependencies of the RolesGuard (Reflector, ?). Please make sure that the argument UserService at index [1] is available in the CoachModule context.
Potential solutions:
- Is CoachModule a valid NestJS module?
- If UserService is a provider, is it part of the current CoachModule?
- If UserService is exported from a separate @Module, is that module imported within CoachModule?
@Module({
imports: [ /* the Module containing UserService */ ]
})
What is the solution for this problem so that I won't need to add user service import to every module in which I am using RolesGaurd
Solution
you must have that provider available to all modules that is using the RolesGuard
guard
So you should:
- import a module that exports
UserService
, in every module that will use the guard, or - import a global module that exports
UserService
in the root module, or - register that provider in every module that will use the guard
Answered By - Micael Levi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.