c818f883e77ac7f7790cae6944bbf1b42763cea9
[dmaap/messagerouter/msgrtr.git] / src / main / java / com / att / dmf / mr / service / impl / ApiKeysServiceImpl.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  org.onap.dmaap
4  *  ================================================================================
5  *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
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  *        http://www.apache.org/licenses/LICENSE-2.0
11 *  
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *  ============LICENSE_END=========================================================
18  *  
19  *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  *  
21  *******************************************************************************/
22 package com.att.dmf.mr.service.impl;
23
24 import java.io.IOException;
25
26 import org.json.JSONArray;
27 import org.json.JSONObject;
28 import org.springframework.stereotype.Service;
29
30 import com.att.dmf.mr.beans.ApiKeyBean;
31 import com.att.dmf.mr.beans.DMaaPContext;
32 import com.att.dmf.mr.constants.CambriaConstants;
33 import com.att.dmf.mr.security.DMaaPAuthenticatorImpl;
34 import com.att.dmf.mr.service.ApiKeysService;
35 import com.att.dmf.mr.utils.ConfigurationReader;
36 import com.att.dmf.mr.utils.DMaaPResponseBuilder;
37 import com.att.dmf.mr.utils.Emailer;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import com.att.nsa.configs.ConfigDbException;
41 import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
42 import com.att.nsa.security.NsaApiKey;
43 import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException;
44 import com.att.nsa.security.db.NsaApiDb;
45 import com.att.nsa.security.db.NsaApiDb.KeyExistsException;
46 import com.att.nsa.security.db.simple.NsaSimpleApiKey;
47
48 /**
49  * Implementation of the ApiKeysService, this will provide the below operations,
50  * getAllApiKeys, getApiKey, createApiKey, updateApiKey, deleteApiKey
51  * 
52  * @author nilanjana.maity
53  */
54 @Service
55 public class ApiKeysServiceImpl implements ApiKeysService {
56
57         //private Logger log = Logger.getLogger(ApiKeysServiceImpl.class.toString());
58         private static final EELFLogger log = EELFManager.getInstance().getLogger(ApiKeysServiceImpl.class.toString());
59         /**
60          * This method will provide all the ApiKeys present in kafka server.
61          * 
62          * @param dmaapContext
63          * @throws ConfigDbException
64          * @throws IOException
65          */
66         public void getAllApiKeys(DMaaPContext dmaapContext)
67                         throws ConfigDbException, IOException {
68
69                 ConfigurationReader configReader = dmaapContext.getConfigReader();
70
71                 log.info("configReader : " + configReader.toString());
72
73                 final JSONObject result = new JSONObject();
74                 final JSONArray keys = new JSONArray();
75                 result.put("apiKeys", keys);
76
77                 NsaApiDb<NsaSimpleApiKey> apiDb = configReader.getfApiKeyDb();
78
79                 for (String key : apiDb.loadAllKeys()) {
80                         keys.put(key);
81                 }
82                 log.info("========== ApiKeysServiceImpl: getAllApiKeys: Api Keys are : "
83                                 + keys.toString() + "===========");
84                 DMaaPResponseBuilder.respondOk(dmaapContext, result);
85         }
86
87         /**
88          * @param dmaapContext
89          * @param apikey
90          * @throws ConfigDbException
91          * @throws IOException
92          */
93         @Override
94         public void getApiKey(DMaaPContext dmaapContext, String apikey)
95                         throws ConfigDbException, IOException {
96
97                 String errorMsg = "Api key name is not mentioned.";
98                 int errorCode = HttpStatusCodes.k400_badRequest;
99                 
100                 if (null != apikey) {
101                         NsaSimpleApiKey simpleApiKey = getApiKeyDb(dmaapContext)
102                                         .loadApiKey(apikey);
103                         
104                 
105                         if (null != simpleApiKey) {
106                                 JSONObject result = simpleApiKey.asJsonObject();
107                                 DMaaPResponseBuilder.respondOk(dmaapContext, result);
108                                 log.info("========== ApiKeysServiceImpl: getApiKey : "
109                                                 + result.toString() + "===========");
110                                 return;
111                         } else {
112                                 errorMsg = "Api key [" + apikey + "] does not exist.";
113                                 errorCode = HttpStatusCodes.k404_notFound;
114                                 log.info("========== ApiKeysServiceImpl: getApiKey: Error : API Key does not exist. "
115                                                 + "===========");
116                                 DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
117                                                 errorMsg);
118                                 throw new IOException();
119                         }
120                 }
121
122         }
123
124         /**
125          * @param dmaapContext
126          * @param nsaApiKey
127          * @throws KeyExistsException
128          * @throws ConfigDbException
129          * @throws IOException
130          */
131         @Override
132         public void createApiKey(DMaaPContext dmaapContext, ApiKeyBean nsaApiKey)
133                         throws KeyExistsException, ConfigDbException, IOException {
134
135                 log.debug("TopicService: : createApiKey....");
136                 
137                         String contactEmail = nsaApiKey.getEmail();
138                         final boolean emailProvided = contactEmail != null && contactEmail.length() > 0 && contactEmail.indexOf("@") > 1 ;
139                          String kSetting_AllowAnonymousKeys= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,"apiKeys.allowAnonymous");
140                          if(null==kSetting_AllowAnonymousKeys) kSetting_AllowAnonymousKeys ="false";
141                          
142              // if ((contactEmail == null) || (contactEmail.length() == 0))
143                          if ( kSetting_AllowAnonymousKeys.equalsIgnoreCase("true")    &&  !emailProvided   )
144               {
145                 DMaaPResponseBuilder.respondWithErrorInJson(dmaapContext, 400, "You must provide an email address.");
146                 return;
147               }
148                 
149                 
150                 final NsaApiDb<NsaSimpleApiKey> apiKeyDb = getApiKeyDb(dmaapContext);
151                 String apiKey = nsaApiKey.getKey();
152                 String sharedSecret = nsaApiKey.getSharedSecret();
153                 final NsaSimpleApiKey key = apiKeyDb.createApiKey(apiKey,
154                                 sharedSecret);
155                 if (null != key) {
156
157                         if (null != nsaApiKey.getEmail()) {
158                                 key.setContactEmail(nsaApiKey.getEmail());
159                         }
160
161                         if (null != nsaApiKey.getDescription()) {
162                                 key.setDescription(nsaApiKey.getDescription());
163                         }
164
165                         log.debug("=======ApiKeysServiceImpl: createApiKey : saving api key : "
166                                         + key.toString() + "=====");
167                         apiKeyDb.saveApiKey(key);
168                         // System.out.println("here4");
169                         // email out the secret to validate the email address
170                         if ( emailProvided )
171                         {
172                                 String body = "\n" + "Your email address was provided as the creator of new API key \""
173                                 + apiKey + "\".\n" + "\n" + "If you did not make this request, please let us know."
174                                 + " See http://sa2020.it.att.com:8888 for contact information, " + "but don't worry -"
175                                 + " the API key is useless without the information below, which has been provided "
176                                 + "only to you.\n" + "\n\n" + "For API key \"" + apiKey + "\", use API key secret:\n\n\t"
177                                 + sharedSecret + "\n\n" + "Note that it's normal to share the API key"
178                                 + " (" + apiKey + "). "                         
179                                 + "This is how you are granted access to resources " + "like a UEB topic or Flatiron scope. "
180                                 + "However, you should NOT share the API key's secret. " + "The API key is associated with your"
181                                 + " email alone. ALL access to data made with this " + "key will be your responsibility. If you "
182                                 + "share the secret, someone else can use the API key " + "to access proprietary data with your "
183                                 + "identity.\n" + "\n" + "Enjoy!\n" + "\n" + "The GFP/SA-2020 Team";
184         
185                         Emailer em = dmaapContext.getConfigReader().getSystemEmailer();
186                         em.send(contactEmail, "New API Key", body);
187                         }
188                         log.debug("TopicService: : sending response.");
189         
190                         JSONObject o = key.asJsonObject();
191                         
192                         o.put ( NsaSimpleApiKey.kApiSecretField,
193                                         emailProvided ?
194                                                 "Emailed to " + contactEmail + "." :
195                                                 key.getSecret ()
196                                 );
197                         DMaaPResponseBuilder.respondOk(dmaapContext,
198                                         o);
199                          /*o.put("secret", "Emailed to " + contactEmail + ".");
200                         DMaaPResponseBuilder.respondOk(dmaapContext,
201                                         o); */
202                         return;
203                 } else {
204                         log.debug("=======ApiKeysServiceImpl: createApiKey : Error in creating API Key.=====");
205                         DMaaPResponseBuilder.respondWithError(dmaapContext,
206                                         HttpStatusCodes.k500_internalServerError,
207                                         "Failed to create api key.");
208                         throw new KeyExistsException(apiKey);
209                 }
210         }
211
212         /**
213          * @param dmaapContext
214          * @param apikey
215          * @param nsaApiKey
216          * @throws ConfigDbException
217          * @throws IOException
218          * @throws AccessDeniedException
219          */
220         @Override
221         public void updateApiKey(DMaaPContext dmaapContext, String apikey,
222                         ApiKeyBean nsaApiKey) throws ConfigDbException, IOException, AccessDeniedException {
223
224                 String errorMsg = "Api key name is not mentioned.";
225                 int errorCode = HttpStatusCodes.k400_badRequest;
226
227                 if (null != apikey) {
228                         final NsaApiDb<NsaSimpleApiKey> apiKeyDb = getApiKeyDb(dmaapContext);
229                         final NsaSimpleApiKey key = apiKeyDb.loadApiKey(apikey);
230                         boolean shouldUpdate = false;
231
232                         if (null != key) {
233                                 final NsaApiKey user = DMaaPAuthenticatorImpl
234                                                 .getAuthenticatedUser(dmaapContext);
235
236                                 if (user == null || !user.getKey().equals(key.getKey())) {
237                                         throw new AccessDeniedException("You must authenticate with the key you'd like to update.");
238                                 }
239
240                                 if (null != nsaApiKey.getEmail()) {
241                                         key.setContactEmail(nsaApiKey.getEmail());
242                                         shouldUpdate = true;
243                                 }
244
245                                 if (null != nsaApiKey.getDescription()) {
246                                         key.setDescription(nsaApiKey.getDescription());
247                                         shouldUpdate = true;
248                                 }
249
250                                 if (shouldUpdate) {
251                                         apiKeyDb.saveApiKey(key);
252                                 }
253
254                                 log.info("======ApiKeysServiceImpl : updateApiKey : Key Updated Successfully :"
255                                                 + key.toString() + "=========");
256                                 DMaaPResponseBuilder.respondOk(dmaapContext,
257                                                 key.asJsonObject());
258                                 return;
259                         }
260                 } else {
261                         errorMsg = "Api key [" + apikey + "] does not exist.";
262                         errorCode = HttpStatusCodes.k404_notFound;
263                         DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
264                                         errorMsg);
265                         log.info("======ApiKeysServiceImpl : updateApiKey : Error in Updating Key.============");
266                         throw new IOException();
267                 }
268         }
269
270         /**
271          * @param dmaapContext
272          * @param apikey
273          * @throws ConfigDbException
274          * @throws IOException
275          * @throws AccessDeniedException
276          */
277         @Override
278         public void deleteApiKey(DMaaPContext dmaapContext, String apikey)
279                         throws ConfigDbException, IOException, AccessDeniedException {
280
281                 String errorMsg = "Api key name is not mentioned.";
282                 int errorCode = HttpStatusCodes.k400_badRequest;
283
284                 if (null != apikey) {
285                         final NsaApiDb<NsaSimpleApiKey> apiKeyDb = getApiKeyDb(dmaapContext);
286                         final NsaSimpleApiKey key = apiKeyDb.loadApiKey(apikey);
287
288                         if (null != key) {
289
290                                 final NsaApiKey user = DMaaPAuthenticatorImpl
291                                                 .getAuthenticatedUser(dmaapContext);
292                                 if (user == null || !user.getKey().equals(key.getKey())) {
293                                         throw new AccessDeniedException("You don't own the API key.");
294                                 }
295
296                                 apiKeyDb.deleteApiKey(key);
297                                 log.info("======ApiKeysServiceImpl : deleteApiKey : Deleted Key successfully.============");
298                                 DMaaPResponseBuilder.respondOkWithHtml(dmaapContext,
299                                                 "Api key [" + apikey + "] deleted successfully.");
300                                 return;
301                         }
302                 } else {
303                         errorMsg = "Api key [" + apikey + "] does not exist.";
304                         errorCode = HttpStatusCodes.k404_notFound;
305                         DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
306                                         errorMsg);
307                         log.info("======ApiKeysServiceImpl : deleteApiKey : Error while deleting key.============");
308                         throw new IOException();
309                 }
310         }
311
312         /**
313          * 
314          * @param dmaapContext
315          * @return
316          */
317         private NsaApiDb<NsaSimpleApiKey> getApiKeyDb(DMaaPContext dmaapContext) {
318                 ConfigurationReader configReader = dmaapContext.getConfigReader();
319                 return configReader.getfApiKeyDb();
320         }
321
322 }