All files / lib/hooks/authorize authorize.hook.before.ts

88.76% Statements 79/89
84.52% Branches 71/84
100% Functions 2/2
92.77% Lines 77/83

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 2171x 1x 1x 1x   1x             1x 1x 1x 1x   1x                                   1x   1x 270x   270x         270x   270x     270x       270x   270x 270x   156x     114x 8x     106x                 86x   43x 25x   18x       43x 38x       86x           86x       86x             26x 26x 26x 26x 26x   26x   26x               22x 5x   5x       17x 13x 13x 4x         4x     4x 1x 1x         3x 1x     2x 2x       7x 60x     36x 9x 9x       9x 1x 1x       36x     22x       22x   22x 22x 5x   17x                   36x 24x       20x 20x 32x               16x     4x      
import { Forbidden } from "@feathersjs/errors";
import _isEmpty from "lodash/isEmpty";
import _pick from "lodash/pick";
import { subject } from "@casl/ability";
 
import {
  mergeQuery,
  shouldSkip,
  pushSet,
  isMulti
} from "feathers-utils";
 
import getQueryFor from "../../utils/getQueryFor";
import hasRestrictingFields from "../../utils/hasRestrictingFields";
import hasRestrictingConditions from "../../utils/hasRestrictingConditions";
import couldHaveRestrictingFields from "../../utils/couldHaveRestrictingFields";
 
import {
  hide$select,
  setPersistedConfig,
  checkMulti,
  getAbility,
  throwUnlessCan
} from "./authorize.hook.utils";
 
import {
  HookContext
} from "@feathersjs/feathers";
 
import {
  AuthorizeHookOptions,
  GetQueryOptions,
  HasRestrictingFieldsOptions
} from "../../types";
 
const HOOKNAME = "authorize";
 
export default (options: AuthorizeHookOptions): ((context: HookContext) => Promise<HookContext>) => {
  return async (context: HookContext): Promise<HookContext> => {
    //TODO: make as isomorphic hook -> for vue-client
    Iif (
      shouldSkip(HOOKNAME, context) ||
      context.type !== "before" ||
      !context.params
    ) { return context; }
    const { service, method, id, params } = context;
 
    Iif (!options.modelName) {
      return context;
    }
    const modelName = (typeof options.modelName === "string")
      ? options.modelName
      : options.modelName(context);
 
    Iif (!modelName) { return context; }
 
    const ability = await getAbility(context, options);
    if (!ability) {
      // Ignore internal or not authenticated requests
      return context;
    }
 
    if (options.checkMultiActions) {
      checkMulti(context, ability, modelName, options);
    }
 
    throwUnlessCan(
      ability,
      method,
      modelName,
      modelName,
      options.actionOnForbidden
    );
    
    // if context is with multiple items, there's a change that we need to handle each item separately
    if (isMulti(context)) {
      // if has conditions -> hide $select for after-hook, because
      if (hasRestrictingConditions(ability, "find", modelName)) {
        hide$select(context);
      } else {
        setPersistedConfig(context, "skipRestrictingRead.conditions", true);
      }
 
      // if has no restricting fields at all -> can skip _pick() in after-hook
      if (!couldHaveRestrictingFields(ability, "find", modelName)) {
        setPersistedConfig(context, "skipRestrictingRead.fields", true);
      }
    }
 
    const availableFields = (!options?.availableFields)
      ? undefined
      : (typeof options.availableFields === "function")
        ? options.availableFields(context)
        : options.availableFields;
 
    const hasRestrictingFieldsOptions: HasRestrictingFieldsOptions = {
      availableFields: availableFields
    };
 
    if (["get", "patch", "update", "remove"].includes(method) && id != null) {
      // single: get | patch | update | remove
 
      // get complete item for `throwUnlessCan`-check to be trustworthy
      // -> initial 'get' and 'remove' have no data at all
      // -> initial 'patch' maybe has just partial data
      // -> initial 'update' maybe has completely changed data, for what the check could pass but not for initial data
      const queryGet = Object.assign({}, params.query || {});
      delete queryGet.$select;
      const paramsGet = Object.assign({}, params, { query: queryGet });
      paramsGet.skipHooks = (params.skipHooks?.slice()) || [];
      pushSet(paramsGet, "skipHooks", `${HOOKNAME}`, { unique: true });
 
      const item = await service.get(id, paramsGet);
 
      throwUnlessCan(
        ability,
        method,
        subject(modelName, item),
        modelName,
        options.actionOnForbidden
      );
 
      if (method === "get") {
        context.result = item;
        //pushSet(context, "params.skipHooks", "after");
        return context;
      }
 
      // ensure that only allowed data gets changed
      if (["update", "patch"].includes(method)) {
        const fields = hasRestrictingFields(ability, method, subject(modelName, item), hasRestrictingFieldsOptions);
        if (!fields) { return context; }
        Iif (fields === true || fields.length === 0) {
          if (options.actionOnForbidden) { options.actionOnForbidden(); }
          throw new Forbidden("You're not allowed to make this request");
        }
        
        const data = _pick(context.data, fields);
 
        // if fields are not overlapping -> throw
        if (_isEmpty(data)) {
          Iif (options.actionOnForbidden) { options.actionOnForbidden(); }
          throw new Forbidden("You're not allowed to make this request");
        }
 
        //TODO: if some fields not match -> `actionOnForbiddenUpdate`
 
        if (method === "patch") {
          context.data = data;
        } else {
          // merge with initial data
          const itemPlain = await service._get(id);
          context.data = Object.assign({}, itemPlain, data);
        }
      }
 
      return context;
    } else if (method === "find" || (["patch", "remove"].includes(method) && id == null)) {
      // multi: find | patch | remove
 
      if (method === "patch") {
        const fields = hasRestrictingFields(ability, method, modelName, { availableFields });
        Iif (fields === true) {
          if (options.actionOnForbidden) { options.actionOnForbidden(); }
          throw new Forbidden("You're not allowed to make this request");
        }
        if (fields && fields.length > 0) {
          const data = _pick(context.data, fields);
          context.data = data;
        }
      }
      
      if (hasRestrictingConditions(ability, method, modelName)) {
        // TODO: if query and context.params.query differ -> separate calls
        
        const getQueryOptions: GetQueryOptions = {
          skipFields: true,
          availableFields
        };
        const query = getQueryFor(ability, method, modelName, getQueryOptions);
 
        Eif (!_isEmpty(query)) {
          if (!context.params.query) {
            context.params.query = query;
          } else {
            context.params.query = mergeQuery(
              context.params.query, 
              query, { 
                defaultHandle: "intersect",
                service
              });
          }
        }
      }
 
      return context;
    } else if (method === "create") {
      // create: single | multi
      
      // we have all information we need (maybe we need populated data?)
      const data = (Array.isArray(context.data)) ? context.data : [context.data];
      for (let i = 0; i < data.length; i++) {
        throwUnlessCan(
          ability,
          method,
          subject(modelName, data[i]),
          modelName,
          options.actionOnForbidden
        );
      }
      return context;
    }
 
    return context;
  };
};