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