Trunk, Node, session verification, my method works, but tell me if it is correct or not.

I used this at the beginning:

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

Below code is an example code to get user data with uname as key.

I call this code from the baseline 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);
    }
  });
});

So, here I wrote the code to verify the session directly in the get method above.

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?

For example, show me a controller that checks the paths / user, means that / user / anythinghere / should be checked automatically or show me another better way.

+1
source share
2

, , - - app.get. , Node.js, Express ( , )

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');
});

, :

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

, .:) , - , , : D

+2

:

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

- :

app.all("/api/private*", ensureAuthenticated);

: https://fabianosoriani.wordpress.com/2011/08/15/express-api-on-node-js-with-mysql-auth/

+1

All Articles