PortalRestApiCentralServiceImpl- Add null test before using nullable values
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / ecomp / PortalRestApiCentralServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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  *
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  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.ecomp;
21
22 import fj.data.Either;
23 import java.util.HashMap;
24 import java.util.Map;
25 import javax.servlet.http.HttpServletRequest;
26 import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestCentralService;
27 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
28 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
29 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
30 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
31 import org.onap.portalsdk.core.restful.domain.EcompUser;
32 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
33 import org.openecomp.sdc.be.config.BeEcompErrorManager;
34 import org.openecomp.sdc.be.dao.api.ActionStatus;
35 import org.openecomp.sdc.be.ecomp.converters.EcompUserConverter;
36 import org.openecomp.sdc.be.model.User;
37 import org.openecomp.sdc.be.user.UserBusinessLogic;
38 import org.openecomp.sdc.be.user.UserBusinessLogicExt;
39 import org.openecomp.sdc.common.api.Constants;
40 import org.openecomp.sdc.common.log.wrappers.Logger;
41 import org.openecomp.sdc.exception.ResponseFormat;
42 import org.springframework.context.ApplicationContext;
43 import org.springframework.web.context.ContextLoader;
44
45 public final class PortalRestApiCentralServiceImpl implements IPortalRestCentralService {
46
47     private static final String FAILED_TO_UPDATE_USER_CREDENTIALS = "Failed to update user credentials";
48     private static final String FAILED_TO_DEACTIVATE_USER = "Failed to deactivate user {}";
49     private static final String FAILED_TO_EDIT_USER = "Failed to edit user";
50     private static final String EDIT_USER = "EditUser";
51     private static final String CHECK_ROLES = "checkIfSingleRoleProvided";
52     private static final String RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID = "Received null for argument loginId";
53     private static final String RECEIVED_NULL_ROLES = "Received null roles for user";
54     private static final String RECEIVED_MULTIPLE_ROLES = "Received multiple roles for user {}";
55     private static final String RECEIVED_MULTIPLE_ROLES2 = "Received multiple roles for user";
56     private static final String FAILED_TO_CREATE_USER = "Failed to create user {}";
57     private static final String FAILED_TO_GET_USER_ID_HEADER = "Failed to get user_id header";
58     private static final String JH0003 = "jh0003";
59     private static final String PUSH_USER = "PushUser";
60     private static final String RECEIVED_NULL_FOR_ARGUMENT_USER = "Received null for argument user";
61     private static final Logger log = Logger.getLogger(PortalRestApiCentralServiceImpl.class);
62     private UserBusinessLogic userBusinessLogic;
63     private UserBusinessLogicExt userBusinessLogicExt;
64
65     public PortalRestApiCentralServiceImpl() throws PortalAPIException {
66         try {
67             ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
68             if (ctx == null) {
69                 log.debug("Failed to get CurrentWebApplicationContext.");
70                 BeEcompErrorManager.getInstance().logInternalUnexpectedError("constructor", "Failed to get CurrentWebApplicationContext. Can't get UserBusinessLogic and userBusinessLogicExt", BeEcompErrorManager.ErrorSeverity.ERROR);
71                 throw new PortalAPIException("CurrentWebApplicationContext is null. Failed to get Bean userBusinessLogic and userBusinessLogicExt");
72             } else {
73                 userBusinessLogic = (UserBusinessLogic) ctx.getBean("userBusinessLogic");
74                 userBusinessLogicExt = (UserBusinessLogicExt) ctx.getBean("userBusinessLogicExt");
75             }
76         } catch (Exception e) {
77             log.debug("Failed to get user UserBusinessLogic", e);
78             BeEcompErrorManager.getInstance()
79                 .logInvalidInputError("constructor", "Exception thrown" + e.getMessage(), BeEcompErrorManager.ErrorSeverity.ERROR);
80             throw new PortalAPIException("SDC Internal server error");
81         }
82         log.debug("PortalRestApiCentralServiceImpl Class Instantiated");
83     }
84
85     //For testing purposes
86     PortalRestApiCentralServiceImpl(UserBusinessLogic ubl, UserBusinessLogicExt uble) {
87         this.userBusinessLogic = ubl;
88         this.userBusinessLogicExt = uble;
89     }
90
91     public static void checkIfSingleRoleProvided(EcompUser user) throws PortalAPIException {
92         if (user.getRoles() == null) {
93             log.debug(RECEIVED_NULL_ROLES, user);
94             BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_NULL_ROLES, BeEcompErrorManager.ErrorSeverity.ERROR);
95             throw new PortalAPIException(RECEIVED_NULL_ROLES + user);
96         } else if (user.getRoles().size() > 1) {
97             log.debug(RECEIVED_MULTIPLE_ROLES, user);
98             BeEcompErrorManager.getInstance().logInvalidInputError(CHECK_ROLES, RECEIVED_MULTIPLE_ROLES2, BeEcompErrorManager.ErrorSeverity.ERROR);
99             throw new PortalAPIException(RECEIVED_MULTIPLE_ROLES2 + user);
100         }
101     }
102
103     @Override
104     public Map<String, String> getAppCredentials() throws PortalAPIException {
105         Map<String, String> credMap = new HashMap<>();
106         String portalUser = PortalApiProperties.getProperty(PortalPropertiesEnum.USER.value());
107         String password = PortalApiProperties.getProperty(PortalPropertiesEnum.PASSWORD.value());
108         String appName = PortalApiProperties.getProperty(PortalPropertiesEnum.APP_NAME.value());
109         try {
110             credMap.put("username", CipherUtil.decryptPKC(portalUser));
111             credMap.put("password", CipherUtil.decryptPKC(password));
112             credMap.put("appName", CipherUtil.decryptPKC(appName));
113         } catch (CipherUtilException e) {
114             log.debug("User authentication failed - Decryption failed", e);
115             throw new PortalAPIException("Failed to decrypt" + e.getMessage());
116         }
117         log.debug("the credentials map for portal is {}", credMap);
118         return credMap;
119     }
120
121     @Override
122     public void pushUser(EcompUser user) throws PortalAPIException {
123         log.debug("Start handle request of ECOMP pushUser");
124         if (user == null) {
125             BeEcompErrorManager.getInstance()
126                 .logInvalidInputError(PUSH_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO);
127             log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
128             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
129         }
130         checkIfSingleRoleProvided(user);
131         final String modifierAttId = JH0003;
132         log.debug("modifier id is {}", modifierAttId);
133         User convertedAsdcUser = EcompUserConverter.convertEcompUserToUser(user);
134         try {
135             log.debug("Before creating ecomp user {} sdc user {}", user, convertedAsdcUser);
136             userBusinessLogic.createUser(modifierAttId, convertedAsdcUser);
137         } catch (Exception e) {
138             log.debug(FAILED_TO_CREATE_USER, user, e);
139             BeEcompErrorManager.getInstance().logInvalidInputError(PUSH_USER, FAILED_TO_CREATE_USER, BeEcompErrorManager.ErrorSeverity.ERROR);
140             throw new PortalAPIException(FAILED_TO_CREATE_USER + e.getMessage());
141         }
142         log.debug("User created ecomp user {} sdc user {}", user, convertedAsdcUser);
143     }
144
145     @Override
146     public void editUser(String loginId, EcompUser user) throws PortalAPIException {
147         if (user == null) {
148             log.debug(RECEIVED_NULL_FOR_ARGUMENT_USER);
149             BeEcompErrorManager.getInstance()
150                 .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_USER, BeEcompErrorManager.ErrorSeverity.INFO);
151             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_USER);
152         } else if (loginId == null) {
153             log.debug(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
154             BeEcompErrorManager.getInstance()
155                 .logInvalidInputError(EDIT_USER, RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID, BeEcompErrorManager.ErrorSeverity.INFO);
156             throw new PortalAPIException(RECEIVED_NULL_FOR_ARGUMENT_LOGIN_ID);
157         }
158         log.debug("Start handle request of ECOMP editUser {} with loginId {} with follopwing roles {}", user, loginId, user.getRoles());
159         final String modifierAttId = JH0003;
160         log.debug("modifier id is {}", modifierAttId);
161         if (user.getLoginId() != null && !user.getLoginId().equals(loginId)) {
162             log.debug("loginId and user loginId not equal");
163             BeEcompErrorManager.getInstance()
164                 .logInvalidInputError(EDIT_USER, "loginId and user loginId not equal", BeEcompErrorManager.ErrorSeverity.INFO);
165             throw new PortalAPIException("loginId not equals to the user loginId field");
166         } else if (user.getLoginId() == null) {
167             user.setLoginId(loginId);
168         }
169         Either<User, ActionStatus> verifyNewUser;
170         try {
171             verifyNewUser = userBusinessLogic.verifyNewUserForPortal(user.getLoginId());
172         } catch (ComponentException e) {
173             log.debug("Failed to verify new user", e);
174             throw new PortalAPIException(e.getCause());
175         }
176         if (verifyNewUser.isRight() && (ActionStatus.USER_NOT_FOUND.equals(verifyNewUser.right().value()) || ActionStatus.USER_INACTIVE
177             .equals(verifyNewUser.right().value()))) {
178             log.debug("Edit user for user that not exist in DB, executing push user flow {}", user);
179             pushUser(user);
180             return;
181         }
182         User asdcUser = EcompUserConverter.convertEcompUserToUser(user);
183         log.debug("Before editing ecomp user {} sdc user {}", user, asdcUser);
184         Either<User, ResponseFormat> updateUserCredentialsResponse = userBusinessLogic.updateUserCredentials(asdcUser);
185         if (updateUserCredentialsResponse.isRight()) {
186             log.debug(FAILED_TO_UPDATE_USER_CREDENTIALS);
187             BeEcompErrorManager.getInstance()
188                 .logInvalidInputError(EDIT_USER, FAILED_TO_UPDATE_USER_CREDENTIALS, BeEcompErrorManager.ErrorSeverity.ERROR);
189             throw new PortalAPIException(FAILED_TO_EDIT_USER + updateUserCredentialsResponse.right().value());
190         }
191         if (user.getRoles() == null || user.getRoles().isEmpty()) {
192             try {
193                 log.debug("Before deactivating ecomp user {} sdc user {}", user, asdcUser);
194                 userBusinessLogicExt.deActivateUser(modifierAttId, loginId);
195             } catch (Exception e) {
196                 log.debug("Error: Failed to deactivate user {}", loginId);
197                 BeEcompErrorManager.getInstance()
198                     .logInvalidInputError(FAILED_TO_DEACTIVATE_USER, "Failed to deactivate user", BeEcompErrorManager.ErrorSeverity.INFO);
199                 throw new PortalAPIException("Error: Failed to deactivate user" + e);
200             }
201         } else {
202             checkIfSingleRoleProvided(user);
203             try {
204                 log.debug("Before updating ecomp user {} sdc user {}", user, asdcUser);
205                 userBusinessLogic.updateUserRole(modifierAttId, loginId, asdcUser.getRole());
206             } catch (Exception e) {
207                 log.debug("Error: Failed to update user role {}", loginId);
208                 BeEcompErrorManager.getInstance()
209                     .logInvalidInputError(FAILED_TO_EDIT_USER, "Failed to update user role", BeEcompErrorManager.ErrorSeverity.INFO);
210                 throw new PortalAPIException("Error: Failed to update user role" + e);
211             }
212         }
213         log.debug("user updated ecomp user {} sdc user {}", user, asdcUser);
214     }
215
216     @Override
217     public String getUserId(HttpServletRequest request) throws PortalAPIException {
218         String header = request.getHeader(Constants.USER_ID_HEADER);
219         if (header == null) {
220             log.debug(FAILED_TO_GET_USER_ID_HEADER);
221             BeEcompErrorManager.getInstance()
222                 .logInvalidInputError("getUserId", FAILED_TO_GET_USER_ID_HEADER, BeEcompErrorManager.ErrorSeverity.ERROR);
223             throw new PortalAPIException(FAILED_TO_GET_USER_ID_HEADER);
224         }
225         return header;
226     }
227 }