summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-app-common/src/main/java/org/onap/portalapp/service/OnBoardingApiServiceImpl.java
blob: 966eb8f28e7af5b34af896e74d58bf4b0dc0a02c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/*
 * ============LICENSE_START==========================================
 * ONAP Portal SDK
 * ===================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalapp.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;

import org.onap.portalsdk.core.auth.LoginStrategy;
import org.onap.portalsdk.core.domain.App;
import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.domain.UserApp;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.onboarding.client.AppContextManager;
import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestCentralService;
import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
import org.onap.portalsdk.core.onboarding.util.CipherUtil;
import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.onap.portalsdk.core.service.AppService;
import org.onap.portalsdk.core.service.RestApiRequestBuilder;
import org.onap.portalsdk.core.service.RoleService;
import org.onap.portalsdk.core.service.UserProfileService;
import org.onap.portalsdk.core.service.UserService;
import org.onap.portalsdk.core.service.WebServiceCallService;
import org.onap.portalsdk.core.util.JSONUtil;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.slf4j.MDC;
import org.springframework.context.ApplicationContext;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * Implements the REST API interface to answer requests made by Portal app about
 * users and active sessions.
 * 
 * Since an instance of this class will be instantiated by the OnBoarding
 * servlet from the ecompFW library, we cannot use Spring injections here. This
 * 'injection' is done indirectly using AppContextManager class.
 *
 */
public class OnBoardingApiServiceImpl implements IPortalRestAPIService, IPortalRestCentralService {

