Fix critical cross site scripting
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / user / UserBusinessLogic.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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  *
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.user;
21
22 import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.ADD_USER;
23 import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.GET_USERS_LIST;
24 import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_USER;
25
26 import fj.data.Either;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Objects;
32 import java.util.stream.Collectors;
33 import org.apache.commons.collections.CollectionUtils;
34 import org.apache.commons.lang3.StringUtils;
35 import org.apache.tinkerpop.gremlin.structure.Edge;
36 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
37 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
40 import org.openecomp.sdc.be.facade.operations.UserOperation;
41 import org.openecomp.sdc.be.impl.ComponentsUtils;
42 import org.openecomp.sdc.be.model.LifecycleStateEnum;
43 import org.openecomp.sdc.be.model.User;
44 import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
45 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
46 import org.openecomp.sdc.common.api.UserRoleEnum;
47 import org.openecomp.sdc.common.datastructure.UserContext;
48 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
49 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
50 import org.openecomp.sdc.common.log.wrappers.Logger;
51 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
52 import org.openecomp.sdc.exception.ResponseFormat;
53
54 @org.springframework.stereotype.Component
55 public class UserBusinessLogic {
56
57     private static final Logger log = Logger.getLogger(UserBusinessLogic.class);
58     private static final String IN_CERTIFICATION_CHECKED_OUT = "in-certification/checked-out";
59     private static final String UNKNOWN = "UNKNOWN";
60     private static UserAdminValidator userAdminValidator = UserAdminValidator.getInstance();
61     private final UserAdminOperation userAdminOperation;
62     private final ComponentsUtils componentsUtils;
63     private final UserOperation facadeUserOperation;
64
65     public UserBusinessLogic(UserAdminOperation userAdminOperation, ComponentsUtils componentsUtils, UserOperation facadeUserOperation) {
66         this.userAdminOperation = userAdminOperation;
67         this.componentsUtils = componentsUtils;
68         this.facadeUserOperation = facadeUserOperation;
69     }
70
71     public User getUser(String userId, boolean inTransaction) {
72         userId = decryptUserId(userId);
73         Either<User, ActionStatus> result = userAdminOperation.getUserData(userId, inTransaction);
74         if (result.isRight()) {
75             handleUserAccessAuditing(userId, result.right().value());
76             throw new ByActionStatusComponentException(result.right().value(), userId);
77         }
78         User user = result.left().value();
79         if (user == null) {
80             handleUserAccessAuditing(userId, ActionStatus.GENERAL_ERROR);
81             throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
82         }
83         return user;
84     }
85
86     private String decryptUserId(final String userId) {
87         if (StringUtils.isNotEmpty(userId)) {
88             try {
89                 return CipherUtil.decryptPKC(userId);
90             } catch (final Exception e) {
91                 return userId;
92             }
93         }
94         return userId;
95     }
96
97     public User getUser(String userId) {
98         userId = decryptUserId(userId);
99         UserContext userContext = ThreadLocalsHolder.getUserContext();
100         if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId())) {
101             log.info("USER_NOT_FOUND, user=" + userId);
102             handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND);
103             throw new ByActionStatusComponentException(ActionStatus.USER_NOT_FOUND, userId);
104         }
105         if (Objects.isNull(userContext.getUserRoles())) {
106             userContext.setUserRoles(new HashSet<>());
107         }
108         return convertUserContextToUser(userContext);
109     }
110
111     protected User convertUserContextToUser(UserContext userContext) {
112         User user = new User();
113         user.setUserId(userContext.getUserId());
114         user.setFirstName(userContext.getFirstName());
115         user.setLastName(userContext.getLastName());
116         boolean userHasRoles = userContext.getUserRoles().iterator().hasNext();
117         user.setRole(!userHasRoles ? null : userContext.getUserRoles().iterator().next());
118         user.setStatus(userHasRoles ? UserStatusEnum.ACTIVE : UserStatusEnum.INACTIVE);
119         return user;
120     }
121
122     public boolean hasActiveUser(String userId) {
123         userId = decryptUserId(userId);
124         UserContext userContext = ThreadLocalsHolder.getUserContext();
125         if (Objects.isNull(userContext) || Objects.isNull(userContext.getUserId())) {
126             handleUserAccessAuditing(userId, ActionStatus.USER_NOT_FOUND);
127             return false;
128         }
129         if (Objects.isNull(userContext.getUserRoles()) || userContext.getUserRoles().isEmpty()) {
130             handleUserAccessAuditing(userId, ActionStatus.USER_INACTIVE);
131             return false;
132         }
133         return true;
134     }
135
136     public User createUser(String modifierUserId, User newUser) {
137         User modifier = getValidModifier(modifierUserId, newUser.getUserId(), AuditingActionEnum.ADD_USER);
138         // verify user not exist
139         String newUserId = newUser.getUserId();
140         Either<User, ActionStatus> eitherUserInDB = verifyNewUser(newUserId);
141         newUser.setStatus(UserStatusEnum.ACTIVE);
142         validateEmail(newUser);
143         validateRole(newUser);
144         // handle last login if user is import
145         if (newUser.getLastLoginTime() == null) {
146             newUser.setLastLoginTime(0L);
147         }
148         User createdUser;
149         if (ActionStatus.USER_INACTIVE.equals(eitherUserInDB.right()
150             .value())) { // user inactive - update state                                                                                  // exist
151             newUser.setLastLoginTime(0L);
152             createdUser = userAdminOperation.updateUserData(newUser);
153         } else { // user does not exist - create new user
154             if (!userAdminValidator.validateUserId(newUserId)) {
155                 log.debug("createUser method - user has invalid userId = {}", newUser.getUserId());
156                 throw new ByActionStatusComponentException(ActionStatus.INVALID_USER_ID, newUserId);
157             }
158             createdUser = userAdminOperation.saveUserData(newUser);
159         }
160         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
161         handleAuditing(modifier, null, createdUser, responseFormat, AuditingActionEnum.ADD_USER);
162         getFacadeUserOperation().updateUserCache(UserOperationEnum.CREATE, createdUser.getUserId(), createdUser.getRole());
163         return createdUser;
164     }
165
166     private void validateRole(User newUser) {
167         if (newUser.getRole() == null || newUser.getRole().length() == 0) {
168             newUser.setRole(Role.DESIGNER.name());
169         } else {
170             if (!userAdminValidator.validateRole(newUser.getRole())) {
171                 log.debug("createUser method - user has invalid role = {}", newUser.getUserId());
172                 throw new ByActionStatusComponentException(ActionStatus.INVALID_ROLE, newUser.getRole());
173             }
174         }
175     }
176
177     private void validateEmail(User newUser) {
178         if (newUser.getEmail() != null && !userAdminValidator.validateEmail(newUser.getEmail())) {
179             log.debug("createUser method - user has invalid email = {}", newUser.getUserId());
180             throw new ByActionStatusComponentException(ActionStatus.INVALID_EMAIL_ADDRESS, newUser.getEmail());
181         }
182     }
183
184     private Either<User, ActionStatus> verifyNewUser(String newUserId) {
185         Either<User, ActionStatus> eitherUserInDB = getUserData(newUserId);
186         if (eitherUserInDB.isRight()) {
187             ActionStatus status = eitherUserInDB.right().value();
188             if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) {
189                 componentsUtils.auditAdminUserActionAndThrowException(ADD_USER, null, null, null, status, newUserId);
190             }
191         } else {// User exist in DB
192             User userFromDb = eitherUserInDB.left().value();
193             if (userFromDb.getStatus() == UserStatusEnum.ACTIVE) {
194                 log.debug("createUser method - user with id {} already exist with id: {}", newUserId, userFromDb.getUserId());
195                 componentsUtils.auditAdminUserActionAndThrowException(ADD_USER, null, null, null, ActionStatus.USER_ALREADY_EXIST, newUserId);
196             }
197         }
198         return eitherUserInDB;
199     }
200
201     public Either<User, ActionStatus> verifyNewUserForPortal(String newUserId) {
202         Either<User, ActionStatus> eitherUserInDB = getUserData(newUserId);
203         if (eitherUserInDB.isRight()) {
204             ActionStatus status = eitherUserInDB.right().value();
205             if (!ActionStatus.USER_NOT_FOUND.equals(status) && !ActionStatus.USER_INACTIVE.equals(status)) {
206                 componentsUtils.auditAdminUserActionAndThrowException(ADD_USER, null, null, null, status, newUserId);
207             }
208         }
209         return eitherUserInDB;
210     }
211
212     private Either<User, ActionStatus> getUserData(String newUserId) {
213         if (newUserId == null) {
214             log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "Create user - new user id is missing");
215             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
216         }
217         return userAdminOperation.getUserData(newUserId, false);
218     }
219
220     public User updateUserRole(String modifierUserId, String userIdToUpdate, String userRole) {
221         User modifier = getValidModifier(modifierUserId, userIdToUpdate, UPDATE_USER);
222         User userToUpdate = getUser(userIdToUpdate, false);
223         validateChangeRoleToAllowedRoles(userRole);
224         List<Edge> userPendingTasks = userAdminOperation.getUserPendingTasksList(userToUpdate, getChangeRoleStateLimitations(userToUpdate));
225         if (!userPendingTasks.isEmpty()) {
226             log.debug("updateUserRole method - User cannot be updated, user have pending projects userId {}", userIdToUpdate);
227             String userInfo = userToUpdate.getFirstName() + " " + userToUpdate.getLastName() + '(' + userToUpdate.getUserId() + ')';
228             componentsUtils.auditAdminUserActionAndThrowException(UPDATE_USER, modifier, userToUpdate, null,
229                 ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS, userInfo, IN_CERTIFICATION_CHECKED_OUT);
230         }
231         Role newRole = Role.valueOf(userRole);
232         User newUser = new User();
233         newUser.setRole(newRole.name());
234         newUser.setUserId(userIdToUpdate);
235         User updatedUser = userAdminOperation.updateUserData(newUser);
236         handleAuditing(modifier, userToUpdate, updatedUser, componentsUtils.getResponseFormat(ActionStatus.OK), UPDATE_USER);
237         getFacadeUserOperation().updateUserCache(UserOperationEnum.CHANGE_ROLE, updatedUser.getUserId(), updatedUser.getRole());
238         return updatedUser;
239     }
240
241     private void validateChangeRoleToAllowedRoles(String userRole) {
242         List<String> allowedRoles = Arrays.asList(UserRoleEnum.DESIGNER.getName(), UserRoleEnum.ADMIN.getName());
243         if (!allowedRoles.contains(userRole)) {
244             throw new ByActionStatusComponentException(ActionStatus.INVALID_ROLE, userRole);
245         }
246     }
247
248     User getValidModifier(String modifierUserId, String userIdHandle, AuditingActionEnum actionEnum) {
249         if (modifierUserId == null) {
250             log.error(EcompLoggerErrorCode.DATA_ERROR, "", "", "user modifier is missing");
251             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
252         }
253         User modifier = getUser(modifierUserId, false);
254         if (!modifier.getRole().equals(UserRoleEnum.ADMIN.getName())) {
255             log.debug("user is not admin. Id = {}", modifier.getUserId());
256             componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.RESTRICTED_OPERATION);
257         }
258         if (modifier.getUserId().equals(userIdHandle)) {
259             log.debug("admin user cannot act on self. Id = {}", modifier.getUserId());
260             componentsUtils.auditAdminUserActionAndThrowException(actionEnum, modifier, null, null, ActionStatus.UPDATE_USER_ADMIN_CONFLICT);
261         }
262         return modifier;
263     }
264
265     public List<User> getAllAdminUsers() {
266         Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(Role.ADMIN.name(), null);
267         if (response.isRight()) {
268             throw new ByActionStatusComponentException(response.right().value());
269         }
270         return response.left().value();
271     }
272
273     public List<User> getUsersList(String modifierAttId, List<String> roles, String rolesStr) {
274         if (modifierAttId == null) {
275             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
276         }
277         User user = getUser(modifierAttId, false);
278         Either<List<User>, ResponseFormat> getResponse;
279         List<User> userList = new ArrayList<>();
280         if (!CollectionUtils.isEmpty(roles)) {
281             for (String role : roles) {
282                 if (!userAdminValidator.validateRole(role)) {
283                     componentsUtils.auditAdminUserActionAndThrowException(GET_USERS_LIST, user, null, null, ActionStatus.INVALID_ROLE, role);
284                 }
285                 getResponse = getUsersPerRole(role, user, rolesStr);
286                 userList.addAll(getResponse.left().value());
287             }
288         } else {
289             rolesStr = "All";
290             getResponse = getUsersPerRole(null, user, rolesStr);
291             userList.addAll(getResponse.left().value());
292         }
293         handleGetUsersListAuditing(user, componentsUtils.getResponseFormat(ActionStatus.OK), rolesStr);
294         return userList;
295     }
296
297     Either<List<User>, ResponseFormat> getUsersPerRole(String role, User user, String rolesStr) {
298         ResponseFormat responseFormat;
299         Either<List<User>, ActionStatus> response = userAdminOperation.getAllUsersWithRole(role, UserStatusEnum.ACTIVE.name());
300         if (response.isRight()) {
301             responseFormat = componentsUtils.getResponseFormat(response.right().value());
302             handleGetUsersListAuditing(user, responseFormat, rolesStr);
303             return Either.right(responseFormat);
304         }
305         List<User> users = response.left().value().stream().filter(u -> StringUtils.isNotEmpty(u.getUserId())).collect(Collectors.toList());
306         return Either.left(users);
307     }
308
309     private void handleGetUsersListAuditing(User user, ResponseFormat responseFormat, String details) {
310         componentsUtils.auditGetUsersList(user, details, responseFormat);
311     }
312
313     private void handleAuditing(User modifier, User userBefore, User userAfter, ResponseFormat responseFormat, AuditingActionEnum actionName) {
314         componentsUtils.auditAdminUserAction(actionName, modifier, userBefore, userAfter, responseFormat);
315     }
316
317     private void handleUserAccessAuditing(User user, ResponseFormat responseFormat) {
318         componentsUtils.auditUserAccess(user, responseFormat);
319     }
320
321     private void handleUserAccessAuditing(String userId, ActionStatus status, String... params) {
322         componentsUtils.auditUserAccess(new User(userId), status, params);
323     }
324
325     public User authorize(User authUser) {
326         String userId = authUser.getUserId();
327         if (userId == null) {
328             log.debug("authorize method -  user id is missing");
329             throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
330         }
331         User user = getUser(userId, false);
332         String firstName = authUser.getFirstName();
333         if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) {
334             user.setFirstName(firstName);
335         }
336         String lastName = authUser.getLastName();
337         if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) {
338             user.setLastName(lastName);
339         }
340         String email = authUser.getEmail();
341         if (email != null && !email.isEmpty() && !email.equals(user.getEmail())) {
342             user.setEmail(email);
343         }
344         // last login time stamp handle
345         user.setLastLoginTime();
346         User updatedUser = userAdminOperation.updateUserData(user);
347         Long lastLoginTime = user.getLastLoginTime();
348         if (lastLoginTime != null) {
349             updatedUser.setLastLoginTime(lastLoginTime);
350         } else {
351             updatedUser.setLastLoginTime(0L);
352         }
353         handleUserAccessAuditing(updatedUser.getUserId(), ActionStatus.OK);
354         ASDCKpiApi.countUsersAuthorizations();
355         return updatedUser;
356     }
357
358     /*
359      * The method updates user credentials only, the role is neglected The role updated through updateRole method
360      */
361     public Either<User, ResponseFormat> updateUserCredentials(User updatedUserCred) {
362         ResponseFormat responseFormat;
363         String userId = updatedUserCred.getUserId();
364         if (userId == null) {
365             updatedUserCred.setUserId(UNKNOWN);
366             log.debug("updateUserCredentials method - user header is missing");
367             responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
368             handleUserAccessAuditing(updatedUserCred, responseFormat);
369             return Either.right(responseFormat);
370         }
371         User user = getUser(userId, false);
372         String firstName = updatedUserCred.getFirstName();
373         if (firstName != null && !firstName.isEmpty() && !firstName.equals(user.getFirstName())) {
374             user.setFirstName(firstName);
375         }
376         String lastName = updatedUserCred.getLastName();
377         if (lastName != null && !lastName.isEmpty() && !lastName.equals(user.getLastName())) {
378             user.setLastName(lastName);
379         }
380         String email = updatedUserCred.getEmail();
381         if (email != null && !email.isEmpty() && !email.equals(user.getEmail())) {
382             user.setEmail(email);
383         }
384         if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() != null) {
385             if (updatedUserCred.getLastLoginTime() > user.getLastLoginTime()) {
386                 user.setLastLoginTime(updatedUserCred.getLastLoginTime());
387             }
388         } else if (updatedUserCred.getLastLoginTime() != null && user.getLastLoginTime() == null) {
389             user.setLastLoginTime(updatedUserCred.getLastLoginTime());
390         }
391         User updatedUser = userAdminOperation.updateUserData(user);
392         responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
393         handleUserAccessAuditing(updatedUser, responseFormat);
394         return Either.left(updatedUser);
395     }
396
397     private List<Object> getChangeRoleStateLimitations(User user) {
398         UserRoleEnum role = UserRoleEnum.valueOf(user.getRole());
399         List<Object> properties = new ArrayList<>();
400         switch (role) {
401             case DESIGNER:
402             case PRODUCT_STRATEGIST:
403             case PRODUCT_MANAGER:
404             case ADMIN:
405                 properties.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
406                 break;
407             case TESTER:
408                 // For tester we allow change role even if there are pending task (per US468155 in 1810)
409             default:
410         }
411         return properties;
412     }
413
414     public UserOperation getFacadeUserOperation() {
415         return facadeUserOperation;
416     }
417 }