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