Last active
September 2, 2015 13:40
-
-
Save alexbeletsky/e58c46221f9c05764c6f to your computer and use it in GitHub Desktop.
Securing ExpressJS v4.0 HTTP endpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var bodyParser = require('body-parser'); | |
var methodOverride = require('method-override'); | |
var morgan = require('morgan'); | |
var cors = require('cors'); | |
var config = require('./config'); | |
var middleware = require('./source/middleware'); | |
var logger = require('./source/utils/logger'); | |
var auth = require('./source/utils/auth'); | |
var app = express(); | |
var env = process.env.NODE_ENV || 'development'; | |
var port = process.env.PORT || 3010; | |
morgan.format('custom', ':method :url :status :res[content-length] - :response-time ms'); | |
app.use(morgan('custom', {stream: logger.stream()})); | |
app.use(bodyParser.json()); | |
app.use(methodOverride()); | |
app.use(cors()); | |
auth(app, ['/api']); | |
require('./source/api')(app); | |
app.use(middleware.errors()); | |
app.listen(port, function () { | |
logger.info('api listening on port ' + port + ' ' + env); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var middleware = require('../middleware'); | |
function applyAuthentication(app, routesToSecure) { | |
routesToSecure.forEach(function (route) { | |
app.all(route + '/*', middleware.access.auth()); | |
}); | |
return app; | |
} | |
module.exports = applyAuthentication; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function auth() { | |
return function (req, res, next) { | |
var token = headers() || query(); | |
if (!token) { | |
return next({message: 'access token is missing', status: 401}); | |
} | |
// Auth logic here.. | |
next(); | |
function headers() { | |
return req.headers.accessToken || req.headers.accesstoken; | |
} | |
function query() { | |
return req.query.accessToken || req.query.accesstoken; | |
} | |
}; | |
} | |
module.exports = auth; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment