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