All files / backend/koa-middleware isLoggedIn.js

100% Statements 8/8
100% Branches 6/6
100% Functions 2/2
100% Lines 8/8
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 461x                                                                 14x 139x 20x 20x 20x     119x       1x  
const HttpError = require('./HttpError');
 
/**
 * @swagger
 * definition:
 *   AuthError:
 *     description:
 *       HTTP status code 401.
 *       User is not authenticated. Mainly returned on missing or expired JWT.
 *
 *     properties:
 *       errorId:
 *         type: string
 *         format: uuid
 *
 *       errorCode:
 *         type: string
 *         example: NO_AUTH
 *
 *       errorMessage:
 *         type: string
 *         example: You must login with a valid JWT
 */
 
/**
 * Checks over already loaded `ctx.state.user` to determine
 * if the API that uses this middleware have access to DB user info.
 *
 * @category middleware
 *
 * @return {Function} koa wrapper middleware
 */
function isLoggedIn() {
  return async (ctx, next) => {
    if (!((ctx.state || {}).user || {}).id) {
      const error = new HttpError(401, 'NO_AUTH', 'You must login with a valid JWT');
      ctx.app.emit('error', error, ctx);
      return;
    }
 
    return next();
  };
}
 
module.exports = isLoggedIn;