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