All files / services/api/policies auth.policy.ts

0% Statements 0/18
0% Branches 0/7
0% Functions 0/3
0% Lines 0/17

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                                                                   
import { VersedMiddleware } from "@services/api/endpoints/definition-utils";
import { Context } from "@versed/context";
import { createVersedAxiosClient } from "@versed/core";
import config from "../../../../config/config";
import { ITokenService } from "@schemas/services/token/token.v1.service";
import tokenSpec from "@schemas/services/token/token.v1.service.json";
import { UnauthorizedError } from "@versed/error";
 
const client = createVersedAxiosClient();
const tokenService = client.createService<ITokenService>(tokenSpec, {
  basePath: config.services.token.url.get(),
});
 
export const AuthPolicy = (required = true): VersedMiddleware => async (
  ctx: Context,
  next: Function,
) => {
  ctx = ctx.child("auth middleware");
  const { accessToken } = ctx.meta as any;
 
  if (accessToken) {
    const { userId } = await tokenService.Auth(ctx, {
      accessToken: accessToken,
    });
    (ctx.meta as any).userId = userId;
  }
  if (required && !(ctx.meta as any).userId) {
    throw new UnauthorizedError();
  }
 
  ctx.end();
  next();
};