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