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