Skip to content

Instantly share code, notes, and snippets.

@cadecairos
Created July 25, 2013 16:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cadecairos/6081326 to your computer and use it in GitHub Desktop.
Save cadecairos/6081326 to your computer and use it in GitHub Desktop.
MakeAPI Hawk middleware
function (req, res, next) {
/* Hawk does all the necessaries in this authenticate function.
* You pass it a function to look up an ID ( In the MakeAPI I call
* them public keys, as they are randomly generated UUIDs
*/
hawkModule.Hawk.server.authenticate(req, function (publickey, callback) {
/* Create a credentials object, This contains the algorithm that should
* be used to calculate the MAC It also contains the public key and will
* contain a private key after a successful lookup
*/
var credentials = {
algorithm: 'sha256',
user: publickey
};
/* Search for a private key associated with the public key
* that was passed in via the Authorization header of the request
*/
ApiUser.findOne({
publickey: publickey
}, function (err, doc) {
// If there's no matching private key, reject the request
if (err || !doc) {
return callback(err);
}
// only warn of revoked key if the passed MAC is successfully
// authenticated
if (doc.revoked) {
req.revokedKey = true;
}
/* Attach the private key to the credentials object,
* and return it to the Hawk authenticate function for
* verification of the requests integrity
*/
credentials.key = doc.privatekey;
callback(null, credentials);
});
}, hawkOptions, function (err, creds, artifacts) {
/* This is the result of Hawk's authenticate function
* If the request is invalid (ie. the MAC generated by the
* server does not match the MAC generated by the client),
* respond with a 401
*/
var msg = "Your Key has been revoked, contact a MakeAPI administrator.";
if (err || req.revokedKey) {
msg = err ? err.message : msg;
// This function generates a Authorization header and MAC
// for the Client to authenticate responses.
return hawkModule.respond(401, res, creds, artifacts, {
status: "failure",
reason: msg
}, "application/json");
}
// I store this information so that we can use it in other
// middleware function for Hawk signed responses.
req.credentials = creds;
req.artifacts = artifacts;
//SUCCESS!
next();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment