Created
September 5, 2014 17:36
-
-
Save eddiezane/5a1fd04383a497a63157 to your computer and use it in GitHub Desktop.
Basic HTTP Auth
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 app = express(); | |
var server = require('http').createServer(app); | |
// Set up SendGrid! | |
var sendgrid = require('sendgrid')('SENDGRID_USERNAME', 'SENDGRID_PASSWORD'); | |
server.listen(3000); | |
// Define our middleware | |
app.use(function(req, res, next) { | |
var authHeader = req.headers.authorization; | |
// Check to see if the header exists | |
// If not, return the challenge header and code | |
if (authHeader === undefined) { | |
res.header('WWW-Authenticate', 'Basic realm="Please sign in, yo!"'); | |
res.status(401).end(); | |
return; | |
} | |
// Split the header and grab the base64 encoded username:password | |
var encodedHeader = authHeader.split(' ')[1]; | |
// Base64 decode the username:password string | |
var decodedHeader = new Buffer(encodedHeader, 'base64').toString(); | |
var username = decodedHeader.split(':')[0]; | |
var password = decodedHeader.split(':')[1]; | |
// These could be environment variables | |
// Check the credentials... | |
if (username == 'user' && password == 'pass') { | |
// and pass control on to our routes | |
next(); | |
} else { | |
// Send an email to alert us! | |
sendgrid.send({ | |
to: 'your_email@example.com', | |
from: 'your_email@example.com', | |
subject: 'Hax0r attempt', | |
text: 'From IP: ' + req.ip | |
}, function() { | |
// Deny them access | |
res.status(403).end('Incorrect login'); | |
}); | |
} | |
}); | |
app.get('/', function(req, res) { | |
res.send('You are in!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment