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