Skip to content

Instantly share code, notes, and snippets.

@marcusoftnet
Created May 2, 2014 03:58
Show Gist options
  • Select an option

  • Save marcusoftnet/05099c28143816e5387c to your computer and use it in GitHub Desktop.

Select an option

Save marcusoftnet/05099c28143816e5387c to your computer and use it in GitHub Desktop.
Encapsulated koa-basic-authentication
var koa = require('koa');
var auth = require('koa-basic-auth');
var userAuth = require('./lib/authentication.js');
var app = module.exports = koa();
// Security
app.use(userAuth.reqBasic);
app.use(auth(userAuth.user));
// listen
app.use(function *(){
this.body = 'secret';
});
app.listen(3000);
console.log('listening on port 3000');
module.exports.reqBasic = function *(next){
try { yield next; }
catch (err) {
if (401 == err.status) {
this.status = 401;
this.set('WWW-Authenticate', 'Basic');
this.body = 'Nope... you need to authenticate first. With a proper user!';
}
else { throw err; }
}
};
module.exports.user = {name:'marcus', pass:'secret'};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment