All files ability.js

100% Statements 71/71
94.23% Branches 49/52
100% Functions 17/17
100% Lines 70/70
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        141x 55x     86x   86x       40x     1x     1x       5x 2x     3x 3x       40x               40x       45x 45x   45x 45x 45x 45x     45x       45x 45x   45x 87x 87x   87x 128x 128x   128x 130x 130x 130x 130x         45x       95x 95x   95x 128x 8x     120x         47x       70x 70x   70x 27x     43x 49x 29x       14x       70x 70x 70x 70x   70x       3x       3x 1x         5x 5x   5x 4x     5x   5x 3x 2x 2x 2x           90x   90x 4x        
import { ForbiddenError } from './error';
import { Rule } from './rule';
 
function getSubjectName(subject) {
  if (!subject || typeof subject === 'string') {
    return subject;
  }
 
  const Type = typeof subject === 'object' ? subject.constructor : subject;
 
  return Type.modelName || Type.name;
}
 
function clone(object) {
  return JSON.parse(JSON.stringify(object));
}
 
const DEFAULT_ALIASES = {
  manage: ['create', 'read', 'update', 'delete'],
};
const PRIVATE_FIELD = typeof Symbol !== 'undefined' ? Symbol.for('private') : `__private${Date.now()}`;
 
export class Ability {
  static addAlias(alias, actions) {
    if (alias === actions || Array.isArray(actions) && actions.indexOf(alias) !== -1) {
      throw new Error(`Attempt to alias action to itself: ${alias} -> ${actions.toString()}`);
    }
 
    DEFAULT_ALIASES[alias] = actions;
    return this;
  }
 
  constructor(rules, { RuleType = Rule, subjectName = getSubjectName } = {}) {
    this[PRIVATE_FIELD] = {
      RuleType,
      subjectName,
      originalRules: rules,
      rules: {},
      events: {},
      aliases: clone(DEFAULT_ALIASES)
    };
    this.update(rules);
  }
 
  update(rules) {
    Eif (Array.isArray(rules)) {
      const payload = { rules, ability: this };
 
      this.emit('update', payload);
      this[PRIVATE_FIELD].originalRules = Object.freeze(rules.slice(0));
      this[PRIVATE_FIELD].rules = this.buildIndexFor(this.rules);
      this.emit('updated', payload);
    }
 
    return this;
  }
 
  buildIndexFor(rules) {
    const indexedRules = {};
    const { RuleType } = this[PRIVATE_FIELD];
 
    for (let i = 0; i < rules.length; i++) {
      const rule = rules[i];
      const actions = this.expandActions(rule.actions);
 
      for (let j = 0; j < actions.length; j++) {
        const action = actions[j];
        const subjects = Array.isArray(rule.subject) ? rule.subject : [rule.subject];
 
        for (let k = 0; k < subjects.length; k++) {
          const subject = subjects[k];
          indexedRules[subject] = indexedRules[subject] || {};
          indexedRules[subject][action] = indexedRules[subject][action] || [];
          indexedRules[subject][action].unshift(new RuleType(rule));
        }
      }
    }
 
    return indexedRules;
  }
 
  expandActions(rawActions) {
    const actions = Array.isArray(rawActions) ? rawActions : [rawActions];
    const { aliases } = this[PRIVATE_FIELD];
 
    return actions.reduce((expanded, action) => {
      if (aliases.hasOwnProperty(action)) {
        return expanded.concat(this.expandActions(aliases[action]));
      }
 
      return expanded;
    }, actions);
  }
 
  get rules() {
    return this[PRIVATE_FIELD].originalRules;
  }
 
  can(action, subject) {
    const subjectName = this[PRIVATE_FIELD].subjectName(subject);
    const rules = this.rulesFor(action, subject);
 
    if (subject === subjectName) {
      return rules.length > 0 && !rules[0].inverted;
    }
 
    for (let i = 0; i < rules.length; i++) {
      if (rules[i].matches(subject)) {
        return !rules[i].inverted;
      }
    }
 
    return false;
  }
 
  rulesFor(action, subject) {
    const subjectName = this[PRIVATE_FIELD].subjectName(subject);
    const { rules } = this[PRIVATE_FIELD];
    const specificRules = rules.hasOwnProperty(subjectName) ? rules[subjectName][action] : null;
    const generalRules = rules.hasOwnProperty('all') ? rules.all[action] : null;
 
    return (specificRules || []).concat(generalRules || []);
  }
 
  cannot(action, subject) {
    return !this.can(action, subject);
  }
 
  throwUnlessCan(action, subject) {
    if (this.cannot(action, subject)) {
      throw new ForbiddenError(`Cannot execute "${action}" on "${this[PRIVATE_FIELD].subjectName(subject)}"`);
    }
  }
 
  on(event, handler) {
    const { events } = this[PRIVATE_FIELD];
    let isAttached = true;
 
    if (!events[event]) {
      events[event] = [];
    }
 
    events[event].push(handler);
 
    return () => {
      if (isAttached) {
        const index = events[event].indexOf(handler);
        events[event].splice(index, 1);
        isAttached = false;
      }
    };
  }
 
  emit(event, payload) {
    const handlers = this[PRIVATE_FIELD].events[event];
 
    if (handlers) {
      handlers.forEach(handler => handler(payload));
    }
  }
}