:
var jwt = require('jwt-simple');
var db = require('../../config/db');
var bcrypt = require('bcrypt');
var user = require('../models/user');
function chkRole(roles, role) {
var r = roles.filter(function(e) {
return e === role;
});
return r.length > 0;
}
module.exports = function(req, res, next) {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
var t = req.headers['cookie'] ? req.headers['cookie'].split(";")[0].split("=")[1] : null;
var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || req.headers['x-access-token'] || t;
if (token) {
try {
var U = jwt.decode(token, db.secret);
if (U.exp <= Date.now()) {
res.status(400);
res.json({
"status" : 400,
"message" : "Token Expired"
});
}
var roles;
user.findOne({
email : U.email
}, function(err, user) {
if (err)
throw err;
if (!user) {
res.status(401);
res.json({
"status" : 401,
"message" : "Invalid credentials"
});
console.log(res.status);
} else {
if (U.pass === user.password) {
if (chkRole(user.roles, 'admin') && (req.url.indexOf('/api/admin/') >= 0)) {
next();
} else if ((chkRole(user.roles, 'player') || chkRole(user.roles, 'admin')) && (req.url.indexOf('/api/game/') >= 0)) {
GLOBAL.email = user.email;
next();
} else {
res.status(403);
res.json({
"status" : 403,
"message" : "Not Authorized"
});
}
}
}
});
} catch (err) {
res.status(500);
res.json({
"status" : 500,
"message" : "Oops something went wrong",
"error" : err
});
}
} else {
res.status(401);
res.json({
"status" : 401,
"message" : "Invalid Token or Key"
});
}
};
次の行
を追加することによって、アプリケーションのメイン
app.js
ファイルに登録することができます
app.all('/api/*', [ require('./app/middlewares/validateRequest') ]);