All files / lib/channels channels.utils.ts

79.17% Statements 19/24
71.43% Branches 20/28
66.67% Functions 4/6
75% Lines 15/20

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 62 63 64                    1x   1x 48x     48x 48x     1x                   58x 58x 29x           1x 4x     1x 48x 48x         1x                            
import { Ability, AnyAbility } from "@casl/ability";
 
import { Application, HookContext } from "@feathersjs/feathers";
import { RealTimeConnection } from "@feathersjs/transport-commons/lib/channels/channel/base";
 
import {
  ChannelOptions,
  InitOptions
} from "../types";
 
import { getContextPath } from "../utils/getDefaultModelName";
 
export const makeOptions = (app: Application, options?: Partial<ChannelOptions>): ChannelOptions => {
  Iif (!app) {
    throw new Error("feathers-casl: You need to provide an 'app' to the channels:makeOptions function");
  }
  options = options || {};
  return Object.assign({}, defaultOptions, getAppOptions(app), options);
};
 
const defaultOptions: ChannelOptions = {
  activated: true,
  channelOnError: ["authenticated"],
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  ability: ((app: Application, connection: RealTimeConnection, data: Record<string, unknown>, context: HookContext): Ability => {
    return connection.ability;
  }),
  modelName: getContextPath,
  restrictFields: true,
  availableFields: (context: HookContext): string[] => {
    const availableFields: string[] | ((context: HookContext) => string[]) = context.service.options?.casl?.availableFields;
    if (!availableFields) return undefined;
    return (typeof availableFields === "function")
      ? availableFields(context)
      : availableFields;
  }
};
 
export const makeDefaultOptions = (options?: Partial<ChannelOptions>): ChannelOptions => {
  return Object.assign({}, defaultOptions, options);
};
 
const getAppOptions = (app: Application): ChannelOptions | Record<string, never> => {
  const caslOptions: InitOptions = app?.get("casl");
  return (caslOptions && caslOptions.channels)
    ? caslOptions.channels
    : {};
};
 
export const getAbility = (
  app: Application, 
  data: Record<string, unknown>,
  connection: RealTimeConnection,
  context: HookContext,
  options: Partial<ChannelOptions>
): undefined | AnyAbility => {
  if (options.ability) {
    return (typeof options.ability === "function") ?
      options.ability(app, connection, data, context) :
      options.ability;
  } else {
    return connection.ability;
  }
};