API authentification (tbc...)

This commit is contained in:
Gaël Métais
2014-12-09 09:04:28 +01:00
parent 906f0876a0
commit 49015e3422
9 changed files with 300 additions and 22 deletions
+52
View File
@@ -0,0 +1,52 @@
var config = require('../../server_config/settings.json');
var jwt = require('jwt-simple');
var debug = require('debug')('authMiddleware');
var authMiddleware = function(req, res, next) {
'use strict';
if (req.path.indexOf('/api/') === 0) {
// Test if it's an authorized key
if (req.headers && req.headers['x-api-key'] && isApiKeyValid(req.headers['x-api-key'])) {
next();
return;
}
// Test if it's an authorized token
if (req.headers && req.headers['x-api-token'] && isTokenValid(req.headers['x-api-token'])) {
next();
return;
}
res.status(401).send('Unauthorized');
}
};
function isApiKeyValid(apiKey) {
return (config.authorizedKeys[apiKey]) ? true : false;
}
function isTokenValid(token) {
var data = null;
try {
jwt.decode(token, config.tokenSalt);
} catch(err) {
debug('Error while decoding token');
debug(err);
return false;
}
return data.expire &&
data.expire > Date.now() &&
data.application &&
config.authorizedApplications.indexOf(data.application) >= 0;
}
module.exports = authMiddleware;
+7 -5
View File
@@ -13,10 +13,7 @@ var ApiController = function(app) {
var runsDatastore = new RunsDatastore();
var resultsDatastore = new ResultsDatastore();
// Retrieve the list of all runs
/*app.get('/api/runs', function(req, res) {
// NOT YET
});*/
// Create a new run
app.post('/api/runs', function(req, res) {
@@ -107,6 +104,11 @@ var ApiController = function(app) {
}
});
// Retrieve the list of all runs
/*app.get('/api/runs', function(req, res) {
// NOT YET
});*/
// Delete one run by id
/*app.delete('/api/runs/:id', function(req, res) {
deleteRun()
@@ -125,7 +127,7 @@ var ApiController = function(app) {
// Exists
app.head('/api/runs/:id', function(req, res) {
existsX();
// Retourne 200 si existe ou 404 si n'existe pas
// Returns 200 if the result exists or 404 if not
});
*/