1

我目前正在为 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并调用它的方法。
4

2 回答 2

3

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

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

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

客户端 js - 使用来自 w3schools.com 的cookiesetCookie和函数getCookie

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

于 2013-05-24T08:38:21.180 回答
0

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

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

于 2013-05-29T20:57:58.193 回答