Changes Listed below:
[music.git] / src / main / java / org / onap / music / authentication / MusicAAFAuthentication.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
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  *
21  * ============LICENSE_END=============================================
22  * ====================================================================
23  */
24
25 package org.onap.music.authentication;
26
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import javax.ws.rs.core.MediaType;
31
32 import org.apache.commons.jcs.access.CacheAccess;
33 import org.onap.music.datastore.PreparedQueryObject;
34 import org.onap.music.eelf.logging.EELFLoggerDelegate;
35 import org.onap.music.eelf.logging.format.AppMessages;
36 import org.onap.music.eelf.logging.format.ErrorSeverity;
37 import org.onap.music.eelf.logging.format.ErrorTypes;
38 import org.onap.music.exceptions.MusicServiceException;
39 import org.onap.music.authentication.MusicAuthenticator.Operation;
40 import org.onap.music.main.MusicCore;
41 import org.onap.music.main.MusicUtil;
42
43 import com.datastax.driver.core.DataType;
44 import com.datastax.driver.core.Row;
45 import com.sun.jersey.api.client.Client;
46 import com.sun.jersey.api.client.ClientResponse;
47 import com.sun.jersey.api.client.WebResource;
48
49 public class MusicAAFAuthentication implements MusicAuthenticator {
50             
51      private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAAFAuthentication.class);
52
53     @Override
54     public boolean authenticateAdmin(String authorization) {
55         logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: ");
56         String userId = MusicUtil.extractBasicAuthentication(authorization).get(MusicUtil.USERID);
57         CacheAccess<String, String> adminCache = CachingUtil.getAdminUserCache();
58         if (authorization == null) {
59             logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty...");
60             return false;
61         }
62         if (adminCache.get(authorization) != null && adminCache.get(authorization).equals(userId)) {
63             logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. ");
64             return true;
65         }
66         else {
67             Client client = Client.create();
68             String aafUrl = MusicUtil.getAafAdminUrl();
69             if (aafUrl==null) {
70                 logger.error(EELFLoggerDelegate.errorLogger, "Admin url is not set, please set in properties");
71                 return false;
72             }
73             
74             WebResource webResource = client.resource(
75                     MusicUtil.getAafAdminUrl().concat(userId).concat("/").concat(MusicUtil.getAdminAafRole()));
76
77             ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
78                     .header("Authorization", authorization).get(ClientResponse.class);
79             if (response.getStatus() == 200) {
80                 CachingUtil.updateAdminUserCache(authorization, userId);
81                 return true;
82             }
83         }
84         return false;
85     }
86
87     @Override
88     public boolean authenticateUser(String namespace, String authorization, String keyspace,
89             String aid, Operation operation) {
90         logger.info(EELFLoggerDelegate.applicationLogger,"Inside User Authentication.......");
91         Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
92         String userId = userCredentials.get(MusicUtil.USERID);
93         String password = userCredentials.get(MusicUtil.PASSWORD);
94
95         Map<String, Object> resultMap = new HashMap<>();
96         String uuid = null;
97         if(! MusicUtil.getIsCadi()) {
98             resultMap = CachingUtil.validateRequest(namespace, userId, password, keyspace, aid,
99                             operation);
100             if (!resultMap.isEmpty())
101                 return false;
102             String isAAFApp = null;
103             try {
104                 isAAFApp= CachingUtil.isAAFApplication(namespace);
105             } catch(MusicServiceException e) {
106                 logger.error(e.getErrorMessage(), e);
107                 resultMap.put("Exception", e.getMessage());
108                 return false;
109             }
110             if(isAAFApp == null) {
111                 resultMap.put("Exception", "Namespace: "+namespace+" doesn't exist. Please make sure ns(appName)"
112                         + " is correct and Application is onboarded.");
113                 return false;
114             }
115             boolean isAAF = Boolean.parseBoolean(isAAFApp);
116             if (userId == null || password == null) {
117                 logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
118                 logger.error(EELFLoggerDelegate.errorLogger,"UserId/Password or more required headers is missing.");
119                 resultMap.put("Exception",
120                                 "UserId and Password are mandatory for the operation " + operation);
121                 return false;
122             }
123             if(!isAAF && !(operation==Operation.CREATE_KEYSPACE)) {
124                 resultMap = CachingUtil.authenticateAIDUser(namespace, userId, password, keyspace);
125                 if (!resultMap.isEmpty())
126                     return false;
127     
128             }
129             if (isAAF && namespace != null && userId != null && password != null) {
130                 boolean isValid = true;
131                 try {
132                     isValid = CachingUtil.authenticateAAFUser(namespace, userId, password, keyspace);
133                 } catch (Exception e) {
134                     logger.error(EELFLoggerDelegate.errorLogger,"Error while aaf authentication for user:" + userId);
135                     logger.error(EELFLoggerDelegate.errorLogger,"Error: "+ e.getMessage(), e);
136                     logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
137                     logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + namespace);
138                     resultMap.put("Exception", e.getMessage());
139                 }
140                 if (!isValid) {
141                     logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated...", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
142                     resultMap.put("Exception", "User not authenticated...");
143                 }
144                 if (!resultMap.isEmpty())
145                     return false;
146     
147             }
148         } else {
149             
150             String cachedKS = CachingUtil.getKSFromCadiCache(userId);
151             if(cachedKS != null && !cachedKS.equals(keyspace)) {
152                 resultMap.put("Exception", "User not authenticated to access this keyspace...");
153                 return false;
154             }
155         }
156         
157         if (operation==Operation.CREATE_KEYSPACE) {
158             try {
159                 logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace.");
160                 PreparedQueryObject pQuery = new PreparedQueryObject();
161                 pQuery.appendQueryString(
162                                 "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering");
163                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), namespace));
164                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
165                 pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
166                                 MusicUtil.DEFAULTKEYSPACENAME));
167                 Row rs = MusicCore.get(pQuery).one();
168                 uuid = rs.getUUID("uuid").toString();
169                 resultMap.put("uuid", "existing");
170             } catch (Exception e) {
171                 logger.error(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID.", e);
172                 uuid = MusicUtil.generateUUID();
173                 resultMap.put("uuid", "new");
174             }
175             resultMap.put("aid", uuid);
176             CachingUtil.updateCadiCache(userId, keyspace);
177         }
178         return true;
179     }
180     
181 }