BrightSide Workbench Full Report + Source Code
FlatPermissions.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2022 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.security;
20 
21 import java.util.List;
22 import java.util.TreeMap;
23 import java.util.TreeSet;
24 import org.turro.actor.Actors;
25 import org.turro.elephant.context.Application;
26 import org.turro.plugin.contacts.IContact;
27 import org.turro.reflection.Reflections;
28 
33 public class FlatPermissions extends TreeMap<String, TreeSet<String>> {
34 
35  public boolean isInRole(String role) {
36  String[] roles = role.split("\\s*\\|\\s*");
37  for(String r : roles) {
38  if(checkRole(r)) return true;
39  }
40  return false;
41  }
42 
43  public boolean anyKeyMatch(List<String> roles) {
44  return roles.stream().anyMatch(role -> containsKey(role));
45  }
46 
47  public PermissionMap asMap() {
48  return new PermissionMap(this);
49  }
50 
51  public void addPermissions(TreeMap<String, TreeSet<String>> rolePermissions) {
52  rolePermissions.entrySet().forEach(entry -> {
53  TreeSet<String> set = get(entry.getKey());
54  if(set == null) set = new TreeSet<>();
55  set.addAll(entry.getValue());
56  put(entry.getKey(), set);
57  });
58  }
59 
60  protected boolean isActor(IContact contact, String actor) {
61  if(contact == null) contact = (IContact) Application.getUser();
62  return Actors.isActor(contact, actor);
63  }
64 
65  private boolean checkRole(String role) {
66  String[] value = role.split("\\s*:\\s*");
67  if(value.length == 2) {
68  if(role.startsWith("class:")) {
69  return Reflections.exist(role.substring(6));
70  } else if("@actor".equals(value[0])) {
71  return isActor(null, value[1]);
72  } else if(containsKey(value[0])) {
73  return get(value[0]).contains(value[1]);
74  }
75  }
76  return false;
77  }
78 
79 }
static boolean isActor(String actor)
Definition: Actors.java:45
boolean anyKeyMatch(List< String > roles)
boolean isActor(IContact contact, String actor)
void addPermissions(TreeMap< String, TreeSet< String >> rolePermissions)