Skip to content

Commit

Permalink
Added example for basic-auth
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusoftnet committed Apr 4, 2014
1 parent c4d8c84 commit d26e3ef
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 1 deletion.
31 changes: 31 additions & 0 deletions basicAuth/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
var auth = require('koa-basic-auth');
var koa = require('koa');
var app = koa();

// custom 401 handling

app.use(function *(next){
try {
yield next;
} catch (err) {
if (401 == err.status) {
this.status = 401;
this.body = 'cant haz that';
} else {
throw err;
}
}
});

// require auth

app.use(auth({ name: 'tj', pass: 'tobi' }));

// secret response

app.use(function *(){
this.body = 'secret';
});

app.listen(3000);
console.log('listening on port 3000');
52 changes: 52 additions & 0 deletions basicAuth/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var basicAuth = require('koa-basic-auth');
var request = require('supertest');
var koa = require('koa');
var assert = require('assert');

describe('Koa Basic Auth', function(){

describe('with no credentials', function(){
it('should `throw` 401', function(done){
var app = koa();

app.use(basicAuth({ name: 'user', pass: 'pass' }));

request(app.listen())
.get('/')
.expect(401)
.end(done);
})
})

describe('with invalid credentials', function(){
it('should `throw` 401', function(done){
var app = koa();

app.use(basicAuth({ name: 'user', pass: 'pass' }));

request(app.listen())
.get('/')
.auth('foo', 'bar')
.expect(401)
.end(done);
})
})

describe('with valid credentials', function(){
it('should call the next middleware', function(done){
var app = koa();

app.use(basicAuth({ name: 'user', pass: 'pass' }));
app.use(function *(){
this.body = 'Protected';
})

request(app.listen())
.get('/')
.auth('user', 'pass')
.expect(200)
.expect('Protected')
.end(done);
})
})
})
1 change: 1 addition & 0 deletions errors/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ app.use(function *(){
app.on('error', function(err){
if (process.env.NODE_ENV != 'test') {
console.log('sent error %s to the cloud', err.message);
console.log(err);
}
});

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"raw-body": "^1.1.1",
"save-to": "^1.0.0",
"streaming-json-stringify": "^1.0.0",
"swig": "^1.2.2"
"swig": "^1.2.2",
"koa-basic-auth": "^1.1.1"
},
"devDependencies": {
"co": "*",
Expand Down

0 comments on commit d26e3ef

Please sign in to comment.