adminjs-typeorm icon indicating copy to clipboard operation
adminjs-typeorm copied to clipboard

Session always undefined inside a generic middleware

Open Paroca72 opened this issue 2 years ago • 3 comments

I'm trying to understand if a user is authenticated after I login using the default Admin.js login procedure. I'm not using the admin.js router but just a simple express.js router like:

    app.use('/dashboard', [
        authMiddleware,
        dashboardRouting,
    ]);

But if I asking for Session inside the middleware is always undefined. Where is a way to understand if I am authenticated in a generic middleware?

Paroca72 avatar Jul 11 '23 05:07 Paroca72

Session store and middleware are created specifically inside AdminJS router so you cannot access the session object in outside routes, you'd have to do something like:

export const getAdminRouter = (admin: AdminJS) => {
  const router = Router({ mergeParams: true });

  const sessionOpts = {
    secret: config.session.secret,
    saveUninitialized: config.session.saveUninitialized,
    resave: config.session.resave,
    store: sessionStore,
  };

  router.use(
    session({
      ...sessionOpts,
      name: 'adminjs',
    }),
  );

  router.post('/endpoint', /* ... session available ... */);

  const modifiedRouter = ExpressPlugin.buildAuthenticatedRouter(
    admin,
    {
      cookiePassword: config.session.secret as string,
      cookieName: 'adminjs',
      authenticate,
    },
    router,
    {
      secret: config.session.secret,
      saveUninitialized: config.session.saveUninitialized,
      resave: config.session.resave,
      store: sessionStore,
    },
  );

  return modifiedRouter;
};

dziraf avatar Jul 11 '23 06:07 dziraf

So no way to know if I'm "Admin.js" authenticated in a generic middleware?

Paroca72 avatar Jul 11 '23 10:07 Paroca72

No, only if you use session middleware with identical options in your other routes.

dziraf avatar Jul 11 '23 10:07 dziraf