res.cookie未在某些帐户的浏览器中设置cookie

时间:2019-11-01 15:28:09

标签: node.js authentication cookies

大家好,我将以下请求以文本形式发送到我的发布路线:{ JSON: '{"company":"OmarCompanyTestDev_1","token":"3c87d2345c637627d4c45a39de0362444001b222","email":"support47@support.com","devices":[{"width":200,"height":200}],"first_name":"support user","last_name":"for OmarCompanyTestDev_1"}' }这个请求有时仅适用,但是我的所有变量都被分配了,并按需重定向。

但是,此请求每次都能正常运行。

 { JSON: '{"company":"NewCompany2","token":"8674f778db4d1e58d5f1fedea4e5fa90ceffc9c2","email":"support69@support.com","devices":[],"first_name":"support user","last_name":"for NewCompany2"}' }

这里是我在nodejs中运行的代码。我似乎没有收到任何错误,但cookie并未在第一个请求上设置。我不明白两者之间的区别。所有变量均已分配且所有日志均可用,但未设置cookie。

router.post("/banner-login", async (req, res, next) => {
  function insertDisplay(displayName, userId, width, height) {
    database.query("call insertDisplay(?, ?, ?, ?)", [
      displayName,
      userId,
      width,
      height
    ]);
  }
  try {
    console.log("request body", req.body);
    const bannerJson = JSON.parse(req.body.JSON);
    const {
      company,
      email,
      token,
      devices,
      first_name,
      last_name
    } = bannerJson;
    console.log("bannerJSON", bannerJson);
    console.log("company", company);
    console.log("email", email);
    console.log("token", token);
    console.log("devices", devices);
    console.log("first_name", first_name);
    console.log("last_name", last_name);

    const username = company.replace(/ /g, "_");
    console.log("username", username);
    const password = process.env.BANNER_USER_PASSWORD;
    const userIdResult = await database.query("call getUserIdByUsername(?)", [
      username
    ]);
    const exists = userIdResult[0][0];

    if (exists) {
      const userId = userIdResult[0][0].id;
      await database.query(
        "update users set banner_token=" +
          database.escape(token) +
          " where id=" +
          database.escape(userId)
      );

      await database.query("call deleteDisplaysByUserId(?)", [userId]);
      devices.forEach(item => {
        let displayName = item.width.toString() + "x" + item.height.toString();
        insertDisplay(displayName, userId, item.width, item.height);
      });
    } else {
      const userAttributes = [
        {
          Name: "given_name",
          Value: first_name
        },
        {
          Name: "family_name",
          Value: last_name
        },
        {
          Name: "email",
          Value: email
        },
        {
          Name: "phone_number",
          Value: "+1234567890"
        },
        {
          Name: "custom:company",
          Value: company
        },
        {
          Name: "custom:role",
          Value: "banner"
        }
      ];
      await cognito
        .signUp({
          ClientId: process.env.AWS_COGNITO_CLIENT_ID,
          Username: username,
          Password: password,
          UserAttributes: userAttributes
        })
        .promise();

      const params = {
        UserAttributes: [{ Name: "email_verified", Value: "true" }],
        UserPoolId: process.env.AWS_COGNITO_USER_POOL_ID,
        Username: username
      };
      await cognito.adminUpdateUserAttributes(params).promise();
      const confirmParams = {
        UserPoolId: process.env.AWS_COGNITO_USER_POOL_ID,
        Username: username
      };
      await cognito.adminConfirmSignUp(confirmParams).promise();

      const plan = "FREE";
      const dbPlanName = plan !== "FREE" ? "Braintree" : plan;
      const isDisplayOwner = 1;

      const [[{ insertId }]] = await database.query(
        "CALL insertUser (?, ?, ?, ?)",
        [username, dbPlanName, isDisplayOwner, token]
      );

      const paramsId = {
        UserAttributes: [
          {
            Name: "custom:CE_user_id",
            Value: insertId.toString()
          }
        ],
        UserPoolId: process.env.AWS_COGNITO_USER_POOL_ID,
        Username: username
      };
      await cognito.adminUpdateUserAttributes(paramsId).promise();

      // login
      const userId = insertId;

      await database.query(
        "update users set banner_token=" +
          database.escape(token) +
          " where id=" +
          database.escape(userId)
      );

      await database.query("call deleteDisplaysByUserId(?)", [userId]);
      devices.forEach(item => {
        let displayName = item.width.toString() + "x" + item.height.toString();

        insertDisplay(displayName, userId, item.width, item.height);
      });
    }
    const data = await cognito
      .initiateAuth({
        AuthFlow: "USER_PASSWORD_AUTH",
        ClientId: process.env.AWS_COGNITO_CLIENT_ID,
        AuthParameters: {
          USERNAME: username,
          PASSWORD: password
        }
      })
      .promise();
    const { IdToken, AccessToken, RefreshToken } = data.AuthenticationResult;
    const encryptedIdToken = crypto.encryptTokenPayload(IdToken);
    const encryptedAccessToken = crypto.encryptTokenPayload(AccessToken);
    res.cookie("token", {
      IdToken: encryptedIdToken,
      AccessToken: encryptedAccessToken,
      RefreshToken: RefreshToken
    });
      res.redirect("/");
  } catch (error) {
    console.log("there was an error", error);
    next(error);
  }

});

这里的任何帮助都会很棒。谢谢

1 个答案:

答案 0 :(得分:1)

基本上,发生的情况是cookie的大小在某些情况下太大。 Cookie只能容纳4096个字节。在某些情况下,我的Cookie数据远大于该数据,因此无法设置Cookie。为了解决此问题,我将cookie信息拆分为多个cookie。希望这对外面的人有帮助。