Merge "Push variuos changes"
[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 import org.onap.music.service.impl.MusicZKCore;
41
42 import com.datastax.driver.core.DataType;
43 import com.datastax.driver.core.Row;
44 import com.sun.jersey.api.client.Client;
45 import com.sun.jersey.api.client.ClientResponse;
46 import com.sun.jersey.api.client.WebResource;
47
48 public class MusicAuthentication {
49     
50      private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicAuthentication.class);
51     
52     /**
53      * authenticate user logic
54      *
55      * @param nameSpace
56      * @param userId
57      * @param password
58      * @param keyspace
59      * @param aid
60      * @param operation
61      * @return
62      * @throws Exception
63      */
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                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.valueOf(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.info(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         String a = MusicUtil.getAdminId();
158         String b = MusicUtil.getAdminPass();
159         return (id.equals(MusicUtil.getAdminId()) && password.equals(MusicUtil.getAdminPass()));
160     }
161
162     public static boolean authenticateAdmin(Map<String,String> adminCredentials) {
163         if(adminCredentials.containsKey("ERROR"))
164             return false;
165          String admin_id = adminCredentials.get(MusicUtil.USERID);
166          String admin_password = adminCredentials.get(MusicUtil.PASSWORD);
167          return (admin_id.equals(MusicUtil.getAdminId()) && admin_password.equals(MusicUtil.getAdminPass()));
168     }
169
170     public static boolean authenticateAdmin(String authorization) throws Exception {
171         logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: "+authorization);
172         String userId = MusicUtil.extractBasicAuthentication(authorization).get(MusicUtil.USERID);
173         if(MusicUtil.getIsCadi()) {
174             CachingUtil.updateAdminUserCache(authorization, userId);
175             return true;
176         }
177         CacheAccess<String, String> adminCache = CachingUtil.getAdminUserCache();
178         if (authorization == null) {
179             logger.error(EELFLoggerDelegate.errorLogger, "Authorization cannot be empty..."+authorization);
180             throw new Exception("Authorization cannot be empty");
181         }
182         if (adminCache.get(authorization) != null && adminCache.get(authorization).equals(userId)) {
183             logger.info(EELFLoggerDelegate.applicationLogger, "MusicCore.authenticateAdmin: Validated against admincache.. "+authorization);
184             return true;
185         }
186         else {
187             Client client = Client.create();
188             WebResource webResource = client.resource(
189                     MusicUtil.getAafAdminUrl().concat(userId).concat("/").concat(MusicUtil.getAdminAafRole()));
190             ;
191
192             ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
193                     .header("Authorization", authorization).get(ClientResponse.class);
194             if (response.getStatus() == 200) {
195                 CachingUtil.updateAdminUserCache(authorization, userId);
196                 return true;
197             }
198         }
199         return false;
200
201     }
202     
203 }