骨干,节点,会话验证,我的方法有效,但请告诉我它是否正确 [英] Backbone, Node, Session validation, my method working, but tell me whether it is correct or not

查看:62
本文介绍了骨干,节点,会话验证,我的方法有效,但请告诉我它是否正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一开始就使用了它:

I used this at the beginning :

var app = express.createServer(
  express.cookieParser(),
  express.session({ secret: 'somesecretword' })
);

下面的代码是一个示例代码,用于使用uname作为键来获取用户详细信息.

Below code is a sample code to get user details with uname as the key.

我通过调用model.fetch()从主干模型的URL调用此代码.

I call this code from backbone model's url, by calling model.fetch().

app.get('/user/:uname/', function (req, res) {

  var uname=req.params.uname;
  if(!req.session.user)   // check if logged in
  res.send("Not Logged In");

  return UserModel.find({uname : uname},function(err, user) {
    if (!err) {
      return res.send(user);
    } else {
      return res.send(err);
    }
  });
});

所以,这里我直接在上面的get方法中编写了用于验证会话的代码.

So, here I wrote the code for validating session directly in the above get method.

如果我有很多这样的方法怎么办?我是否必须在每个方法中都写相同的东西,或者Node中是否有任何控制器可以做到这一点?

What if I have many such methods? Do I have to write the same thing in every method, or is there any controller in Node that does this work?

例如,向我展示一个验证路径"/user"的控制器,这意味着"/user/anythinghere/"应自动进行验证,或者向我展示其他更好的方法.

For example, show me a controller that validates for the paths "/user" , means "/user/anythinghere/" should be validated automatically or show me some other better way.

推荐答案

您需要的是某种与app.get方法一起传递的中间件.我无法完全重新编写您的代码块,因为我本人仍在Express文档中学习Node.js(如何修改以满足您的需要)

What you are needing is some sort of middleware to pass with the app.get method. I can't exactly re-write your code block as I myself am still learning Node.js how ever this from the Express documentation (modified a bit to try and suit your needs)

function requireAuth(req, res, next) {
  if(req.session.user) {
    next();
  } else {
    next(new Error('Failed to load user ' + req.params.id));
  }
}

app.get('/user/edit/:id', requireAuth, function(req, res){
  res.send('you can see this because you are authed');
});

app.get('/', function(req, res){
  res.send('Not requiring auth on homepage');
});

这里的文档可以更好地说明这一点:

The documentation here explains it better then I can:

http://expressjs.com/guide.html#route-middleware

我希望这可以有所帮助. :)如果有的话,我自己刚刚学到了一些新的答案,所以谢谢:D

I hope this can be of some help. :) If anything, I myself just learnt something new answering this, so thanks :D

这篇关于骨干,节点,会话验证,我的方法有效,但请告诉我它是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