adrien2p / medusa-extender

:syringe: Medusa on steroid, take your medusa project to the next level with some badass features :rocket:
https://adrien2p.github.io/medusa-extender/
MIT License
321 stars 39 forks source link

[BUG] In the loggedInUser.middleware req.user is missing #96

Closed bibekkakati closed 2 years ago

bibekkakati commented 2 years ago

Error:

Resolution path: loggedInUser
AwilixResolutionError: Could not resolve 'loggedInUser'.

When I checked, req.user is not coming in the loggedInUser middleware.

Middleware code:

import {
  MedusaAuthenticatedRequest,
  MedusaMiddleware,
  Middleware,
} from "medusa-extender";
import { NextFunction, Response } from "express";

import UserService from "./user.service";

@Middleware({ requireAuth: true, routes: [{ method: "all", path: "*" }] })
export class LoggedInUserMiddleware implements MedusaMiddleware {
  public async consume(
    req: MedusaAuthenticatedRequest,
    res: Response,
    next: NextFunction
  ): Promise<void> {

    if (req.user && req.user.userId) {
      const userService = req.scope.resolve('userService') as UserService;
      const loggedInUser = await userService.retrieve(req.user.userId, {
        select: ['id', 'store_id'],
      });

      console.log(req.user);

      req.scope.register({
        loggedInUser: {
          resolve: () => loggedInUser,
        },
      });
    }
    next();
  }
}
adrien2p commented 2 years ago

Hi there,

Could you show me your components where you are trying to access the loggedInUser. Also, i can see that you are applying it everywhere. The store routes have an optional auth system which means than the loggedInUser can be undefined.

I suggest you to look at this you can see here that the loggedInUser will always be part of the container but can be null in some cases

bibekkakati commented 2 years ago

I tried by installing the medusa-marketplace package as well.

Main error was occurring while trying to add a product.

This is my product.service.ts

import {
  EntityEventType,
  MedusaEventHandlerParams,
  OnMedusaEntityEvent,
  Service,
} from "medusa-extender";

import { EntityManager } from "typeorm";
import { ProductService as MedusaProductService } from "@medusajs/medusa/dist/services";
import { Product } from "./product.entity";
import { User } from "../user/user.entity";
import UserService from "../user/user.service";

type ConstructorParams = {
  manager: any;
  loggedInUser: User;
  productRepository: any;
  productVariantRepository: any;
  productOptionRepository: any;
  eventBusService: any;
  productVariantService: any;
  productCollectionService: any;
  productTypeRepository: any;
  productTagRepository: any;
  imageRepository: any;
  searchService: any;
  userService: UserService;
  cartRepository: any;
  priceSelectionStrategy: any;
};

@Service({ scope: "SCOPED", override: MedusaProductService })
export class ProductService extends MedusaProductService {
  readonly #manager: EntityManager;

  constructor(private readonly container: ConstructorParams) {
    super(container);
    this.#manager = container.manager;
  }

  @OnMedusaEntityEvent.Before.Insert(Product, { async: true })
  public async attachStoreToProduct(
    params: MedusaEventHandlerParams<Product, "Insert">
  ): Promise<EntityEventType<Product, "Insert">> {
    const { event } = params;
    const loggedInUser = this.container.loggedInUser;
    event.entity.store_id = loggedInUser.store_id; // getting loggedInUser as null
    return event;
  }

  prepareListQuery_(selector: object, config: object): object {
    const loggedInUser = this.container.loggedInUser;
    if (loggedInUser) {
      selector["store_id"] = loggedInUser.store_id;
    }

    return super.prepareListQuery_(selector, config);
  }
}
adrien2p commented 2 years ago

So, as you can see in the tutorial, we now always register the loggedInUser but as a nullable value instead of registering it only when there is a loggedInUser. Can I ask you to update your middleware with the one in the tutorial repo?

bibekkakati commented 2 years ago

I replaced the modules folder from the tutorial-repo but getting same error again. Not sure what is happening.

error:   Cannot read properties of null (reading 'store_id')
TypeError: Cannot read properties of null (reading 'store_id')
adrien2p commented 2 years ago

could you share me a reproducible repo so that I can see the config as well as the code please

bibekkakati commented 2 years ago

Hey, it's working. I just updated the dependencies with exact version as in the package.json of the tutorial-repo.

Thanks @adrien2p

Keith-Hon commented 2 years ago

Hi @adrien2p I have exactly the same problem. I do not want to downgrade the medusa's version tho. Is there any documentation on how and where req.user is resolved from a request?

Here are the versions of the packages used "@medusajs/medusa": "1.3.5", "@medusajs/medusa-cli": "1.3.1", "medusa-extender": "1.7.4",

Keith-Hon commented 2 years ago

Hi @adrien2p I have exactly the same problem. I do not want to downgrade the medusa's version tho. Is there any documentation on how and where req.user is resolved from a request?

Here are the versions of the packages used "@medusajs/medusa": "1.3.5", "@medusajs/medusa-cli": "1.3.1", "medusa-extender": "1.7.4",

I ended up fixing it by

  if (req.user && req.user.userId) {
      userId = req.user.userId;
  } else if (req.session.jwt) {
      const decoded = jwt_decode(req.session.jwt);
      userId = decoded['userId'];
  }

  if (userId) {
      const userService = req.scope.resolve('userService') as UserService;
      const loggedInUser = await userService.retrieve(userId, {
          select: ['id', 'store_id'],
      });
      req.scope.register({
          loggedInUser: {
              resolve: () => loggedInUser,
          },
      });
  }