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