Improve authentication middleware mounting

This commit is contained in:
Andrew Stewart 2014-06-04 13:17:17 -07:00
parent 5e21c52b95
commit a4cfc4b8ec
1 changed files with 27 additions and 14 deletions

View File

@ -1,5 +1,5 @@
/*
* api
* Cylon API
* cylonjs.com
*
* Copyright (c) 2013-2014 The Hybrid Group
@ -14,8 +14,7 @@ var fs = require('fs'),
var express = require('express'),
bodyParser = require('body-parser');
var Cylon = require('./cylon'),
Logger = require('./logger');
var Logger = require('./logger');
var API = module.exports = function API(opts) {
var self = this;
@ -45,19 +44,14 @@ var API = module.exports = function API(opts) {
this.server.node = this.server;
}
// configure basic auth, if requested
if (opts.auth && opts.auth.type && opts.auth.type === 'basic') {
var user = opts.auth.user,
pass = opts.auth.pass;
if (user && pass) {
this.server.use(express.basicAuth(user, pass));
}
}
var authfn = this.setupAuth();
this.server.use(authfn);
this.server.set('title', 'Cylon API Server');
this.server.use(bodyParser());
this.server.use(express["static"](__dirname + "/../node_modules/robeaux/"));
this.configureRoutes();
};
API.prototype.defaults = {
@ -71,6 +65,23 @@ API.prototype.defaults = {
}
};
API.prototype.setupAuth = function setupAuth() {
var authfn = function auth(req, res, next) { next(); };
if (typeof(this.auth) === 'object' && this.auth.type) {
var type = this.auth.type,
module = "./api/auth/" + type,
filename = path.normalize(__dirname + "/" + module + ".js"),
exists = fs.existsSync(filename);
if (exists) {
authfn = require(filename)(this.auth);
}
};
return authfn;
};
API.prototype.listen = function() {
var self = this;
@ -103,10 +114,12 @@ API.prototype.parseCommandParams = function(req) {
// Sets all routes for the server
API.prototype.configureRoutes = function() {
var Cylon = require('./cylon');
var self = this;
this.server.all("/*", function(req, res, next) {
res.set("Access-Control-Allow-Origin", self.opts.CORS || "*");
res.set("Access-Control-Allow-Origin", self.CORS || "*");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.set('Content-Type', 'application/json');
return next();