a9d4ad54f0113815177485c2884387bab5f154fe
[aai/aai-common.git] / aai-auth / src / main / java / org / onap / aaiauth / auth / AuthCore.java
1 /**
2  * ============LICENSE_START=======================================================
3  * EcompAuth
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  *
22  * ECOMP and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25 package org.onap.aaiauth.auth;
26
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import java.io.File;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import org.onap.aaiauth.util.AuthConstants;
35
36
37 public class AuthCore {
38
39     private String authFilename;
40     public ObjectMapper mapper;
41
42     private enum HTTP_METHODS {
43         POST, GET, PUT, DELETE, PATCH
44     }
45
46     public AuthCore(String filename) throws Exception {
47         this.authFilename = filename;
48         loadUsers(filename);
49     }
50
51     private static boolean usersInitialized = false;
52     private static HashMap<String, AuthUser> users;
53
54     public String getConfigFile() {
55         return this.authFilename;
56     }
57
58     /**
59      * Loads the auth file and caches a list of authorized users.
60      * @param authFilename
61      *        -  Absolute path of the file where authorized users are listed.
62      */
63     public synchronized void loadUsers(String authFilename) throws Exception {
64         users = new HashMap<>();
65
66         mapper = new ObjectMapper(); // can reuse, share globally
67         JsonNode rootNode = mapper.readTree(new File(authFilename));
68         JsonNode rolesNode = rootNode.path(AuthConstants.ROLES_NODE_PATH);
69
70         for (JsonNode roleNode : rolesNode) {
71             String roleName = roleNode.path(AuthConstants.ROLE_NAME_PATH).asText();
72
73             AuthRole role = new AuthRole();
74             JsonNode usersNode = roleNode.path(AuthConstants.USERS_NODE_PATH);
75             JsonNode functionsNode = roleNode.path(AuthConstants.FUNCTIONS_NODE_PATH);
76             for (JsonNode functionNode : functionsNode) {
77                 String function = functionNode.path(AuthConstants.FUNCTION_NAME_PATH).asText();
78                 JsonNode methodsNode = functionNode.path(AuthConstants.METHODS_NODE_PATH);
79                 boolean hasMethods = handleMethodNode(methodsNode, role, function);
80
81                 if (!hasMethods) {
82                     // iterate the list from HTTP_METHODS
83                     for (HTTP_METHODS meth : HTTP_METHODS.values()) {
84                         String thisFunction = meth.toString() + ":" + function;
85
86                         role.addAllowedFunction(thisFunction);
87                     }
88                 }
89             }
90
91             handleUserNode(usersNode, roleName, role);
92         }
93
94         usersInitialized = true;
95     }
96
97     private boolean handleMethodNode(JsonNode methodsNode, AuthRole role, String function) {
98         boolean hasMethods = false;
99         for (JsonNode methodNode : methodsNode) {
100             String methodName = methodNode.path(AuthConstants.METHOD_NAME_PATH).asText();
101             hasMethods = true;
102             String thisFunction = methodName + ":" + function;
103
104             role.addAllowedFunction(thisFunction);
105         }
106         return hasMethods;
107     }
108
109     private void handleUserNode(JsonNode usersNode, String roleName, AuthRole role) {
110         for (JsonNode userNode : usersNode) {
111             // make the user lower case
112             String node = userNode.path(AuthConstants.USER_NODE_PATH).asText().toLowerCase();
113             AuthUser user;
114             if (users.containsKey(node)) {
115                 user = users.get(node);
116             } else {
117                 user = new AuthUser();
118             }
119
120             user.setUser(node);
121             user.addRole(roleName, role);
122             users.put(node, user);
123         }
124     }
125
126     public class AuthUser {
127
128         public AuthUser() {
129             this.roles = new HashMap<>();
130         }
131
132         private String username;
133         private HashMap<String, AuthRole> roles;
134
135         public String getUser() {
136             return this.username;
137         }
138
139         public Map<String, AuthRole> getRoles() {
140             return this.roles;
141         }
142
143         public void addRole(String roleName, AuthRole role) {
144             this.roles.put(roleName, role);
145         }
146
147         /**
148          * Returns true if the user has permissions for the function, otherwise returns false.
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          * @param delFunc
184          *        - String value of the function.
185          */
186         public void delAllowedFunction(String delFunc) {
187             if (this.allowedFunctions.contains(delFunc)) {
188                 this.allowedFunctions.remove(delFunc);
189             }
190         }
191
192         /**
193          * Returns true if the user has permissions to use the function, otherwise returns false.
194          * @param afunc
195          *        - String value of the function.
196          */
197         public boolean hasAllowedFunction(String afunc) {
198             return this.allowedFunctions.contains(afunc);
199         }
200     }
201
202     /**
203      * Returns a hash-map of all users which have been loaded and initialized.
204      */
205     public Map<String, AuthUser> getUsers(String key) throws Exception {
206         if (!usersInitialized || (users == null)) {
207             loadUsers(this.authFilename);
208         }
209         return users;
210     }
211
212     /**
213      * Returns true if the user is allowed to access a function.
214      * @param username
215      *        - String value of user
216      * @param authFunction
217      *        - String value of the function.
218      */
219     public boolean authorize(String username, String authFunction) {
220         AuthUser user = users.get(username);
221         return user != null && user.checkAllowed(authFunction);
222     }
223 }