从方法/发布外部访问Meteor.userId

时间:2013-05-24 04:59:57

标签: javascript meteor

我目前正在为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 ()
});

这显然是一种相对hacky的做事方式,但我需要创建一个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的方法,并从我的代码中调用它。

2 个答案:

答案 0 :(得分:2)

首先需要定位的是获取可以从标题中识别用户的内容(特别是因为您希望在没有javascript可以运行的位置获取用户名)。

Meteor存储localStorage中登录的会话数据,只能通过javascript访问。因此,在页面加载并且标题已通过之前,它无法检查谁登录。

为此,您还需要将用户数据存储为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

进行反应

答案 1 :(得分:0)

我的解决方案受到@Akshat方法的服务器部分的启发。由于我正在制作RESTful API,所以我每次都会传递userId / loginToken(作为param,cookie或header)。

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

相关问题