Hi, I'm facing the following issue - (Front-end - ...
# general
u
Hi, I'm facing the following issue - (Front-end - Network inspector) - 500 status code - Response : {"error": "User authentication", "message": "Session is not defined"} Stack : - Front : React - Back : Nodejs - Receipe : Session, Self-hosted - mongodb - The above artefacts "dockerized" which means the entiere configuration is described on dockercompose.yml Thanks by advance for your attention,
r
Hey!
Can you show me which API you are querying?
u
Copy code
js
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import morgan from "morgan";
import supertokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";
import { errorHandler, middleware } from "supertokens-node/framework/express";
import dotenv from "dotenv";
dotenv.config();

import router from "./routes";
import swaggerUi from "swagger-ui-express";
import yamljs from "yamljs";
const swaggerDoc = yamljs.load("swagger.yaml");

export default class Server {
  /**
   * Config server
   * @returns {app}
   */
  static initSuperTokens() {
    return supertokens.init({
      framework: "express",
      supertokens: { connectionURI: `${process.env.SUPERTKNS_CORE_ADDR}` },
      appInfo: {
        appName: "peb-app",
        apiDomain: `${process.env.API_ADDR}`,
        websiteDomain: `${process.env.UI_ADDR}`,
        apiBasePath: "/",
        websiteBasePath: "/",
      },
      recipeList: [Session.init()],
    });
  }
  static config() {
    this.initSuperTokens();
    const app = express();
    app.use(
      cors({
        origin: `${process.env.UI_ADDR}`,
        allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()],
        credentials: true,
      })
    );
    app.use(middleware());
    app.use(
      morgan(
        ':remote-addr - :remote-user [:date[web]] ":method :url HTTP/:http-version" :status :res[content-length]'
      )
    );
    app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDoc));

    //Configuration de l'app
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());

    //Configuration des routes de l'API depuis routes.js
    app.use("/", router);
    app.use(errorHandler());
    /* 
      // Implémente ton gestionnaire d'erreurs
      app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { });
    */
    return app;
  }
}
r
what is the request that yields a 500 error?
you seem to be using just our session recipe. So how are you using it?
u
Copy code
js
static async auth(req, res) {
    let status = 200;
    let body = {};
    try {
      let { email, mot_de_passe } = req.body;
      let user = await User.findOne({ email: email })
        .populate({ path: "poste", select: "libelle" })
        .populate({
          path: "service",
          select: "abreviation denomination _id",
        })
        .populate({ path: "role", select: "-__v" })
        .select("-__v -created_at");
      if (
        user &&
        user.status === true &&
        crypto.createHash("sha256").update(mot_de_passe).digest("hex") ===
          user.mot_de_passe
      ) {
        console.log(user["_id"]);
        let userId = user["_id"];
        await Session.createNewSession(res, userId);
        let { mot_de_passe, ...loggedUser } = user.toObject();
        body = { message: "Utilisateur connecté :white_check_mark: !" };
      } else {
        status = 401;
        new Error("Unauthorized");
      }
    } catch (e) {
      status = status !== 200 ? status : 500;
      body = {
        error: e.error || "User authentication",
        message: e.message || "An error is occured into user auth",
      };
    }
    return res.status(status).json(body);
  }
r
how have you imported Session?
u
I haven't, sorry 😩 , I've imported it and it returned me :
Copy code
json
{"error":"User authentication","message":"No SuperTokens core available to query"}
r
right yea. You need to import session
Also make sure that the value of
process.env.SUPERTKNS_CORE_ADDR
is correct
u
SUPERTKNS_CORE_ADDR=http://localhost:3567
r
so the node service is running inside a docker container?
u
Yes
r
if you use localhost inside the container, it points to inside the container and not your host's localhost
so you need to give the local IP of your machine
u
Yes I understand, so did I :
Copy code
yaml
supertokens-dev:
    container_name: supertokens-dev
    build:
      context: ./supertokens-core
      dockerfile: Dockerfile.dev
    ports:
      - "3567:3567"
r
probably the connection URI in the node backend should be "http://supertokens-dev:3567"
u
As I was looking through my configuration, I may have noticed a mistake, in my Dockerfile I didn't : EXPOSE 3567
r
hmmm. Did exposing it solve the issue?
u
No, it didn't. Currently implementing your suggestion
r
ok. lmk
u
It works, 🙌 🎯
r
Great!
u
Thank you for your patience
r
Happy to help 🙂
6 Views