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