问题描述
如何在服务器端路由上检查用户是否已登录?
How can check, on server side route, if user is logged?
我会在之前"添加检查,但 Metor.user() 在这里不起作用.
I would add check on 'before', but Metor.user() don't work here.
提前致谢.
附言我找到了 如何获取 Meteor.user() 在服务器端返回?,但不能在铁路由器上工作
p.s. I have found How to get Meteor.user() to return on the server side?, but not work on iron-router
推荐答案
恐怕这是不可能的.我想问题出在您尝试使用两种不同的协议连接到服务器的事实 - 无论是字面上还是逻辑上 - 所以没有明显的方法来关联这两个操作.
I'm afraid that this is not possible. I guess that the problem comes from the fact that you're trying to connect to the server with two different protocols - both literally and in logically - so there is no obvious way to relate this two actions.
然而,有一个非常简单的解决方案可以满足您的需求.您需要开发一个简单的特权令牌系统,或秘密密钥,或任何您称之为的东西.首先,创建一个服务端方法
There is, however, a pretty simple solution that may suit your needs. You'll need to develop a simple system of privileges tokens, or secret keys, or whatever you call them. First, create a server method
var Secrets = new Meteor.Collection("secrets"); // only on server!!!
Meteor.methods({
getSecretKey: function () {
if (!this.userId)
// check if the user has privileges
throw Meteor.Error(403);
return Secrets.insert({_id: Random.id(), user: this.userId});
},
});
然后,您现在可以在客户端上使用它来获取 secretKey
附加到您的 AJAX
请求(或其他内容),无论是在 HTTP
标头或 URL
本身.不要怕!如果您使用 HTTPS
,它们都将被加密.
Then, you can now use it on the client to get the secretKey
which attach to your AJAX
request (or something), either within the HTTP
header or in the URL
itself. Fear not!They will all be encrypted if you're using HTTPS
.
在服务器端,您现在可以从传入的请求中检索 secretKey
并检查它是否存在于 Secrets
集合中.然后你就会知道用户是否被授予了某些特权.此外,出于安全原因,您可能希望在一段时间后从集合中删除您的密钥.
On the server side you can now retrieve the secretKey
from the incoming request and check if it is present in the Secrets
collection. You'll know then if the user is granted certain privileges or not.Also you may want to remove your secret keys from the collection after some time for safety reasons.
这篇关于铁路由器服务器端的 Meteor.user()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!