We will be defining three simple middlewares to help with authentication. They are explained here:
- authenticated: This is the middleware that ensures a user is signed in before they can have access to a resource. We define it by creating an authenticated.js file and putting the following content in it:
// ./middleware/authenticated.js
module.exports = () => {
return async (ctx, next) => {
const { user } = ctx.session;
if (user) await next();
else ctx.redirect('/auth');
};
};
- guest: This middleware ensures that only not logged-in users can access a resource. We can define it by creating a guest.js in the middleware folder and putting the following content in it:
// ./middleware/guest.js
module.exports = () => {
return async (ctx, next) => {
const { user } = ctx.session;
if (user) ctx.redirect('/');
else await next();
};
};
- user: This middleware simply takes the current user in the session and makes it available in ctx.state, which is then passed to the views. We can define it by creating user.js in the middleware folder and putting the following content in it:
// ./middleware/user.js
module.exports = () => {
return async (ctx, next) => {
const { user } = ctx.session;
if (user) ctx.state = { ...ctx.state, user };
await next();
};
};
Next, we can register all three middlewares by updating our router file as shown:
// ./middleware/router.js
const authenticated = require('./authenticated');
const guest = require('./guest');
const user = require('./user');
router.use(user());
const auth = new KoaRouter()
.get('/', guest(), authController.index)
.post('/login', authController.login)
.post('/register', authController.register)
.get('/logout', authController.logout);
router.use('/auth', auth.routes());
Now we can register, sign in, and sign out of our app! Next, we will implement the different actions needed for our blog posts.