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