如果用户已登录,如何在服务器端路由上检查?
我会在“之前”添加检查,但 Metor.user() 在这里不起作用。
提前致谢。
ps 我找到了如何让 Meteor.user() 在服务器端返回?,但不适用于铁路由器
如果用户已登录,如何在服务器端路由上检查?
我会在“之前”添加检查,但 Metor.user() 在这里不起作用。
提前致谢。
ps 我找到了如何让 Meteor.user() 在服务器端返回?,但不适用于铁路由器
恐怕这是不可能的。我猜这个问题来自这样一个事实,即您试图使用两种不同的协议连接到服务器 - 无论是字面上还是逻辑上 - 所以没有明显的方法可以将这两个动作联系起来。
但是,有一个非常简单的解决方案可能适合您的需求。您需要开发一个简单的特权令牌系统,或密钥,或任何您称之为的系统。一、创建服务器方法
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
.
在服务器端,您现在可以secretKey
从传入请求中检索 并检查它是否存在于Secrets
集合中。然后您就会知道用户是否被授予某些特权。此外,出于安全原因,您可能希望在一段时间后从集合中删除您的密钥。
如果您要做的是对发出请求的 Meteor.user 进行身份验证,我目前正在 IronRouter.route() 的上下文中执行此操作。请求必须在标头中使用有效的用户 ID 和身份验证令牌进行。我从 Router.route() 中调用这个函数,然后我可以访问 this.user:
###
Verify the request is being made by an actively logged in user
@context: IronRouter.Router.route()
###
authenticate = ->
# Get the auth info from header
userId = this.request.headers['x-user-id']
loginToken = this.request.headers['x-auth-token']
# Get the user from the database
if userId and loginToken
user = Meteor.users.findOne {'_id': userId, 'services.resume.loginTokens.token': loginToken}
# Return an error if the login token does not match any belonging to the user
if not user
respond.call this, {success: false, message: "You must be logged in to do this."}, 401
# Attach the user to the context so they can be accessed at this.user within route
this.user = user
###
Respond to an HTTP request
@context: IronRouter.Router.route()
###
respond = (body, statusCode=200, headers={'Content-Type':'text/json'}) ->
this.response.writeHead statusCode, headers
this.response.write(JSON.stringify(body))
this.response.end()
这段代码深受 RestStop 和 RestStop2 的启发。它是用于在 Meteor 0.9.0+(构建在 Iron Router 之上)中编写 REST API 的流星包的一部分。你可以在这里查看完整的源代码: