Cleanup project's name in Sonar
[aai/search-data-service.git] / src / main / java / org / openecomp / sa / auth / SearchDbServiceAuthCore.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.openecomp.sa.auth;
24
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import org.json.simple.parser.JSONParser;
29 import org.json.simple.parser.ParseException;
30 import org.openecomp.cl.api.Logger;
31 import org.openecomp.cl.eelf.LoggerFactory;
32 import org.openecomp.sa.searchdbabstraction.util.SearchDbConstants;
33
34 import java.io.File;
35 import java.io.FileNotFoundException;
36 import java.io.FileReader;
37 import java.io.IOException;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Timer;
43
44 public class SearchDbServiceAuthCore {
45
46   private static Logger logger = LoggerFactory.getInstance()
47       .getLogger(SearchDbServiceAuthCore.class.getName());
48
49   private static String GlobalAuthFileName = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME;
50
51   private static enum HTTP_METHODS {
52     POST, GET, PUT, DELETE
53   }
54
55   ;
56
57   // Don't instantiate
58   private SearchDbServiceAuthCore() {
59   }
60
61   private static boolean usersInitialized = false;
62   private static HashMap<String, SearchDbAuthUser> users;
63   private static boolean timerSet = false;
64   private static Timer timer = null;
65
66   public synchronized static void init() {
67
68
69     SearchDbServiceAuthCore.getConfigFile();
70     SearchDbServiceAuthCore.reloadUsers();
71
72   }
73
74   public static void cleanup() {
75     timer.cancel();
76   }
77
78   public static String getConfigFile() {
79     if (GlobalAuthFileName == null) {
80       String nc = SearchDbConstants.SDB_AUTH_CONFIG_FILENAME;
81       if (nc == null) {
82         nc = "/home/aaiadmin/etc/aaipolicy.json";
83       }
84
85       GlobalAuthFileName = nc;
86     }
87     return GlobalAuthFileName;
88   }
89
90   public synchronized static void reloadUsers() {
91     users = new HashMap<String, SearchDbAuthUser>();
92
93
94     ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
95     JSONParser parser = new JSONParser();
96     try {
97       Object obj = parser.parse(new FileReader(GlobalAuthFileName));
98       // aailogger.debug(logline, "Reading from " + GlobalAuthFileName);
99       JsonNode rootNode = mapper.readTree(new File(GlobalAuthFileName));
100       JsonNode rolesNode = rootNode.path("roles");
101
102       for (JsonNode roleNode : rolesNode) {
103         String roleName = roleNode.path("name").asText();
104
105         TabularAuthRole authRole = new TabularAuthRole();
106         JsonNode usersNode = roleNode.path("users");
107         JsonNode functionsNode = roleNode.path("functions");
108         for (JsonNode functionNode : functionsNode) {
109           String function = functionNode.path("name").asText();
110           JsonNode methodsNode = functionNode.path("methods");
111           boolean hasMethods = false;
112           for (JsonNode methodNode : methodsNode) {
113             String methodName = methodNode.path("name").asText();
114             hasMethods = true;
115             String thisFunction = methodName + ":" + function;
116
117             authRole.addAllowedFunction(thisFunction);
118           }
119
120           if (hasMethods == false) {
121             // iterate the list from HTTP_METHODS
122             for (HTTP_METHODS meth : HTTP_METHODS.values()) {
123               String thisFunction = meth.toString() + ":" + function;
124
125               authRole.addAllowedFunction(thisFunction);
126             }
127           }
128
129         }
130         for (JsonNode userNode : usersNode) {
131           // make the user lower case
132           String username = userNode.path("username").asText().toLowerCase();
133           SearchDbAuthUser authUser = null;
134           if (users.containsKey(username)) {
135             authUser = users.get(username);
136           } else {
137             authUser = new SearchDbAuthUser();
138           }
139
140
141           authUser.setUser(username);
142           authUser.addRole(roleName, authRole);
143           users.put(username, authUser);
144         }
145       }
146     } catch (FileNotFoundException fnfe) {
147       logger.debug("Failed to load the policy file ");
148
149     } catch (ParseException e) {
150       logger.debug("Failed to Parse the policy file ");
151
152     } catch (JsonProcessingException e) {
153       logger.debug("JSON processing error while parsing policy file: " + e.getMessage());
154
155     } catch (IOException e) {
156       logger.debug("IO Exception while parsing policy file: " + e.getMessage());
157     }
158
159     usersInitialized = true;
160
161   }
162
163   public static class SearchDbAuthUser {
164     public SearchDbAuthUser() {
165       this.roles = new HashMap<String, TabularAuthRole>();
166     }
167
168     private String username;
169     private HashMap<String, TabularAuthRole> roles;
170
171     public String getUser() {
172       return this.username;
173     }
174
175     public HashMap<String, TabularAuthRole> getRoles() {
176       return this.roles;
177     }
178
179     public void addRole(String roleName, TabularAuthRole authRole) {
180       this.roles.put(roleName, authRole);
181     }
182
183     public boolean checkAllowed(String checkFunc) {
184       for (Map.Entry<String, TabularAuthRole> roleEntry : this.roles.entrySet()) {
185         TabularAuthRole role = roleEntry.getValue();
186         if (role.hasAllowedFunction(checkFunc)) {
187           // break out as soon as we find it
188           return true;
189         }
190       }
191       // we would have got positive confirmation had it been there
192       return false;
193     }
194
195     public void setUser(String myuser) {
196       this.username = myuser;
197     }
198
199   }
200
201   public static class TabularAuthRole {
202     public TabularAuthRole() {
203       this.allowedFunctions = new ArrayList<String>();
204     }
205
206     private List<String> allowedFunctions;
207
208     public void addAllowedFunction(String func) {
209       this.allowedFunctions.add(func);
210     }
211
212     public void delAllowedFunction(String delFunc) {
213       if (this.allowedFunctions.contains(delFunc)) {
214         this.allowedFunctions.remove(delFunc);
215       }
216     }
217
218     public boolean hasAllowedFunction(String afunc) {
219       if (this.allowedFunctions.contains(afunc)) {
220         return true;
221       } else {
222         return false;
223       }
224     }
225   }
226
227   public static HashMap<String, SearchDbAuthUser> getUsers(String key) {
228     if (!usersInitialized || (users == null)) {
229       reloadUsers();
230     }
231     return users;
232   }
233
234   public static boolean authorize(String username, String authFunction) {
235     // logline.init(component, transId, fromAppId, "authorize()");
236
237     if (!usersInitialized || (users == null)) {
238       init();
239     }
240     if (users.containsKey(username)) {
241       if (users.get(username).checkAllowed(authFunction) == true) {
242
243         return true;
244       } else {
245
246
247         return false;
248       }
249     } else {
250
251       return false;
252     }
253   }
254 }