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