AAI-1523 Batch reformat aai-auth
[aai/aai-common.git] / aai-auth / src / main / java / org / onap / aaiauth / auth / AuthCore.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 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
22 package org.onap.aaiauth.auth;
23
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26
27 import java.io.File;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32
33 import org.onap.aaiauth.util.AuthConstants;
34
35 public class AuthCore {
36
37     private String authFilename;
38     public ObjectMapper mapper;
39
40     private enum HTTP_METHODS {
41         POST, GET, PUT, DELETE, PATCH
42     }
43
44     public AuthCore(String filename) throws Exception {
45         this.authFilename = filename;
46         loadUsers(filename);
47     }
48
49     private static boolean usersInitialized = false;
50     private static HashMap<String, AuthUser> users;
51
52     public String getConfigFile() {
53         return this.authFilename;
54     }
55
56     /**
57      * Loads the auth file and caches a list of authorized users.
58      * 
59      * @param authFilename
60      *        - Absolute path of the file where authorized users are listed.
61      */
62     public synchronized void loadUsers(String authFilename) throws Exception {
63         users = new HashMap<>();
64
65         mapper = new ObjectMapper(); // can reuse, share globally
66         JsonNode rootNode = mapper.readTree(new File(authFilename));
67         JsonNode rolesNode = rootNode.path(AuthConstants.ROLES_NODE_PATH);
68
69         for (JsonNode roleNode : rolesNode) {
70             String roleName = roleNode.path(AuthConstants.ROLE_NAME_PATH).asText();
71
72             AuthRole role = new AuthRole();
73             JsonNode usersNode = roleNode.path(AuthConstants.USERS_NODE_PATH);
74             JsonNode functionsNode = roleNode.path(AuthConstants.FUNCTIONS_NODE_PATH);
75             for (JsonNode functionNode : functionsNode) {
76                 String function = functionNode.path(AuthConstants.FUNCTION_NAME_PATH).asText();
77                 JsonNode methodsNode = functionNode.path(AuthConstants.METHODS_NODE_PATH);
78                 boolean hasMethods = handleMethodNode(methodsNode, role, function);
79
80                 if (!hasMethods) {
81                     // iterate the list from HTTP_METHODS
82                     for (HTTP_METHODS meth : HTTP_METHODS.values()) {
83                         String thisFunction = meth.toString() + ":" + function;
84
85                         role.addAllowedFunction(thisFunction);
86                     }
87                 }
88             }
89
90             handleUserNode(usersNode, roleName, role);
91         }
92
93         usersInitialized = true;
94     }
95
96     private boolean handleMethodNode(JsonNode methodsNode, AuthRole role, String function) {
97         boolean hasMethods = false;
98         for (JsonNode methodNode : methodsNode) {
99             String methodName = methodNode.path(AuthConstants.METHOD_NAME_PATH).asText();
100             hasMethods = true;
101             String thisFunction = methodName + ":" + function;
102
103             role.addAllowedFunction(thisFunction);
104         }
105         return hasMethods;
106     }
107
108     private void handleUserNode(JsonNode usersNode, String roleName, AuthRole role) {
109         for (JsonNode userNode : usersNode) {
110             // make the user lower case
111             String node = userNode.path(AuthConstants.USER_NODE_PATH).asText().toLowerCase();
112             AuthUser user;
113             if (users.containsKey(node)) {
114                 user = users.get(node);
115             } else {
116                 user = new AuthUser();
117             }
118
119             user.setUser(node);
120             user.addRole(roleName, role);
121             users.put(node, user);
122         }
123     }
124
125     public class AuthUser {
126
127         public AuthUser() {
128             this.roles = new HashMap<>();
129         }
130
131         private String username;
132         private HashMap<String, AuthRole> roles;
133
134         public String getUser() {
135             return this.username;
136         }
137
138         public Map<String, AuthRole> getRoles() {
139             return this.roles;
140         }
141
142         public void addRole(String roleName, AuthRole role) {
143             this.roles.put(roleName, role);
144         }
145
146         /**
147          * Returns true if the user has permissions for the function, otherwise returns false.
148          * 
149          * @param checkFunc
150          *        - String value of the function.
151          */
152         public boolean checkAllowed(String checkFunc) {
153             for (Map.Entry<String, AuthRole> roleEntry : this.roles.entrySet()) {
154                 AuthRole role = roleEntry.getValue();
155                 if (role.hasAllowedFunction(checkFunc)) {
156                     // break out as soon as we find it
157                     return true;
158                 }
159             }
160             // we would have got positive confirmation had it been there
161             return false;
162         }
163
164         public void setUser(String myuser) {
165             this.username = myuser;
166         }
167     }
168
169     public static class AuthRole {
170
171         public AuthRole() {
172             this.allowedFunctions = new ArrayList<>();
173         }
174
175         private List<String> allowedFunctions;
176
177         public void addAllowedFunction(String func) {
178             this.allowedFunctions.add(func);
179         }
180
181         /**
182          * Remove the function from the user's list of allowed functions.
183          * 
184          * @param delFunc
185          *        - String value of the function.
186          */
187         public void delAllowedFunction(String delFunc) {
188             if (this.allowedFunctions.contains(delFunc)) {
189                 this.allowedFunctions.remove(delFunc);
190             }
191         }
192
193         /**
194          * Returns true if the user has permissions to use the function, otherwise returns false.
195          * 
196          * @param afunc
197          *        - String value of the function.
198          */
199         public boolean hasAllowedFunction(String afunc) {
200             return this.allowedFunctions.contains(afunc);
201         }
202     }
203
204     /**
205      * Returns a hash-map of all users which have been loaded and initialized.
206      */
207     public Map<String, AuthUser> getUsers(String key) throws Exception {
208         if (!usersInitialized || (users == null)) {
209             loadUsers(this.authFilename);
210         }
211         return users;
212     }
213
214     /**
215      * Returns true if the user is allowed to access a function.
216      * 
217      * @param username
218      *        - String value of user
219      * @param authFunction
220      *        - String value of the function.
221      */
222     public boolean authorize(String username, String authFunction) {
223         AuthUser user = users.get(username);
224         return user != null && user.checkAllowed(authFunction);
225     }
226 }