4db24c1a258d716a3ded8180f08e65baca09c8e3
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ConsumerBusinessLogic.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.components.impl;
21
22 import fj.data.Either;
23 import java.util.Date;
24 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
25 import org.openecomp.sdc.be.config.BeEcompErrorManager;
26 import org.openecomp.sdc.be.dao.api.ActionStatus;
27 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
28 import org.openecomp.sdc.be.model.ConsumerDefinition;
29 import org.openecomp.sdc.be.model.User;
30 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
31 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
32 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
33 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
34 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
35 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
36 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
37 import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
38 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
39 import org.openecomp.sdc.be.resources.data.ConsumerData;
40 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
41 import org.openecomp.sdc.be.user.Role;
42 import org.openecomp.sdc.common.log.wrappers.Logger;
43 import org.openecomp.sdc.common.util.ValidationUtils;
44 import org.openecomp.sdc.exception.ResponseFormat;
45 import org.springframework.beans.factory.annotation.Autowired;
46 import org.springframework.stereotype.Component;
47
48 @Component("ConsumerBusinessLogic")
49 public class ConsumerBusinessLogic extends BaseBusinessLogic {
50
51     private static final String CONSUMER_NAME = "Consumer name";
52     private static final String CONSUMER_SALT = "Consumer salt";
53     private static final String CONSUMER_PW = "Consumer password";
54     private static final String AUDIT_BEFORE_SENDING_RESPONSE = "audit before sending response";
55     private static final Logger log = Logger.getLogger(ConsumerBusinessLogic.class.getName());
56     @javax.annotation.Resource
57     private ConsumerOperation consumerOperation;
58
59     @Autowired
60     public ConsumerBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation, IGroupInstanceOperation groupInstanceOperation,
61                                  IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
62                                  InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
63         super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
64             artifactToscaOperation);
65     }
66
67     public Either<ConsumerDefinition, ResponseFormat> createConsumer(User user, ConsumerDefinition consumer) {
68         Either<User, ResponseFormat> userValidation = validateUser(user, consumer, AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS);
69         if (userValidation.isRight()) {
70             return Either.right(userValidation.right().value());
71         }
72         checkFieldsForOverrideAttempt(consumer);
73         user = userValidation.left().value();
74         consumer.setLastModfierAtuid(user.getUserId());
75         Either<ConsumerDefinition, ResponseFormat> consumerValidationResponse = validateConsumer(consumer);
76         if (consumerValidationResponse.isRight()) {
77             ResponseFormat responseFormat = consumerValidationResponse.right().value();
78             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
79             return Either.right(responseFormat);
80         }
81         String consumerName = consumer.getConsumerName();
82         StorageOperationStatus lockResult = graphLockOperation.lockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
83         if (!lockResult.equals(StorageOperationStatus.OK)) {
84             BeEcompErrorManager.getInstance().logBeFailedLockObjectError("createConsumer", NodeTypeEnum.ConsumerCredentials.getName(), consumerName);
85             log.debug("Failed to lock consumer: {} error - {}", consumerName, lockResult);
86             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
87             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
88             return Either.right(responseFormat);
89         }
90         try {
91             Either<ConsumerData, StorageOperationStatus> getResponse = consumerOperation.getCredentials(consumerName);
92             if (getResponse.isLeft() && getResponse.left().value() != null) {
93                 return updateConsumer(consumer);
94             }
95             Date date = new Date();
96             consumer.setConsumerDetailsLastupdatedtime(date.getTime());
97             consumer.setConsumerLastAuthenticationTime(Long.valueOf(0));
98             Either<ConsumerData, StorageOperationStatus> createResponse = consumerOperation.createCredentials(new ConsumerData(consumer));
99             if (createResponse.isRight()) {
100                 ResponseFormat responseFormat = componentsUtils
101                     .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(createResponse.right().value()));
102                 componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
103                 return Either.right(responseFormat);
104             }
105             log.debug("Consumer created successfully!!!");
106             consumer = new ConsumerDefinition(createResponse.left().value().getConsumerDataDefinition());
107             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
108             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.ADD_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
109             return Either.left(consumer);
110         } finally {
111             graphLockOperation.unlockComponent(consumerName, NodeTypeEnum.ConsumerCredentials);
112         }
113     }
114
115     private Either<User, ResponseFormat> validateUser(User user, ConsumerDefinition consumer, AuditingActionEnum auditAction) {
116         if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
117             log.debug("createEcompUser method - user is missing. userId= {}", user.getUserId());
118             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
119             log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
120             componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
121             return Either.right(responseFormat);
122         }
123         log.debug("get user from DB");
124         User userFromDB;
125         try {
126             userFromDB = userAdmin.getUser(user.getUserId(), false);
127         } catch (ByActionStatusComponentException e) {
128             log.debug("createEcompUser method - user is not listed. userId= {}", user.getUserId());
129             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_ACCESS);
130             log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
131             componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
132             return Either.right(responseFormat);
133         }
134         user = userFromDB;
135         // validate user role
136         log.debug("validate user role");
137         if (!user.getRole().equals(Role.ADMIN.name())) {
138             log.info("role {} is not allowed to perform this action", user.getRole());
139             ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
140             log.debug(AUDIT_BEFORE_SENDING_RESPONSE);
141             componentsUtils.auditConsumerCredentialsEvent(auditAction, consumer, responseFormat, user);
142             return Either.right(responseFormat);
143         }
144         return Either.left(user);
145     }
146
147     private Either<ConsumerDefinition, ResponseFormat> validateConsumer(ConsumerDefinition consumer) {
148         Either<ConsumerDefinition, ResponseFormat> validateConsumerName = validateConsumerName(consumer);
149         if (validateConsumerName.isRight()) {
150             return Either.right(validateConsumerName.right().value());
151         }
152         Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword = validateConsumerPassword(consumer);
153         if (validateConsumerPassword.isRight()) {
154             return Either.right(validateConsumerPassword.right().value());
155         }
156         consumer = validateConsumerPassword.left().value();
157         Either<ConsumerDefinition, ResponseFormat> validateEcompUserSalt = validateConsumerSalt(consumer);
158         if (validateEcompUserSalt.isRight()) {
159             return Either.right(validateEcompUserSalt.right().value());
160         }
161         return Either.left(consumer);
162     }
163
164     private Either<ConsumerDefinition, ResponseFormat> validateConsumerName(ConsumerDefinition consumer) {
165         String name = consumer.getConsumerName();
166         if (!ValidationUtils.validateStringNotEmpty(name)) {
167             log.debug("Consumer name cannot be empty.");
168             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_NAME));
169         }
170         if (!ValidationUtils.validateConsumerName(name)) {
171             log.debug("Consumer name is invalid.");
172             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
173         }
174         if (!ValidationUtils.validateLength(name, ValidationUtils.CONSUMER_NAME_MAX_LENGTH)) {
175             log.debug("Consumer name exceeds limit.");
176             return Either.right(componentsUtils
177                 .getResponseFormat(ActionStatus.EXCEEDS_LIMIT, CONSUMER_NAME, String.valueOf(ValidationUtils.CONSUMER_NAME_MAX_LENGTH)));
178         }
179         if (!ValidationUtils.isUTF8Str(name)) {
180             log.debug("Consumer name includes non UTF 8 characters.");
181             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_NAME));
182         }
183         return Either.left(consumer);
184     }
185
186     private Either<ConsumerDefinition, ResponseFormat> validateConsumerPassword(ConsumerDefinition consumer) {
187         String password = consumer.getConsumerPassword();
188         if (!ValidationUtils.validateStringNotEmpty(password)) {
189             log.debug("Consumer password cannot be empty.");
190             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_PW));
191         }
192         if (password.length() != ValidationUtils.CONSUMER_PASSWORD_LENGTH) {
193             log.debug("Consumer password length is not valid.");
194             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_PW));
195         }
196         consumer.setConsumerPassword(password.toLowerCase());
197         if (!ValidationUtils.validateConsumerPassSalt(consumer.getConsumerPassword())) {
198             log.debug("Consumer password is invalid.");
199             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_PW));
200         }
201         return Either.left(consumer);
202     }
203
204     private Either<ConsumerDefinition, ResponseFormat> validateConsumerSalt(ConsumerDefinition consumer) {
205         String salt = consumer.getConsumerSalt();
206         if (!ValidationUtils.validateStringNotEmpty(salt)) {
207             log.debug("Consumer salt cannot be empty.");
208             return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, CONSUMER_SALT));
209         }
210         if (salt.length() != ValidationUtils.CONSUMER_SALT_LENGTH) {
211             log.debug("Consumer salt length is not valid.");
212             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_LENGTH, CONSUMER_SALT));
213         }
214         if (!ValidationUtils.validateConsumerPassSalt(salt)) {
215             log.debug("Consumer salt is invalid.");
216             return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM, CONSUMER_SALT));
217         }
218         return Either.left(consumer);
219     }
220
221     public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId, User user) {
222         ConsumerDefinition tmpConsumer = new ConsumerDefinition();
223         tmpConsumer.setConsumerName(consumerId);
224         // In case of filter (southbound) call
225         if (user != null) {
226             Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS);
227             if (userValidation.isRight()) {
228                 return Either.right(userValidation.right().value());
229             }
230             user = userValidation.left().value();
231         }
232         Either<ConsumerData, StorageOperationStatus> getResult = consumerOperation.getCredentials(consumerId);
233         if (getResult.isRight()) {
234             ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(getResult.right().value());
235             ResponseFormat responseFormat;
236             if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
237                 responseFormat = componentsUtils.getResponseFormat(action, consumerId);
238             } else {
239                 responseFormat = componentsUtils.getResponseFormat(action);
240             }
241             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
242             return Either.right(responseFormat);
243         }
244         ConsumerDefinition consumer = new ConsumerDefinition(getResult.left().value().getConsumerDataDefinition());
245         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
246         componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.GET_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
247         return Either.left(consumer);
248     }
249
250     public Either<ConsumerDefinition, ResponseFormat> getConsumer(String consumerId) {
251         return getConsumer(consumerId, null);
252     }
253
254     public Either<ConsumerDefinition, ResponseFormat> deleteConsumer(String consumerId, User user) {
255         ConsumerDefinition tmpConsumer = new ConsumerDefinition();
256         tmpConsumer.setConsumerName(consumerId);
257         Either<User, ResponseFormat> userValidation = validateUser(user, tmpConsumer, AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS);
258         if (userValidation.isRight()) {
259             return Either.right(userValidation.right().value());
260         }
261         user = userValidation.left().value();
262         Either<ConsumerData, StorageOperationStatus> deleteResult = consumerOperation.deleteCredentials(consumerId);
263         if (deleteResult.isRight()) {
264             ActionStatus action = componentsUtils.convertFromStorageResponseForConsumer(deleteResult.right().value());
265             ResponseFormat responseFormat;
266             if (action == ActionStatus.ECOMP_USER_NOT_FOUND) {
267                 responseFormat = componentsUtils.getResponseFormat(action, consumerId);
268             } else {
269                 responseFormat = componentsUtils.getResponseFormat(action);
270             }
271             componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, tmpConsumer, responseFormat, user);
272             return Either.right(responseFormat);
273         }
274         ConsumerDefinition consumer = new ConsumerDefinition(deleteResult.left().value().getConsumerDataDefinition());
275         ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
276         componentsUtils.auditConsumerCredentialsEvent(AuditingActionEnum.DELETE_ECOMP_USER_CREDENTIALS, consumer, responseFormat, user);
277         return Either.left(consumer);
278     }
279
280     public Either<ConsumerDefinition, ResponseFormat> updateConsumer(ConsumerDefinition consumer) {
281         Either<ConsumerData, StorageOperationStatus> updateResult = consumerOperation.updateCredentials(new ConsumerData(consumer));
282         if (updateResult.isRight()) {
283             ResponseFormat responseFormat = componentsUtils
284                 .getResponseFormat(componentsUtils.convertFromStorageResponseForConsumer(updateResult.right().value()));
285             return Either.right(responseFormat);
286         }
287         consumer = new ConsumerDefinition(updateResult.left().value().getConsumerDataDefinition());
288         return Either.left(consumer);
289     }
290
291     private void checkFieldsForOverrideAttempt(ConsumerDefinition consumer) {
292         if (consumer.getConsumerDetailsLastupdatedtime() != null) {
293             log.info("Consumer Details Last updated time cannot be defined by user. This field will be overridden by the application");
294         }
295         if (consumer.getConsumerLastAuthenticationTime() != null) {
296             log.info("Consumer Last Authentication time cannot be defined by user. This field will be overridden by the application");
297         }
298         if (consumer.getLastModfierAtuid() != null) {
299             log.info("Consumer Last Modifier USER_ID cannot be defined by user. This field will be overridden by the application");
300         }
301     }
302 }