最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

deno - Oak session set in one middleware empty in other - Stack Overflow

programmeradmin5浏览0评论

I am facing a weird issue that when I set the session in one middleware, it's value in undefined in other. Even in the same middle ware functions it is undefined.

Here is how my app file looks like

import { oakCors } from "/x/cors/mod.ts";
import { authMiddleware } from "./middlewares/authMiddleware.js";
import { errorMiddleware } from "./middlewares/errorMiddleware.js";

import { router } from "./routes/routes.js";

const app = new Application();
app.use(
  oakCors({
    origin: "http://localhost:5173",
  }),
);
app.use(Session.initMiddleware());

app.use(errorMiddleware);
app.use(authMiddleware);

app.use(router.routes());

app.listen({ port: 7777 });

export default app;

Here is the login controller used in the Router middleware

const loginUser = async ({ request, response, state, cookies }) => {
  const parseBody = await request.body.json();

  const email = parseBody.email;
  const password = parseBody.password;

  const existingUsers = await userService.findUsersWithEmail(email);

  if (existingUsers?.length === 0) {
    response.body = "User not found. Register with the link given below.";
    response.status = 404;
    return;
  }

  const userDB = existingUsers[0];

  const hashedUserDBPassword = userDB.password;

  const matchPasswords = await bcryptpare(password, hashedUserDBPassword);
  if (!matchPasswords) {
    response.body = "Incorrect password!";
    response.status = 401;
    return;
  }

  const userLogInDetails = {
    id: userDB.id,
    email: userDB.email,
    admin: userDB.admin,
    isLoggedIn: true,
  };

  await state.session.set("user", userLogInDetails); //This session should be available in every middleware context

  response.status = 200;
  response.body = userLogInDetails;
};

and here is my auth middleware

const authMiddleware = async ({ request, response, state, cookies }, next) => {
  const authRoutes = request.url.pathname.includes("auth");

  const user = await state.session.get("user"); // This is undefined on every route 

  await next();
  return;
};

export { authMiddleware };

The session set in the login controller await state.session.set("user", userLogInDetails); should ne available on every subsequent API calls but is always undefined.

What I am missing here?

I have tried using Cookies to store the session but it still didn't work. I am expecting that the session data should be available in every middleware context

发布评论

评论列表(0)

  1. 暂无评论