'How to get only currentUser related content in NestJs with prisma

Im creating a multi company app which logged user will only have access to his content. At the moment i don't want to implement multi tentant in this app.

I have created a Decorator to get the current logged user:

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.user;
  },
);

And used this decorator on my controller actions to get the companyId of the user and pass this ID to the service.

 @Get()
  async getAll(
    @CurrentUser()
    currentUser,
  ) {
    return this.categoryService.getAll(currentUser.companyId);
  }

Now, on service i have access to the companyId and can access his content:

  async getAll(companyId: string) {
    const categories = await this.prisma.category.findMany({
      where: { companyId: companyId },
    });

    return categories;
  }

The BIG problem is that i will have to repeat this process in every controller, services and etc.

Is there any easier way to do this? Anything i can use on the service level? How can i solve this?



Solution 1:[1]

Hello, one of the simplest ways to do this is userGuard, you need jwt token to use it. Now you may be wondering what useguards are and how they are used.I want to give to you real example,

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy,ExtractJwt } from "passport-jwt";


@Injectable()
export class  JwtStrategy extends PassportStrategy(Strategy,'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'super-secret-cat',
    });
  }
  async validate(payload: any) {
    
 
    return payload
  }
}

This is a simple JWT guard.First checks for jwt login, then using

@UseGuards(AuthGuard("jwt")

You verify your authenticates the user For more information https://docs.nestjs.com/guards

Solution 2:[2]

Not sure what you want to achieve exactly, but I will do this:

/* File: CategoryService.ts */

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';

@Injectable({ scope: Scope.REQUEST })
export class CategoryService {
  // declare your variables/properties

  constructor(@Inject(REQUEST) private request: Request) {

  }

  // get current user
  getCurrentUserCompanyId() {
    return this.request.user['companyId'];
  }

  async getAll() {
    const categories = await this.prisma.category.findMany({
      where: { companyId: this.getCurrentUserCompanyId() },
    });

    return categories;
  }
}


/* File: category.controller.ts */
@Controller('category')
export class CategoryController {

  constructor(private categoryService: CategoryService) {}

  @Get()
  async getAll() {
    return this.categoryService.getAll();
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mustafa Kendigüzel
Solution 2