	private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OnBoardingApiServiceImpl.class);

	private RoleService roleService;
	private UserProfileService userProfileService;
	private IAdminAuthExtension adminAuthExtensionServiceImpl;

	private LoginStrategy loginStrategy;
	private UserService userService;
	private RestApiRequestBuilder restApiRequestBuilder;
	private AppService appServiceImpl;

	private static final String isAccessCentralized = PortalApiProperties
			.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED);
	
	private static final String isCentralized = "remote";
	private static String portalApiVersion = "/v3";
	
	public OnBoardingApiServiceImpl() {
		// Defend against null-pointer exception during server startup
		// that was caused by a spurious Spring annotation on this class.
		ApplicationContext appContext = AppContextManager.getAppContext();
		if (appContext == null)
			throw new RuntimeException("OnBoardingApiServiceImpl ctor failed to get appContext");
		roleService = appContext.getBean(RoleService.class);
		userProfileService = appContext.getBean(UserProfileService.class);
		loginStrategy = appContext.getBean(LoginStrategy.class);
		// initialize the base class definition for Admin Auth Extension
		adminAuthExtensionServiceImpl = appContext.getBean(IAdminAuthExtension.class);
		userService = appContext.getBean(UserService.class);
		if(isCentralized.equals(isAccessCentralized)){
		restApiRequestBuilder = appContext.getBean(RestApiRequestBuilder.class);
		appServiceImpl = appContext.getBean(AppService.class);
		}
	}

	private void setCurrentAttributes(User user, EcompUser userJson) {

		user.setEmail(userJson.getEmail());
		user.setFirstName(userJson.getFirstName());
		user.setHrid(userJson.getHrid());
		user.setJobTitle(userJson.getJobTitle());
		user.setLastName(userJson.getLastName());
		user.setLoginId(userJson.getLoginId());
		user.setOrgManagerUserId(userJson.getOrgManagerUserId());
		user.setMiddleInitial(userJson.getMiddleInitial());
		user.setOrgCode(userJson.getOrgCode());
		user.setOrgId(userJson.getOrgId());
		user.setPhone(userJson.getPhone());
		user.setOrgUserId(userJson.getOrgUserId());
		user.setActive(userJson.isActive());
		// user.setRoles(new TreeSet(userJson.getRoles()));
	}

	@Override
	public void pushUser(EcompUser userJson) throws PortalAPIException {

		if (logger.isDebugEnabled())
			logger.debug(EELFLoggerDelegate.debugLogger, "pushUser was invoked: {}", userJson);
		User user = new User();
		String response = "";
		try {
			// Set input attributes to the object obout to be saved
			setCurrentAttributes(user, userJson);
			user.setRoles(new TreeSet<Role>());
			user.setUserApps(new TreeSet<UserApp>());
			user.setPseudoRoles(new TreeSet<Role>());
			userProfileService.saveUser(user);
			logger.debug(EELFLoggerDelegate.debugLogger, "push user success.");

			// After successful creation, call admin auth extension
			if (adminAuthExtensionServiceImpl != null) {
				try {
					adminAuthExtensionServiceImpl.saveUserExtension(user);
				} catch (Exception ex) {
					logger.error("pushUser: saveUserExtension failed", ex);
				}
			}

			response = "push user success.";
			response = JSONUtil.convertResponseToJSON(response);
		} catch (Exception e) {
			response = "OnboardingApiService.pushUser failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		} finally {
			MDC.remove(SystemProperties.MDC_TIMER);
		}
	}

	@Override
	public void editUser(String loginId, EcompUser userJson) throws PortalAPIException {

		if (logger.isDebugEnabled())
			logger.debug(EELFLoggerDelegate.debugLogger, "OnboardingApi editUser was invoked with loginID {}, JSON {}",
					loginId, userJson);
		User editUser = new User();
		String response = "";
		try {
			setCurrentAttributes(editUser, userJson);
			if (editUser.getOrgUserId() != null) {
				editUser.setLoginId(editUser.getOrgUserId());
			}
			User domainUser = userProfileService.getUserByLoginId(loginId);
			if (domainUser != null)
				domainUser = JSONUtil.mapToDomainUser(domainUser, editUser);
			else
				domainUser = editUser;
			userProfileService.saveUser(domainUser);
			logger.debug(EELFLoggerDelegate.debugLogger, "edit user success.");

			// After successful edit, call the admin auth extension
			if (adminAuthExtensionServiceImpl != null) {
				try {
					adminAuthExtensionServiceImpl.editUserExtension(domainUser);
				} catch (Exception ex) {
					logger.error("editUser: editUserExtension failed", ex);
				}
			}

			response = "edit user success.";
			response = JSONUtil.convertResponseToJSON(response);
		} catch (Exception e) {
			response = "OnboardingApiService.editUser failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		} finally {
			MDC.remove(SystemProperties.MDC_TIMER);
		}

		// return response;
	}

	@Override
	public EcompUser getUser(String loginId) throws PortalAPIException {
		try {
			if (logger.isDebugEnabled())
				logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);

			User user = null;
			if (isCentralized.equals(isAccessCentralized)) {
				String responseString = restApiRequestBuilder.getViaREST(portalApiVersion+"/user/" + loginId, true,
						loginId);
				user = userService.userMapper(responseString);
			}
			else{
			   user = userProfileService.getUserByLoginId(loginId);
			   user.getRoles().removeIf(role -> (role.getActive() == false));
			}
			if (user == null) {
				logger.info(EELFLoggerDelegate.debugLogger, "User + " + loginId + " doesn't exist");
				return null;
				// Unfortunately, Portal is not ready to accept proper error
				// response yet ..
				// commenting throw clauses until portal is ready
				// throw new PortalAPIException("User + " + loginId + " doesn't
				// exist");
			} else
				return UserUtils.convertToEcompUser(user);
		} catch (Exception e) {
			String response = "OnboardingApiService.getUser failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			return null;
			// Unfortunately, Portal is not ready to accept proper error response
			// yet .. commenting throw clauses until portal is ready
			// throw new PortalAPIException(response, e);
		}

	}

	@Override
	public List<EcompUser> getUsers() throws PortalAPIException {
		String users_List = "";
		try {
			if (isCentralized.equals(isAccessCentralized)) {
				List<EcompUser> UsersList = new ArrayList<>();
				List<EcompUser> finalUsersList = new ArrayList<>();
					users_List = restApiRequestBuilder.getViaREST(portalApiVersion + "/users", true, null);
					ObjectMapper mapper = new ObjectMapper();
					UsersList = mapper.readValue(users_List,
							TypeFactory.defaultInstance().constructCollectionType(List.class, EcompUser.class));
					for (EcompUser userString : UsersList) {
						EcompUser ecompUser = mapper.convertValue(userString, EcompUser.class);
						finalUsersList.add(ecompUser);
					}
					return UsersList;
				}
			 else {
				List<User> users = userProfileService.findAllActive();
				List<EcompUser> ecompUsers = new ArrayList<>();
				for (User user : users)
					ecompUsers.add(UserUtils.convertToEcompUser(user));
				return ecompUsers;
			}
		} catch (Exception e) {
			String response = "OnboardingApiService.getUsers failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			if (users_List.equals("")) {
				throw new PortalAPIException("Application is Inactive");
			} else {
				throw new PortalAPIException(response, e);
			}
		}
	}

	@Override
	public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
		try {
			List<Role> roles = roleService.getActiveRoles(requestedLoginId);
			List<EcompRole> ecompRoles = new ArrayList<>();
			for (Role role : roles)
				ecompRoles.add(UserUtils.convertToEcompRole(role));
			return ecompRoles;
		} catch (Exception e) {
			String response = "OnboardingApiService.getAvailableRoles failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		}
	}

	@Override
	public void pushUserRole(String loginId, List<EcompRole> rolesJson) throws PortalAPIException {
		String response = "";
		try {
			if (logger.isDebugEnabled())
				logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}, roles Json {}", loginId,
						rolesJson);
			User user = userProfileService.getUserByLoginId(loginId);
			/*
			 * List<EcompRole> ecompRoles = mapper.readValue(rolesJson,
			 * TypeFactory.defaultInstance().constructCollectionType(List.class,
			 * EcompRole.class));
			 */
			SortedSet<Role> roles = new TreeSet<>();
			for (EcompRole role : rolesJson) {
				roles.add(roleService.getRole(loginId,role.getId()));
			}
			// Replace existing roles with new ones
			replaceExistingRoles(roles, user);

			logger.debug(EELFLoggerDelegate.debugLogger, "push user role success.");

			// After successful creation, call admin auth extension
			if (adminAuthExtensionServiceImpl != null) {
				try {
					adminAuthExtensionServiceImpl.saveUserRoleExtension(roles, user);
				} catch (Exception ex) {
					logger.error("pushUserRole: saveUserRoleExtension failed", ex);
				}
			}
			response = "push user role success.";
			response = JSONUtil.convertResponseToJSON(response);

		} catch (Exception e) {
			response = "OnboardingApiService.pushUserRole failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		} finally {
			MDC.remove(SystemProperties.MDC_TIMER);
		}

	}

	@Override
	public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
		if (logger.isDebugEnabled())
			logger.debug(EELFLoggerDelegate.debugLogger, "## REST API ## loginId: {}", loginId);
		List<EcompRole> ecompRoles = new ArrayList<>();
		try {

			if (isCentralized.equals(isAccessCentralized)) {
				User user = null;
				String responseString = restApiRequestBuilder.getViaREST(portalApiVersion+"/user/" + loginId, true,
						loginId);
				user = userService.userMapper(responseString);
				SortedSet<Role> currentRoles = null;
				if (user != null) {
					currentRoles = user.getRoles();
					if (currentRoles != null)
						for (Role role : currentRoles)
							ecompRoles.add(UserUtils.convertToEcompRole(role));
				}
			} else {
				User user = userProfileService.getUserByLoginId(loginId);
				SortedSet<Role> currentRoles = null;
				if (user != null) {
					currentRoles = user.getRoles();
					currentRoles.removeIf(role -> (role.getActive() == false));
					if (currentRoles != null)
						for (Role role : currentRoles)
							ecompRoles.add(UserUtils.convertToEcompRole(role));
				}
			}
			return ecompRoles;
		} catch (Exception e) {
			String response = "OnboardingApiService.getUserRoles failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		}
	}

	@SuppressWarnings("unchecked")
	private void replaceExistingRoles(SortedSet<Role> roles, User user) {
		// 1. remove existing roles
		Set<UserApp> userApps = user.getUserApps();
		Iterator<UserApp> appsItr = userApps.iterator();
		while (appsItr.hasNext()) {
			UserApp tempUserApp = appsItr.next();
			boolean roleFound = false;
			for (Role role : roles) {
				if (tempUserApp.getRole().getId().equals(role.getId())) {
					roleFound = true;
					break;
				}
			}
			if (!roleFound)
				appsItr.remove();
		}
		user.setUserApps(userApps);
		userProfileService.saveUser(user);

		// 2. add new roles
		user.setRoles(roles);
		userProfileService.saveUser(user);
	}

	@Override
	public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
		WebServiceCallService securityService = AppContextManager.getAppContext().getBean(WebServiceCallService.class);
		try {
			String appUser = request.getHeader("username");
			String password = request.getHeader("password");
			// System.out.println("username = " + appUser);
			// System.out.println("password = " + password);
			boolean flag = securityService.verifyRESTCredential(null, appUser, password);
			// System.out.println("username = " + appUser);
			// System.out.println("password = " + password);
			return flag;

		} catch (Exception e) {
			String response = "OnboardingApiService.isAppAuthenticated failed";
			logger.error(EELFLoggerDelegate.errorLogger, response, e);
			throw new PortalAPIException(response, e);
		}
	}

	public String getSessionTimeOuts() throws Exception {
		return PortalTimeoutHandler.gatherSessionExtensions();
	}

	public void updateSessionTimeOuts(String sessionMap) throws Exception {
		PortalTimeoutHandler.updateSessionExtensions(sessionMap);
	}

	@Override
	public String getUserId(HttpServletRequest request) throws PortalAPIException {
		return loginStrategy.getUserId(request);
	}
	
	@Override
	public Map<String, String> getAppCredentials() throws PortalAPIException{
		Map<String, String> credentialsMap = new HashMap<>();
		String appName = null;
		String appUserName = null;
		String decryptedPwd = null;
		App app = appServiceImpl.getDefaultApp();
		if (app != null) {
			appName = app.getName();
			appUserName = app.getUsername();
			try {
				decryptedPwd = CipherUtil.decryptPKC(app.getAppPassword(),
						SystemProperties.getProperty(SystemProperties.Decryption_Key));
			} catch (CipherUtilException e) {
				logger.error(EELFLoggerDelegate.errorLogger, "getAppCredentials failed", e);
			}
		} else {
			logger.warn(EELFLoggerDelegate.errorLogger,
					"getAppCredentials: Unable to locate the app information from the database.");
			appUserName = "unknown";
			appName = SystemProperties.SDK_NAME;
		}
		credentialsMap.put("username", appUserName);
		credentialsMap.put("password", decryptedPwd);
		credentialsMap.put("appName", appName);
		return credentialsMap;
	}

	@Override
	public Map<String, String> getCredentials() throws PortalAPIException{
		return getAppCredentials();
	}
	

}