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