10f1e30c413e38afaadc395d750496881d6fd3fb
[music.git] / src / main / java / org / onap / music / authentication / MusicAuthentication.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22
23 package org.onap.music.authentication;
24
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import javax.ws.rs.core.MediaType;
29
30 import org.apache.commons.jcs.access.CacheAccess;
31 import org.onap.music.datastore.PreparedQueryObject;
32 import org.onap.music.eelf.logging.EELFLoggerDelegate;
33 import org.onap.music.eelf.logging.format.AppMessages;
34 import org.onap.music.eelf.logging.format.ErrorSeverity;
35 import org.onap.music.eelf.logging.format.ErrorTypes;
36 import org.onap.music.exceptions.MusicServiceException;
37 import org.onap.music.authentication.MusicAuthenticator.Operation;
38 import org.onap.music.main.MusicCore;
39 import org.onap.music.main.MusicUtil;
40
41 import com.datastax.driver.core.DataType;
42 import com.datastax.driver.core.Row;
43 import com.sun.jersey.api.client.Client;
44 import com.sun.jersey.api.client.ClientResponse;
45 import com.sun.jersey.api.client.WebResource;
46
47 public class MusicAuthentication implements MusicAuthenticator {
48     
49      private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthentication.class);
50     
51     /**
52      * authenticate user logic
53      *
54      * @param nameSpace
55      * @param userId
56      * @param password
57      * @param keyspace
58      * @param aid
59      * @param operation
60      * @return
61      * @throws Exception
62      */
63      @Deprecated
64     public static Map<String, Object> autheticateUser(String nameSpace, String userId,
65                     String password, String keyspace, String aid, String operation)
66                     throws Exception {
67         logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication.......");
68         Map<String, Object> resultMap = new HashMap<>();
69         String uuid = null;
70         if(! MusicUtil.getIsCadi()) {
71             resultMap = CachingUtil.validateRequest(nameSpace, userId, password, keyspace, aid,
72                             operation);
73             if (!resultMap.isEmpty())
74                 return resultMap;
75             String isAAFApp = null;
76             try {
77                 isAAFApp= CachingUtil.isAAFApplication(nameSpace);
78             } catch(MusicServiceException e) {
79                 logger.error(e.getErrorMessage(), e);
80                resultMap.put("Exception", e.getMessage());
81                return resultMap;
82             }
83             if(isAAFApp == null) {
84                 resultMap.put("Exception", "Namespace: "+nameSpace+" doesn't exist. Please make sure ns(appName)"
85                         + " is correct and Application is onboarded.");
86                 return resultMap;
87             }
88             boolean isAAF = Boolean.parseBoolean(isAAFApp);
89             if (userId == null || password == null) {
90                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
91                 logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId
92                                 + " :: password: " + password);
93                 resultMap.put("Exception",
94                                 "UserId and Password are mandatory for the operation " + operation);
95                 return resultMap;
96             }
97             if(!isAAF && !(operation.equals("createKeySpace"))) {
98                 resultMap = CachingUtil.authenticateAIDUser(nameSpace, userId, password, keyspace);
99                 if (!resultMap.isEmpty())
100                     return resultMap;
101     
102             }
103             if (isAAF && nameSpace != null && userId != null && password != null) {
104                 boolean isValid = true;
105                 try {
106                      isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
107                 } catch (Exception e) {
108                     logger.error(EELFLoggerDelegate.errorLogger,"Error while aaf authentication for user:" + userId);
109                     logger.error(EELFLoggerDelegate.errorLogger,"Error: "+ e.getMessage());
110                     logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
111                     logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace);
112                     resultMap.put("Exception", e.getMessage());
113                 }
114                 if (!isValid) {
115                     logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated...", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
116                     resultMap.put("Exception", "User not authenticated...");
117                 }
118                 if (!resultMap.isEmpty())
119                     return resultMap;
120     
121             }
122         } else {
123             
124             String cachedKS = CachingUtil.getKSFromCadiCache(userId);
125             if(cachedKS != null && !cachedKS.equals(keyspace)) {
126                 resultMap.put("Exception", "User not authenticated to access this keyspace...");
127             }
128         }
129         
130         if (operation.equals("createKeySpace")) {
131             logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace.");
132             PreparedQueryObject pQuery = new PreparedQueryObject();
133             pQuery.appendQueryString(
134                             "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering");
135             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), nameSpace));
136             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
137             pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
138                             MusicUtil.DEFAULTKEYSPACENAME));
139
140             try {
141                 Row rs = MusicCore.get(pQuery).one();
142                 uuid = rs.getUUID("uuid").toString();
143                 resultMap.put("uuid", "existing");
144             } catch (Exception e) {
145                 logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID.");
146                 uuid = MusicUtil.generateUUID();
147                 resultMap.put("uuid", "new");
148             }
149             resultMap.put("aid", uuid);
150             CachingUtil.updateCadiCache(userId, keyspace);
151         }
152         
153         return resultMap;
154     }
155
156     @Override
157     public boolean authenticateAdmin(String authorization) {
158         logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: ");
159         String userId = MusicUtil.extractBasicAuthentication(authorization).get(MusicUtil.USERID);
160         if(MusicUtil.getIsCadi()) {
161             CachingUtil.updateAdminUserCache(authorization, userId);
162             return true;
163         }
164         CacheAccess<String, String> adminCache = CachingUtil.getAdminUserCache();
165         if (authorization == null) {
166             logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty...");
167             return false;
168         }
169         if (adminCache.get(authorization) != null && adminCache.get(authorization).equals(userId)) {
170             logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. ");
171             return true;
172         }
173         else {
174             Client client = Client.create();
175             String aafUrl = MusicUtil.getAafAdminUrl();
176             if (aafUrl==null) {
177                 logger.error(EELFLoggerDelegate.errorLogger, "Admin url is not set, please set in properties");
178                 return false;
179             }
180             
181             WebResource webResource = client.resource(
182                     MusicUtil.getAafAdminUrl().concat(userId).concat("/").concat(MusicUtil.getAdminAafRole()));
183
184             ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
185                     .header("Authorization", authorization).get(ClientResponse.class);
186             if (response.getStatus() == 200) {
187                 CachingUtil.updateAdminUserCache(authorization, userId);
188                 return true;
189             }
190         }
191         return false;
192     }
193
194     @Override
195     public boolean authenticateUser(String namespace, String authorization, String keyspace,
196             String aid, Operation operation) {
197         logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication.......");
198         Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
199         String userId = userCredentials.get(MusicUtil.USERID);
200         String password = userCredentials.get(MusicUtil.PASSWORD);
201
202         Map<String, Object> resultMap = new HashMap<>();
203         String uuid = null;
204         if(! MusicUtil.getIsCadi()) {
205             resultMap = CachingUtil.validateRequest(namespace, userId, password, keyspace, aid,
206                             operation);
207             if (!resultMap.isEmpty())
208                 return false;
209             String isAAFApp = null;
210             try {
211                 isAAFApp= CachingUtil.isAAFApplication(namespace);
212             } catch(MusicServiceException e) {
213                 logger.error(e.getErrorMessage(), e);
214                resultMap.put("Exception", e.getMessage());
215                return false;
216             }
217             if(isAAFApp == null) {
218                 resultMap.put("Exception", "Namespace: "+namespace+" doesn't exist. Please make sure ns(appName)"
219                         + " is correct and Application is onboarded.");
220                 return false;
221             }
222             boolean isAAF = Boolean.parseBoolean(isAAFApp);
223             if (userId == null || password == null) {
224                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
225                 logger.error(EELFLoggerDelegate.errorLogger,"UserId/Password or more required headers is missing.");
226                 resultMap.put("Exception",
227                                 "UserId and Password are mandatory for the operation " + operation);
228                 return false;
229             }
230             if(!isAAF && !(operation==Operation.CREATE_KEYSPACE)) {
231                 resultMap = CachingUtil.authenticateAIDUser(namespace, userId, password, keyspace);
232                 if (!resultMap.isEmpty())
233                     return false;
234     
235             }
236             if (isAAF && namespace != null && userId != null && password != null) {
237                 boolean isValid = true;
238                 try {
239                      isValid = CachingUtil.authenticateAAFUser(namespace, userId, password, keyspace);
240                 } catch (Exception e) {
241                     logger.error(EELFLoggerDelegate.errorLogger,"Error while aaf authentication for user:" + userId);
242                     logger.error(EELFLoggerDelegate.errorLogger,"Error: "+ e.getMessage());
243                     logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
244                     logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + namespace);
245                     resultMap.put("Exception", e.getMessage());
246                 }
247                 if (!isValid) {
248                     logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated...", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
249                     resultMap.put("Exception", "User not authenticated...");
250                 }
251                 if (!resultMap.isEmpty())
252                     return false;
253     
254             }
255         } else {
256             
257             String cachedKS = CachingUtil.getKSFromCadiCache(userId);
258             if(cachedKS != null && !cachedKS.equals(keyspace)) {
259                 resultMap.put("Exception", "User not authenticated to access this keyspace...");
260                 return false;
261             }
262         }
263         
264         if (operation==Operation.CREATE_KEYSPACE) {
265             try {
266                 logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace.");
267                 PreparedQueryObject pQuery = new PreparedQueryObject();
268                 pQuery.appendQueryString(
269                                 "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering");
270                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), namespace));
271                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
272                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
273                                 MusicUtil.DEFAULTKEYSPACENAME));
274                 Row rs = MusicCore.get(pQuery).one();
275                 uuid = rs.getUUID("uuid").toString();
276                 resultMap.put("uuid", "existing");
277             } catch (Exception e) {
278                 logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID.");
279                 uuid = MusicUtil.generateUUID();
280                 resultMap.put("uuid", "new");
281             }
282             resultMap.put("aid", uuid);
283             CachingUtil.updateCadiCache(userId, keyspace);
284         }
285         return true;
286     }
287     
288 }