DMAAP-MR - Merge MR repos
[dmaap/messagerouter/messageservice.git] / src / main / java / org / onap / dmaap / 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 org.onap.dmaap.dmf.mr.service.impl;
23
24 import com.att.eelf.configuration.EELFLogger;
25 import com.att.eelf.configuration.EELFManager;
26 import com.att.nsa.configs.ConfigDbException;
27 import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
28 import com.att.nsa.security.NsaApiKey;
29 import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException;
30 import com.att.nsa.security.db.NsaApiDb;
31 import com.att.nsa.security.db.NsaApiDb.KeyExistsException;
32 import com.att.nsa.security.db.simple.NsaSimpleApiKey;
33 import org.json.JSONArray;
34 import org.json.JSONObject;
35 import org.onap.dmaap.dmf.mr.beans.ApiKeyBean;
36 import org.onap.dmaap.dmf.mr.beans.DMaaPContext;
37 import org.onap.dmaap.dmf.mr.constants.CambriaConstants;
38 import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticatorImpl;
39 import org.onap.dmaap.dmf.mr.service.ApiKeysService;
40 import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
41 import org.onap.dmaap.dmf.mr.utils.DMaaPResponseBuilder;
42 import org.onap.dmaap.dmf.mr.utils.Emailer;
43 import org.springframework.stereotype.Service;
44
45 import java.io.IOException;
46
47 /**
48  * Implementation of the ApiKeysService, this will provide the below operations,
49  * getAllApiKeys, getApiKey, createApiKey, updateApiKey, deleteApiKey
50  * 
51  * @author nilanjana.maity
52  */
53 @Service
54 public class ApiKeysServiceImpl implements ApiKeysService {
55
56         
57         private static final EELFLogger log = EELFManager.getInstance().getLogger(ApiKeysServiceImpl.class.toString());
58         /**
59          * This method will provide all the ApiKeys present in kafka server.
60          * 
61          * @param dmaapContext
62          * @throws ConfigDbException
63          * @throws IOException
64          */
65         public void getAllApiKeys(DMaaPContext dmaapContext)
66                         throws ConfigDbException, IOException {
67
68                 ConfigurationReader configReader = dmaapContext.getConfigReader();
69
70                 log.info("configReader : " + configReader.toString());
71
72                 final JSONObject result = new JSONObject();
73                 final JSONArray keys = new JSONArray();
74                 result.put("apiKeys", keys);
75
76                 NsaApiDb<NsaSimpleApiKey> apiDb = configReader.getfApiKeyDb();
77
78                 for (String key : apiDb.loadAllKeys()) {
79                         keys.put(key);
80                 }
81                 log.info("========== ApiKeysServiceImpl: getAllApiKeys: Api Keys are : "
82                                 + keys.toString() + "===========");
83                 DMaaPResponseBuilder.respondOk(dmaapContext, result);
84         }
85
86         /**
87          * @param dmaapContext
88          * @param apikey
89          * @throws ConfigDbException
90          * @throws IOException
91          */
92         @Override
93         public void getApiKey(DMaaPContext dmaapContext, String apikey)
94                         throws ConfigDbException, IOException {
95
96                 String errorMsg = "Api key name is not mentioned.";
97                 int errorCode = HttpStatusCodes.k400_badRequest;
98                 
99                 if (null != apikey) {
100                         NsaSimpleApiKey simpleApiKey = getApiKeyDb(dmaapContext)
101                                         .loadApiKey(apikey);
102                         
103                 
104                         if (null != simpleApiKey) {
105                                 JSONObject result = simpleApiKey.asJsonObject();
106                                 DMaaPResponseBuilder.respondOk(dmaapContext, result);
107                                 log.info("========== ApiKeysServiceImpl: getApiKey : "
108                                                 + result.toString() + "===========");
109                                 return;
110                         } else {
111                                 errorMsg = "Api key [" + apikey + "] does not exist.";
112                                 errorCode = HttpStatusCodes.k404_notFound;
113                                 log.info("========== ApiKeysServiceImpl: getApiKey: Error : API Key does not exist. "
114                                                 + "===========");
115                                 DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
116                                                 errorMsg);
117                                 throw new IOException();
118                         }
119                 }
120
121         }
122
123         /**
124          * @param dmaapContext
125          * @param nsaApiKey
126          * @throws KeyExistsException
127          * @throws ConfigDbException
128          * @throws IOException
129          */
130         @Override
131         public void createApiKey(DMaaPContext dmaapContext, ApiKeyBean nsaApiKey)
132                         throws KeyExistsException, ConfigDbException, IOException {
133
134                 log.debug("TopicService: : createApiKey....");
135                 
136                         String contactEmail = nsaApiKey.getEmail();
137                         final boolean emailProvided = contactEmail != null && contactEmail.length() > 0 && contactEmail.indexOf("@") > 1 ;
138                          String kSetting_AllowAnonymousKeys= com.att.ajsc.filemonitor.AJSCPropertiesMap.getProperty(CambriaConstants.msgRtr_prop,"apiKeys.allowAnonymous");
139                          if(null==kSetting_AllowAnonymousKeys) {
140                                  kSetting_AllowAnonymousKeys ="false";
141                          }
142             
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                         
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                                  + "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                         
200                         return;
201                 } else {
202                         log.debug("=======ApiKeysServiceImpl: createApiKey : Error in creating API Key.=====");
203                         DMaaPResponseBuilder.respondWithError(dmaapContext,
204                                         HttpStatusCodes.k500_internalServerError,
205                                         "Failed to create api key.");
206                         throw new KeyExistsException(apiKey);
207                 }
208         }
209
210         /**
211          * @param dmaapContext
212          * @param apikey
213          * @param nsaApiKey
214          * @throws ConfigDbException
215          * @throws IOException
216          * @throws AccessDeniedException
217          */
218         @Override
219         public void updateApiKey(DMaaPContext dmaapContext, String apikey,
220                         ApiKeyBean nsaApiKey) throws ConfigDbException, IOException, AccessDeniedException {
221
222                 String errorMsg = "Api key name is not mentioned.";
223                 int errorCode = HttpStatusCodes.k400_badRequest;
224
225                 if (null != apikey) {
226                         final NsaApiDb<NsaSimpleApiKey> apiKeyDb = getApiKeyDb(dmaapContext);
227                         final NsaSimpleApiKey key = apiKeyDb.loadApiKey(apikey);
228                         boolean shouldUpdate = false;
229
230                         if (null != key) {
231                                 final NsaApiKey user = DMaaPAuthenticatorImpl
232                                                 .getAuthenticatedUser(dmaapContext);
233
234                                 if (user == null || !user.getKey().equals(key.getKey())) {
235                                         throw new AccessDeniedException("You must authenticate with the key you'd like to update.");
236                                 }
237
238                                 if (null != nsaApiKey.getEmail()) {
239                                         key.setContactEmail(nsaApiKey.getEmail());
240                                         shouldUpdate = true;
241                                 }
242
243                                 if (null != nsaApiKey.getDescription()) {
244                                         key.setDescription(nsaApiKey.getDescription());
245                                         shouldUpdate = true;
246                                 }
247
248                                 if (shouldUpdate) {
249                                         apiKeyDb.saveApiKey(key);
250                                 }
251
252                                 log.info("======ApiKeysServiceImpl : updateApiKey : Key Updated Successfully :"
253                                                 + key.toString() + "=========");
254                                 DMaaPResponseBuilder.respondOk(dmaapContext,
255                                                 key.asJsonObject());
256                                 return;
257                         }
258                 } else {
259                         errorMsg = "Api key [" + apikey + "] does not exist.";
260                         errorCode = HttpStatusCodes.k404_notFound;
261                         DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
262                                         errorMsg);
263                         log.info("======ApiKeysServiceImpl : updateApiKey : Error in Updating Key.============");
264                         throw new IOException();
265                 }
266         }
267
268         /**
269          * @param dmaapContext
270          * @param apikey
271          * @throws ConfigDbException
272          * @throws IOException
273          * @throws AccessDeniedException
274          */
275         @Override
276         public void deleteApiKey(DMaaPContext dmaapContext, String apikey)
277                         throws ConfigDbException, IOException, AccessDeniedException {
278
279                 String errorMsg = "Api key name is not mentioned.";
280                 int errorCode = HttpStatusCodes.k400_badRequest;
281
282                 if (null != apikey) {
283                         final NsaApiDb<NsaSimpleApiKey> apiKeyDb = getApiKeyDb(dmaapContext);
284                         final NsaSimpleApiKey key = apiKeyDb.loadApiKey(apikey);
285
286                         if (null != key) {
287
288                                 final NsaApiKey user = DMaaPAuthenticatorImpl
289                                                 .getAuthenticatedUser(dmaapContext);
290                                 if (user == null || !user.getKey().equals(key.getKey())) {
291                                         throw new AccessDeniedException("You don't own the API key.");
292                                 }
293
294                                 apiKeyDb.deleteApiKey(key);
295                                 log.info("======ApiKeysServiceImpl : deleteApiKey : Deleted Key successfully.============");
296                                 DMaaPResponseBuilder.respondOkWithHtml(dmaapContext,
297                                                 "Api key [" + apikey + "] deleted successfully.");
298                                 return;
299                         }
300                 } else {
301                         errorMsg = "Api key [" + apikey + "] does not exist.";
302                         errorCode = HttpStatusCodes.k404_notFound;
303                         DMaaPResponseBuilder.respondWithError(dmaapContext, errorCode,
304                                         errorMsg);
305                         log.info("======ApiKeysServiceImpl : deleteApiKey : Error while deleting key.============");
306                         throw new IOException();
307                 }
308         }
309
310         /**
311          * 
312          * @param dmaapContext
313          * @return
314          */
315         private NsaApiDb<NsaSimpleApiKey> getApiKeyDb(DMaaPContext dmaapContext) {
316                 ConfigurationReader configReader = dmaapContext.getConfigReader();
317                 return configReader.getfApiKeyDb();
318         }
319
320 }