SoftwareBrothers / adminjs-typeorm

TypeORM adapter for AdminJS
MIT License
24 stars 33 forks source link

Session always undefined inside a generic middleware #64

Open Paroca72 opened 1 year ago

Paroca72 commented 1 year ago

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?

dziraf commented 1 year ago

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;
};
Paroca72 commented 1 year ago

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

dziraf commented 1 year ago

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