Skip to content

Instantly share code, notes, and snippets.

@LeXXik

LeXXik/router.js Secret

Created July 31, 2014 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeXXik/bd5e1a00b645a89ab722 to your computer and use it in GitHub Desktop.
Save LeXXik/bd5e1a00b645a89ab722 to your computer and use it in GitHub Desktop.
koa router
'use strict';
const
Router = require('koa-router'),
routes = require('./api'),
debug = require('debug')('router');
exports = module.exports = function (app, passport) {
//
// PUBLIC API ------------------------
//
let pub = new Router();
pub
.get('/', function *() {
yield this.render('index');
})
.post('/auth/login', routes.validate.login, passport.authenticate('local'))
.post('/auth/register', routes.validate.registration, routes.users.create, passport.authenticate('local'), routes.users.me)
.get('/favicon.ico', function *() {
this.req.local.response = {
status: 404,
body: {
status: "error",
message: "not_found"
}
};
})
;
app.use(pub.middleware());
//
// SECURED API ------------------------
//
let secured = new Router()
// require an authentication for the secured routes
app.use(function* isAuthed(next) {
debug('checking if user is authenticated');
if (this.req.isAuthenticated()) {
debug('user is authenticated');
yield next;
} else if (!this.req.isAuthenticated()) {
debug('user is not authenticated');
this.req.local.response = {
status: 403,
body: {
status: "forbidden",
message: "not_authenticated"
}
};
this.redirect('/');
} else {
debug('authentication service unavailable');
this.req.local.response = {
status: 501,
body: {
status: "error",
message: "service_unavailable"
}
};
this.redirect('/');
}
});
secured
// user related routes
.get( '/bonjour', function*(next) {
this.req.local.response = {
status: 200,
body: {
status: "ok",
message: "nihao"
}
};
yield next;
})
.get( '/auth/logout', routes.users.logout)
.get( '/users/me', routes.users.me)
.get( '/users/id/:id', routes.users.id)
.get( '/users/name/:uname', routes.users.uname)
// profile related routes
.get( '/profiles/id/:id', routes.profiles.id)
.get( '/profiles/name/:pname', routes.profiles.pname)
.get( '/profiles/add', function*(){ yield this.render('addprofile'); })
.post( '/profiles/add', routes.validate.profile, routes.profiles.createAvatar,
routes.profiles.createProfile, routes.users.update);
app.use(secured.middleware());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment