1 <?php # vim:ts=2:sw=2:et:
2 /* For licensing and copyright terms, see the file named LICENSE */
4 class MTrackAuthorizationException extends Exception {
6 function __construct($msg, $rights) {
7 parent::__construct($msg);
8 $this->rights = $rights;
12 /* Each object in the system has an identifier, like 'ticket:XYZ' that
13 * indicates the type of object as well as its own identifier.
15 * Each object may also have a discressionary access control list (DACL) that
16 * describes what actions members of particular roles are permitted to
17 * the object. The DACL can apply either to the object itself, or be
18 * a cascading (or inherited) entry that applies only to objects that are
19 * children of the object in question.
21 * When determining whether access is permitted, the DACL is walked from
22 * the object being accessed up to the root. As soon as the allow/deny
23 * status us known for a specific (role, action) combination, the search
26 * DACL entries can be explicitly ordered so that a particular user from
27 * a group can be excepted from a blanket allow/deny rule that follows.
31 static $cache = array();
33 static public function addRootObjectAndRoles($name) {
34 /* construct some roles that encapsulate read, modify, write */
35 $rolebase = preg_replace('/s$/', '', $name);
38 array("{$rolebase}Viewer", "read", true),
39 array("{$rolebase}Editor", "read", true),
40 array("{$rolebase}Editor", "modify", true),
41 array("{$rolebase}Creator", "read", true),
42 array("{$rolebase}Creator", "modify", true),
43 array("{$rolebase}Creator", "create", true),
44 array("{$rolebase}Creator", "delete", true),
46 MTrackACL::setACL($name, true, $ents);
48 array("{$rolebase}Viewer", "read", true),
49 array("{$rolebase}Editor", "read", true),
50 array("{$rolebase}Creator", "read", true),
51 array("{$rolebase}Creator", "modify", true),
52 array("{$rolebase}Creator", "create", true),
53 array("{$rolebase}Creator", "delete", true),
55 MTrackACL::setACL($name, false, $ents);
58 /* functions that we can call to determine ancestry */
59 static $genealogist = array();
60 static public function registerAncestry($objtype, $func) {
61 self::$genealogist[$objtype] = $func;
64 /* returns the objectid path that leads from the root to the specified
65 * object, including the object itself as the last element */
66 static public function getParentPath($objectid, $steps = -1)
69 while (strlen($objectid)) {
70 if ($steps != -1 && $steps-- == 0) {
74 if (isset(self::$genealogist[$objectid])) {
75 $func = self::$genealogist[$objectid];
76 if (is_string($func)) {
79 $parent = call_user_func($func, $objectid);
85 if (preg_match("/^(.*):([^:]+)$/", $objectid, $M)) {
87 if (isset(self::$genealogist[$class])) {
88 $func = self::$genealogist[$class];
89 if (is_string($func)) {
92 $parent = call_user_func($func, $objectid);
106 /* computes the overall ACL as it applies to someone that belongs to the
107 * indicated set of roles. */
108 static public function computeACL($objectid, $role_list)
110 $key = $objectid . '~' . join('~', $role_list);
112 if (isset(self::$cache[$key])) {
113 return self::$cache[$key];
116 /* we calculate the path to the object from its parent, and pull
117 * out all ACL entries on those objects that match the provided
118 * role list, ordering from the object up to the root.
122 $db = MTrackDB::get();
123 foreach ($role_list as $r => $rname) {
124 $rlist[] = $db->quote($r);
126 // Always want the special wildcard 'everybody' entry
127 $rlist[] = $db->quote('*');
128 $role_list = join(',', $rlist);
133 $path = self::getParentPath($objectid);
134 foreach ($path as $oid) {
135 $oidlist[] = $db->quote($oid);
137 $oidlist = join(',', $oidlist);
140 select objectid as id, action, cascade, allow
145 and objectid in ($oidlist)
154 # Collect the results and index by objectid; we'll need to walk over
156 $res_by_oid = array();
158 foreach (MTrackDB::q($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) {
159 $res_by_oid[$row['id']][] = $row;
161 foreach ($path as $oid) {
162 if (!isset($res_by_oid[$oid])) continue;
163 foreach ($res_by_oid[$oid] as $row) {
165 if ($row['id'] == $objectid && $row['cascade']) {
166 /* ignore items below the object of interest */
170 if (!isset($actions[$row['action']])) {
171 $actions[$row['action']] = $row['allow'] ? true : false;
176 self::$cache[$key] = $actions;
181 /* Entries is an array of [role, action, allow] tuples in the order
182 * that they should be checked.
183 * If cascade is true, then these entries will replace the
184 * inheritable set, otherwise they will replace the entries
186 * If entries is an empty array, or not an array, then the appropriate
187 * ACL will be removed.
189 static public function setACL($object, $cascade, $entries)
191 self::$cache = array();
193 $cascade = (int)$cascade;
194 MTrackDB::q('delete from acl where objectid = ? and cascade = ?',
197 if (is_array($entries)) {
198 foreach ($entries as $ent) {
199 if (isset($ent['role'])) {
200 $role = $ent['role'];
201 $action = $ent['action'];
202 $allow = $ent['allow'];
204 list($role, $action, $allow) = $ent;
206 MTrackDB::q('insert into acl (objectid, cascade, seq, role,
207 action, allow) values (?, ?, ?, ?, ?, ?)',
208 $object, $cascade, $seq++,
209 $role, $action, (int)$allow);
214 /* Obtains the ACL entries for the specified object.
215 * If cascade is true, it will return the inheritable ACL.
217 static public function getACL($object, $cascade)
219 return MTrackDB::q('select role, action, allow from acl
220 where objectid = ? and cascade = ? order by seq',
221 $object, (int)$cascade)->fetchAll(PDO::FETCH_ASSOC);
224 static public function hasAllRights($object, $rights)
226 if (MTrackAuth::getUserClass() == 'admin') {
229 if (!is_array($rights)) {
230 $rights = array($rights);
232 if (!count($rights)) {
233 throw new Exception("can't have all of no rights");
235 $acl = self::computeACL($object, MTrackAuth::getGroups());
236 # echo "ACL: $object<br>";
242 foreach ($rights as $action) {
243 if (!isset($acl[$action]) || !$acl[$action]) {
250 static public function hasAnyRights($object, $rights)
252 if (MTrackAuth::getUserClass() == 'admin') {
255 if (!is_array($rights)) {
256 $rights = array($rights);
258 if (!count($rights)) {
259 throw new Exception("can't have any of no rights");
261 $acl = self::computeACL($object, MTrackAuth::getGroups());
264 foreach ($rights as $action) {
265 if (isset($acl[$action]) && $acl[$action]) {
272 static public function requireAnyRights($object, $rights)
274 if (!self::hasAnyRights($object, $rights)) {
275 throw new MTrackAuthorizationException("Not authorized", $rights);
279 static public function requireAllRights($object, $rights)
281 if (!self::hasAllRights($object, $rights)) {
282 throw new MTrackAuthorizationException("Not authorized", $rights);
286 /* helper for generating an ACL editor.
287 * As parameters, takes an objectid indicating the object being edited,
288 * and an action map which breaks down tasks into groups.
289 * Each group consists of a set of permissions, starting with the least
290 * permissive in that group, through to most permissive.
291 * Each group will be rendered as a select box, and a synthetic "none"
292 * entry will be generated for the group that explicitly excludes each
293 * of the other permission levels in that group.
295 * The form element that is generated will contain a JSON representation
296 * of an "ents" array that can be passed to setACL().
298 static public function renderACLForm($formprefix, $objectid, $map) {
299 $ident = preg_replace("/[^a-zA-Z]/", '', $formprefix);
301 $groups = MTrackAuth::enumGroups();
303 foreach (MTrackDB::q('select userid, fullname from userinfo where active = 1')
304 ->fetchAll() as $row) {
305 if (isset($groups[$row[0]])) continue;
306 if (strlen($row[1])) {
307 $disp = "$row[0] - $row[1]";
311 $groups[$row[0]] = $disp;
313 if (!isset($groups['*'])) {
314 $groups['*'] = '(Everybody)';
317 // Encode the map into an object
318 $mobj = new stdClass;
323 foreach ($map as $group => $actions) {
324 // Each subsequent action in a group implies access greater than
325 // the item that preceeds it
327 $all_perms = array_keys($actions);
329 foreach ($all_perms as $p) {
330 $prohibit[$p] = "-$p";
332 $none = join('|', $prohibit);
334 $a[] = array($none, 'None');
337 foreach ($actions as $perm => $label) {
339 unset($prohibit[$perm]);
340 $p = join('|', array_merge($accum, $prohibit));
341 $a[] = array($p, $label);
342 /* save this for reverse engineering the right group in the current
344 $reng[$perm] = $group;
345 $rank[$group][$perm] = $i++;
347 $mobj->{$group} = $a;
349 $mobj = json_encode($mobj);
351 $roledefs = new stdclass;
352 $acl = self::getACL($objectid, 0);
353 foreach ($acl as $ent) {
354 $group = $reng[$ent['action']];
355 $act = ($ent['allow'] ? '' : '-') . $ent['action'];
356 $roledefs->{$ent['role']}->{$group}[] = $act;
358 if (!isset($groups[$ent['role']])) {
359 $groups[$ent['role']] = $ent['role'];
362 $roledefs = json_encode($roledefs);
364 /* let's figure out the inherited ACL */
365 $path = self::getParentPath($objectid, 2);
366 $inherited = new stdclass;
367 if (count($path) == 2) {
368 $pacl = self::getACL($path[1], 1);
369 foreach ($pacl as $ent) {
370 // Not relevant per the specified action map
371 if (!isset($reng[$ent['action']])) continue;
373 $group = $reng[$ent['action']];
374 $act = ($ent['allow'] ? '' : '-') . $ent['action'];
375 $inherited->{$ent['role']}->{$group}[] = $act;
377 if (!isset($groups[$ent['role']])) {
378 $groups[$ent['role']] = $ent['role'];
382 // Inheritable set may not be specified directly in
383 // the same terms as the action_map, so we need to infer it
384 // Example: we may have read|modify leaving delete unspecified.
385 // We treat this as read|modify|-delete
386 foreach ($inherited as $role => $agroups) {
387 foreach ($agroups as $group => $actions) {
389 foreach ($actions as $act) {
390 if ($act[0] == '-') continue;
391 if ($highest === null || $rank[$group][$act] > $highest) {
392 $highest = $rank[$group][$act];
396 if ($highest === null) {
397 unset($inherited->{$role}->{$group});
400 // Compute full value
402 foreach ($rank[$group] as $act => $i) {
403 if ($i <= $highest) {
409 $inherited->{$role}->{$group} = join('|', $comp);
413 $inherited = json_encode($inherited);
417 $groups = json_encode($groups);
418 $cat_order = json_encode(array_keys($map));
421 <div class='permissioneditor'>
426 <em>Select "Add" to define permissions for an entity.
427 The first matching permission is taken as definitive,
428 so if a given user belongs to multiple groups and matches
429 multiple permission rows, the first is taken. You may
430 drag to re-order permissions.
434 <em>Permissions inherited from the parent of this object are
435 shown as non-editable entries at the top of the list. You may
436 override them by adding your own explicit entry.</em>
439 <input type='hidden' id='$formprefix' name='$formprefix'>
440 <table id='acl$ident'>
449 $(document).ready(function () {
450 var cat_order = $cat_order;
451 var groups = $groups;
452 var roledefs = $roledefs;
453 var inherited = $inherited;
455 var disp = $('#acl$ident');
456 var tbody = $('tbody', disp);
458 var field = $('#$formprefix');
460 function add_acl_entity(role)
462 // Delete role from select box
463 $('option', sel).each(function () {
464 if ($(this).attr('value') == role) {
468 // Create a row for this role
469 var sp = $('<tr style="cursor:pointer"/>');
472 .html('<span style="position: absolute; margin-left: -1.3em" class="ui-icon ui-icon-arrowthick-2-n-s"></span>')
473 .append(groups[role])
477 for (var gi in cat_order) {
478 var group = cat_order[gi];
479 var gsel = $('<select/>');
480 gsel.data('acl.role', role);
481 var data = mobj[group];
482 for (var i in data) {
490 if (roledefs[role]) {
491 gsel.val(roledefs[role][group].join('|'));
498 var b = $('<button>x</button>');
503 b.click(function () {
513 var tr = $('thead tr', disp);
514 // Add columns for action groups
515 for (var gi in cat_order) {
516 var group = cat_order[gi];
517 tr.append($('<th/>').text(group));
519 // Add fixed inherited rows
520 var thead = $('thead', disp);
521 for (var role in inherited) {
522 tr = $('<tr class="inheritedacl"/>');
523 tr.append($('<td/>').text(groups[role]));
524 for (var group in mobj) {
525 var d = inherited[role][group];
527 // Good old fashioned look up (we don't have this hashed)
528 for (var i in mobj[group]) {
529 var ent = mobj[group][i];
535 tr.append($('<td/>').text(d));
537 tr.append($('<td>(Not Specified)</td>'));
542 sel = $('<select/>');
548 for (var i in groups) {
557 /* make the tbody sortable. Note that we append the "Add..." to the table,
558 * not the tbody, so that we don't allow dragging it around */
561 for (var role in roledefs) {
562 add_acl_entity(role);
565 sel.change(function () {
572 field.parents('form:first').submit(function () {
574 $('select', tbody).each(function () {
575 var role = $(this).data('acl.role');
576 var val = $(this).val().split('|');
580 if (action.substring(0, 1) == '-') {
582 action = action.substring(1);
584 acl.push([role, action, allow]);
587 field.val(JSON.stringify(acl));