使用 sails socket 。 从浏览器中我可以获取用户 id 为 1 的所有“任务”。 我现在可以监听“任务”事件并在动词中查找“创建”以获取新任务并将其添加到列表中。
但是,无论用户如何,我都会从所有创建的任务中获取事件。这似乎是我的一个主要安全问题。人们需要做的就是跳入控制台并设置一个监听器,以便在任何用户创建新任务时收到通知。
我环顾了一段时间,但找不到任何关于该主题的帖子。 对这种事情很陌生 - 有人可以帮忙吗?
在 Sails 中通过 socket.io 处理列表的最佳实践是什么?
干杯!
最佳答案
这应该就是您要寻找的;它会阻止您订阅客户端上的所有现有任务。它仅在您登录时订阅,并且仅订阅属于您的任务。请记住,这只是为您的应用实现安全 REST API 的第一步 - 但它应该可以帮助您入门。
在您的客户端应用程序中,您可以编写:
socket.on('connect', function socketConnected()
{
// This subscribes the user to all tasks that belong to him and only him.
socket.get('/task/subscribe', null, function response(data, jwres)
{
// We don’t really care about the response.
});
// This 1.) creates a new task and 2.) subscribes the user to that task.
// If the 'rest' blueprint is on, POSTing to /task gets redirected to TaskController.create automatically by sails.
// If it's not on, you write "socket.get('/task/create' ..."
socket.post('/task', {name : 'MyNewTask'}, function response(data, jwres)
{
// Add the created task inside of 'data' to your client side app.
});
})
然后在 TaskController.js 中你可以这样写:
subscribe : function(req, res)
{
// Is the user logged in?
if(!req.session.user)
{
return res.badRequest();
}
// Find all tasks that belong to the currently logged in user.
Task.find({userID : req.session.user.id}, findUsersCB(err, tasks)
{
// Subscribe the user to all of his tasks.
Task.subscribe(req.socket, tasks);
// Send user's tasks back to the client.
res.json(tasks);
});
}
create : function(req, res)
{
//Is the user logged in?
if(!req.session.user)
{
return res.badRequest();
}
var taskToBeCreated =
{
name : req.param('name'),
userID : req.session.user.id;
};
// Attempt to create the given task.
Task.create(taskToBeCreated, function createTaskCB(err, createdTask)
{
// Subscribe the user to the newly-created task.
Task.subscribe(req.socket, createdTask);
// Send user's task back to the client.
res.json(task);
});
}
我没有展示“更新”和“销毁”操作的示例,但两者的想法是相同的。
关于sockets - Sails.js socket.io 一般安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997643/