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