basic-auth-and-cors.js 633 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. /**
  2. * Basic Auth and CORS
  3. *
  4. */
  5. var auth = require('koa-basic-auth');
  6. var cors = require('koa-cors');
  7. var koa = require('koa');
  8. var app = koa();
  9. // cors
  10. app.use(cors());
  11. // custom 401 handling
  12. app.use(function *(next){
  13. try {
  14. yield next;
  15. } catch (err) {
  16. if (401 == err.status) {
  17. this.status = 401;
  18. this.set('WWW-Authenticate', 'Basic');
  19. this.body = 'cant haz that';
  20. } else {
  21. throw err;
  22. }
  23. }
  24. });
  25. // require auth
  26. app.use(auth({ name: 'tj', pass: 'tobi' }));
  27. // secret response
  28. app.use(function *(){
  29. this.body = 'secret';
  30. });
  31. app.listen(3000);
  32. console.log('listening on port 3000');