NodeJS 在meteor服务器上的每个请求会话?

hivapdat  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(126)

我正在添加一个认证层,我想我已经弄清楚了,除了一个棘手的细节。我的Meteor应用程序没有任何路由,但我在连接中间件中添加了一个钩子,以便在没有正确的API令牌时“/”路由错误。如果令牌没问题,那么我调用next()将路由转发到Meteor。
问题是,根据令牌的不同,我需要为连接设置服务器端参数,但我不知道如何做到这一点。例如,假设我有一个Map到权限级别的API密钥的静态列表。如果一个用户发送了一个带有“ADMIN_API_KEY”的请求,那么我想设置Session.permission_level = "admin"以供Meteor服务器的函数使用。Session只适用于Meteor中的客户端。

# this code's in coffeescript

  WebApp.connectHandlers.use '/', (req, res, next) ->
    validator = new RequestValidator(req, next)
    validations = [
      "valid_namespace",
      "only_https"
    ]
    error = validator.validate(validations)
    next(error)
    # <<<<<<<<<<<<<<<<<<<<<<<<
    # Here I want to set some config option which can be
    # read by the server in the same way it can read things like
    # Meteor.user()

在Rails中,我只会说session[:permission_level] = "admin"。但在Meteor中似乎不是这样。
顺便说一句,我还没有在Meteor中使用路由包,尽管这会使这比我更容易。

uurity8g

uurity8g1#

我不确定Session我一直在做类似的事情

import { DDP } from 'meteor/ddp';
import { DDPCommon } from 'meteor/ddp-common';

export const authMiddleware = (req, res, next) => {
  const userId = identifyUser(req); // parse the request to get the token you expect
  if (!userId) {
    return next();
  }

  DDP._CurrentInvocation.withValue(new DDPCommon.MethodInvocation({
    isSimulation: false,
    userId,
  }), () => {
    next();
    // in that context, Meteor.userId corresponds to userId
  });
};

对于我的REST API,它在用户ID方面运行良好,并且能够调用应该在DDP上下文中调用的Meteor函数,如Users.find(...)

相关问题