Skip to content

Instantly share code, notes, and snippets.

@SFzxc
Created May 19, 2016 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SFzxc/9caaa60648384a009057a58adf952316 to your computer and use it in GitHub Desktop.
Save SFzxc/9caaa60648384a009057a58adf952316 to your computer and use it in GitHub Desktop.
API - Node.js ExpressJs MongoDB
validation-session.js
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var constants = require('../config/constants');
module.exports = (req, res, next) => {
var sessionToken = req.headers.authorization;
if (!req.body.user && sessionToken) {
jwt.verify(sessionToken, constants.JWT_SECRET, (err, decodedId) => {
console.log(decodedId);
if (decodedId) {
User.findOne({ _id: decodedId}).then((user) => {
req['user'] = user;
next();
}, (err) => {
console.log(err);
res.send(401, 'not authorized1');
});
} else {
res.send(401, 'not authorized2');
}
});
} else {
next();
}
};
Error:
{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
name: 'CastError',
kind: 'ObjectId',
value:
{ _bsontype: 'ObjectID',
id: 'W=&\u0001â©\u0011\u000fÞ9l',
iat: 1463625217,
exp: 1463711617 },
path: '_id',
reason: undefined }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment