https://supertokens.com/ logo
u

ULCE31

05/31/2022, 3:42 PM
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

rp

05/31/2022, 4:48 PM
Hey!
Can you show me which API you are querying?
u

ULCE31

06/01/2022, 3:07 PM
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

rp

06/01/2022, 3:12 PM
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

ULCE31

06/01/2022, 3:14 PM
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

rp

06/01/2022, 3:17 PM
how have you imported Session?
u

ULCE31

06/01/2022, 3:22 PM
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

rp

06/01/2022, 3:23 PM
right yea. You need to import session
Also make sure that the value of
process.env.SUPERTKNS_CORE_ADDR
is correct
u

ULCE31

06/01/2022, 3:24 PM
SUPERTKNS_CORE_ADDR=http://localhost:3567
r

rp

06/01/2022, 3:25 PM
so the node service is running inside a docker container?
u

ULCE31

06/01/2022, 3:25 PM
Yes
r

rp

06/01/2022, 3:25 PM
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

ULCE31

06/01/2022, 3:26 PM
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

rp

06/01/2022, 3:32 PM
probably the connection URI in the node backend should be "http://supertokens-dev:3567"
u

ULCE31

06/01/2022, 3:35 PM
As I was looking through my configuration, I may have noticed a mistake, in my Dockerfile I didn't : EXPOSE 3567
r

rp

06/01/2022, 3:38 PM
hmmm. Did exposing it solve the issue?
u

ULCE31

06/01/2022, 3:38 PM
No, it didn't. Currently implementing your suggestion
r

rp

06/01/2022, 3:39 PM
ok. lmk
u

ULCE31

06/01/2022, 3:45 PM
It works, 🙌 🎯
r

rp

06/01/2022, 3:45 PM
Great!
u

ULCE31

06/01/2022, 3:46 PM
Thank you for your patience
r

rp

06/01/2022, 3:46 PM
Happy to help 🙂
6 Views