Created
July 6, 2012 14:56
-
-
Save ovaillancourt/3060644 to your computer and use it in GitHub Desktop.
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 EventEmitter = require('events').EventEmitter; | |
var querystring = require('querystring'); | |
/** | |
* Pre-baked error messages | |
* | |
*/ | |
var missingInfo = 'Password authentication - Missing Mandatory authentication' + | |
' information. A "login" and "password" must be provided.'; | |
var genericError = 'Password authentication - Error'; | |
var wrongMethod = 'Password authentication - Invalid method. Information must' + | |
' be sent in the request body using a POST method.' | |
var wrongType = 'Password authentication - Unsupported content-type.' + | |
' Content-type must be of type "application/' + | |
'x-www-form-urlencoded'; | |
/** | |
* This is a password authentication service. Basically grabs a POST | |
* request made at /auth/*servicename*, parses the body and makes sure that | |
* the "login" and "password" fields are provided. Returns an error if | |
* any of these conditions isn't matched. | |
* | |
* The post request must be made using the application/x-www-form-urlencoded | |
* encoding. | |
* | |
*/ | |
module.exports = function(options) { | |
var server = new EventEmitter; | |
function done(success, obj){ | |
var _obj = obj || success ? {} : new Error(genericError); | |
var _ev = success ? "auth" : "error"; | |
server.emit(_ev, req, res, _obj); | |
}; | |
server.on("request", function(req, res) { | |
var ct = (req.headers['content-type'] || '').split(';')[0]; | |
if(req.method !== "POST"){ | |
done(false, new Error(wrongMethod)); | |
} | |
else if(ct !== 'application/x-www-form-urlencoded'){ | |
done(false, new Error(wrongType)); | |
} | |
else{ | |
var buf = ''; | |
req.setEncoding('utf8'); | |
req.on('data', function(chunk){ | |
buf += chunk; | |
}); | |
req.on('end', function(){ | |
var authData = querystring.parse(buf); | |
authData.login && authData.password | |
? done(true, authData) | |
: done(false, new Error(missingInfo)); | |
}); | |
} | |
}); | |
return server | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment