When using koa-router , it is expected that only one route will be deleted. Therefore, when you press the route '*' , it will not hit another route, even if you yield next .
So, you should replace the universal route with your own authentication middleware:
app.use(function*(next) { if (this.isAuthenticated()) { yield next } else { this.redirect('/login') } });
The authentication tool forces you to perform your routing with two routing objects instead of one. This way you can distinguish between public and secure routes. So something like:
var public = new koaRouter(); public.get('/login', function *(next) { this.body = yield render('index.html'); }); public.post('/login', passport.authenticate('local', { successRedirect: '/secretBankAccount', failureRedirect: '/login' })); app.use(public.routes()); app.use(function*(next) { if (this.isAuthenticated()) { yield next; } else { this.redirect('/login'); } }) var secured = new koaRouter(); secured.get('/secretBankAccount', function *(next) { this.body = '2 dollars'; }); app.use(secured.routes());
In the above example, the request will first go to the public routing middleware. Then, if it does not match the current request with a public route, it will switch to middleware authentication. If isAuthenticated() is false , a redirect will occur. If isAuthenticated() is true , it will switch to secure routing.
This approach is based on a draft example of a kao passport that was created by koa-passport .
source share