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