我的 serverSessionSecrect() 函数实际上在做什么?

What is my serverSessionSecrect() function actually doing?

我正在设置一个新应用程序并使用一些样板代码来管理会话和加密密码。有一个特殊的功能我就是想不通。

我已尝试按照代码进行操作,但仍然无法确定发生了什么。

const serverSessionSecret = () => {
  if (!process.env.SERVER_SESSION_SECRET ||
      process.env.SERVER_SESSION_SECRET.length < 8 ||
      process.env.SERVER_SESSION_SECRET === warnings.exampleBadSecret) {
    // Warning if user doesn't have a good secret
    console.log(warnings.badSecret);
  }

  return process.env.SERVER_SESSION_SECRET;
};

module.exports = cookieSession({
  secret: serverSessionSecret() || 'secret', // please set this in your .env file
  key: 'user', // this is the name of the req.variable. 'user' is convention, but not required
  resave: 'false',
  saveUninitialized: false,
  cookie: { maxage: 60000, secure: false },
});

该函数引用了我尚未创建的 .env 文件。这就解释了为什么我总是得到 'Bad Secret' console.logserverSessionSecret 函数似乎只是在测试 process.env.SERVER_SESSION_SECRET 是否满足最低安全要求,但这样做的目的是什么。

有没有.env有什么区别?

process.env 是一种访问脚本正在执行的环境变量的方法。

这允许您将不同的变量注入到您的代码中,具体取决于代码所在的位置 运行。环境变量可以导出到代码为 运行 的位置(例如 export newEnv = NewEnvVar),或者存在于 .env 文件中。

查看每一行的评论:

const serverSessionSecret = () => {
  if (!process.env.SERVER_SESSION_SECRET || 
         // Send warning if SERVER_SESSION_SECRET does NOT exit? Or...
      process.env.SERVER_SESSION_SECRET.length < 8 ||
         // Send warning if it less than 8 characters. Or...
      process.env.SERVER_SESSION_SECRET === warnings.exampleBadSecret
         // Send warning if the secret matches a predefined bad example
  ) {
    // Warning if user doesn't have a good secret
    console.log(warnings.badSecret);
  }

     /* If none of the above conditions are met,
     *   a console.log warning message does not get sent.
     */

  return process.env.SERVER_SESSION_SECRET;
     // This returns the Secret or Undefined if it does not exist.
};

然后在您的导出中:

module.exports = cookieSession({
  secret: serverSessionSecret() || 'secret', // please set this in your .env file
     // secret will equal your 'process.env.SERVER_SESSION_SECRET' environment
     // variable, but if it is not defined, it will equal 'secret'
  key: 'user', // this is the name of the req.variable. 'user' is convention, but not required
  resave: 'false',
  saveUninitialized: false,
  cookie: { maxage: 60000, secure: false },
});

总而言之,serverSessionSecret() 在这种情况下仅返回一个字符串。 secret 或环境变量中的设置。

看起来你正在使用这个库:https://www.npmjs.com/package/cookie-session

在这种情况下,当您使用 secret 配置 cookie 会话时,他们的文档显示:

secret

A string which will be used as single key if keys is not provided.

keys

The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.

在您的情况下,process.env.SERVER_SESSION_SECRETsecret 用于签署和验证 cookie。