【问题标题】:Access Meteor.userId from outside a method/publish从方法/发布外部访问 Meteor.userId
【发布时间】:2013-05-19 15:20:10
【问题描述】:

我目前正在为 Meteor 编写一个以服务器为中心的包,相关代码如下所示:

__meteor_bootstrap__.app.stack.unshift({
    route: route_final,
    handle: function (req,res, next) {
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.end("Print current user here");
        return;
    }.future ()
});

这显然是一种比较老套的做事方式,但我需要创建一个 RESTful API。

如何从这里访问Meteor.userId()?文档说它只能从方法内部访问或发布。有什么办法解决吗?

我尝试过的事情:

  • 使用Meteor.publish("user", function() { user = this.userId() }); 从发布中捕获它
  • 从 cookie 中获取令牌 + 用户 ID,并使用类似 Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken}); 的方式自行验证
  • 创建一个名为get_user_id 的方法并从我下面的代码中调用它。

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    您首先需要定位的是从标头中获取可以识别用户的内容(尤其是因为您希望在无法运行 javascript 的地方获取用户名)。

    Meteor 将登录的会话数据存储在 localStorage 中,只能通过 javascript 访问。所以它无法检查谁登录了,直到页面加载完毕并且 headers 已经通过。

    为此,您还需要将用户数据存储为 cookie 以及localStorage

    客户端 js - 使用来自 w3schools.com 的 cookie setCookiegetCookie 函数

    Deps.autorun(function() {
        if(Accounts.loginServicesConfigured() && Meteor.userId()) {
            setCookie("meteor_userid",Meteor.userId(),30);
            setCookie("meteor_logintoken",localStorage.getItem("Meteor.loginToken"),30);
        }
    });
    

    服务器端路由

    handle: function (req,res, next) {
        //Parse cookies using get_cookies function from : http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server
        var userId = get_cookies(req)['meteor_usserid'];
        var loginToken = get_cookies(req)['meteor_logintoken'];
    
        var user = Meteor.users.findOne({_id:userId, "services.resume.loginTokens.token":loginToken});
    
        var loggedInUser = (user)?user.username : "Not logged in";
    
        res.writeHead(200, {'Content-Type': 'text/json'});
        res.end("Print current user here - " + loggedInUser)
        return;
    }.future ()
    

    cookie 允许服务器在页面呈现之前检查谁登录。它在用户登录后立即设置,反应性地使用Deps.autorun

    【讨论】:

    • 应该是"services.resume.loginTokens.token":loginToken});
    • 我得到一个未定义的 setCookie,这仍然有效吗?
    • 顺便说一句,这不再有效,因为现在用户帐户在里面保存 hashedToken 并且不再有 loginToken
    【解决方案2】:

    我的解决方案受到@Akshat 方法的服务器部分的启发。因为我正在制作一个 RESTful API,所以我每次只传递 userId/loginToken(作为参数、cookie 或标头)。

    对于任何感兴趣的人,我将其捆绑为一个包:https://github.com/gkoberger/meteor-reststop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 2016-09-02
      • 1970-01-01
      • 2018-05-09
      • 2018-02-22
      • 2020-10-28
      • 1970-01-01
      相关资源
      最近更新 更多