All files / src middlewares.ts

100% Statements 26/26
100% Branches 2/2
100% Functions 8/8
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 59 60 61  8x     8x       34x 34x 34x     8x       22x 22x 22x 21x       2x 2x   20x     8x       17x 17x       16x     8x       4x 4x 4x     4x 1x     1x 1x   3x    
import { Context } from 'aws-lambda';
import { DeviceVerification } from './devices';
import { AppAccessContext } from './types.d';
 
export const logMiddleware = async (
  event: any,
  context: Context,
  next: any,
) => {
  console.log('receive event ', event, 'context', context);
  return next(event, context);
};
 
export const accessTokenMiddleware = async (
  event: any,
  context: AppAccessContext,
  next: any,
) => {
  try {
    context.accessToken = event.request.headers.authorization;
    await context.app
      .get(DeviceVerification)
      .checkAccessToken(context.accessToken);
  } catch (err) {
    console.error(err);
    throw new Error('Access token is invalid.');
  }
  return next(event, context);
};
 
export const checkDeviceStatusMiddleware = async (
  event: any,
  context: AppAccessContext,
  next: any,
) => {
  await context.app
    .get(DeviceVerification)
    .checkDeviceStatus(context.accessToken);
 
  return next(event, context);
};
 
export const validateDeviceTokenMiddleware = async (
  event: any,
  context: AppAccessContext,
  next: any,
) => {
  try {
    const isDeviceTokenValid = await context.app
      .get(DeviceVerification)
      .isDeviceTokenValid(event.args.deviceUuid, context.accessToken);
    if (!isDeviceTokenValid) {
      throw new Error("Access token and device id don't match.");
    }
  } catch (err) {
    console.error(err);
    throw err;
  }
  return next(event, context);
};