興味があれば、私はついに2番目のソリューションを実装しました。非常にシンプルで仕事をしなさい!
config.jsの
module.exports = {
'secret': 'apisupersecrethere',
};
route.js
var config = require('./config');
app.set('api_secret', config.secret);
api = express.Router();
// function that checks the api_token
api.use(function(req, res, next) {
var token = req.headers['x-access-token'];
if (token) {
jwt.verify(token,app.get('api_secret'),function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
// route protected by the authentication
router.use('/users', api);
// authentication route
router.post('/auth', function(req, res) {
verifyFacebookUserAccessToken(req.body.access_token).
then(function(user) {
var token = jwt.sign(user, app.get('api_secret'), {
expiresIn: 1440*60 // expires in 24 hours
});
res.status(200).json({
success: true,
message: "Authentication success!",
token: token
});
}, function(error) {
res.status(401).json({
success: false,
message: error.message
});
}).
catch(function(error){
res.status(500).json({
success: false,
message: error.message
});
});
});
// Call facebook API to verify the token is valid
function verifyFacebookUserAccessToken(token) {
var deferred = Q.defer();
var path = 'https://graph.facebook.com/me?access_token=' + token;
request(path, function (error, response, body) {
var data = JSON.parse(body);
if (!error && response && response.statusCode && response.statusCode == 200) {
var user = {
facebookUserId: data.id,
username: data.username,
firstName: data.first_name,
lastName: data.last_name,
email: data.email
};
deferred.resolve(user);
}
else {
deferred.reject({
code: response.statusCode,
message: data.error.message
});
}
});
return deferred.promise;
}
歓迎すべてのフィードバック。
よろしくお願いいたします。