All files / backend/koa-middleware jwtToUser.js

100% Statements 17/17
100% Branches 14/14
100% Functions 6/6
100% Lines 15/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591x                             5x 3x     5x 5x   5x 3x     2x           2x   2x             2x   2x                 3x   2x     1x  
const {Sequelize} = require('../../database/config/sequelize-pool');
 
/**
 * if some of the previous Koa middlewares loaded the JWT into `ctx.state.jwtdata`
 * then this middleware loads user data and user permissions from the DB
 * into `ctx.state.user` and `ctx.state.userPermissions`.
 *
 * @category middleware
 *
 * @param {Object} ctx Koa context
 * @param {Function} next Koa next middleware
 *
 * @return {Function} In the end, calls `next`
 */
async function jwtToUser(ctx, next) {
  if (!ctx.state) {
    ctx.state = {};
  }
 
  ctx.state.user = {};
  ctx.state.userPermissions = [];
 
  if (!ctx.state.jwtdata || !ctx.state.jwtdata.userId) {
    return next();
  }
 
  ctx.state.user = await ctx.postgres.Users
      .findOne({
        where: {
          id: ctx.state.jwtdata.userId,
        },
      })
      .then((response) => response && typeof response.toJSON === 'function' ? response.toJSON() : {});
 
  const permissionIds = await ctx.postgres.UserPermissions
      .findAll({
        attributes: ['permissionId'],
        where: {
          userId: ctx.state.jwtdata.userId,
        },
      })
      .then((responses) => Array.isArray(responses) ? responses.map(({permissionId}) => permissionId) : []);
 
  ctx.state.userPermissions = await ctx.postgres.Permissions
      .findAll({
        attributes: ['key'],
        where: {
          id: {
            [Sequelize.Op.in]: permissionIds,
          },
        },
      })
      .then((responses) => Array.isArray(responses) ? responses.map(({key}) => key) : []);
 
  return next();
}
 
module.exports = jwtToUser;