update to use latest portal sdk
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / security / portal / PortalRestAPICentralServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sparky.security.portal;
22
23 import java.io.IOException;
24 import java.text.MessageFormat;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.stream.Collectors;
31
32 import javax.servlet.http.HttpServletRequest;
33
34 import org.onap.aai.sparky.security.EcompSso;
35 import org.onap.aai.sparky.security.portal.config.PortalAuthenticationConfig;
36 import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestAPIService;
37 import org.onap.portalsdk.core.onboarding.crossapi.IPortalRestCentralService;
38 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
39 import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient;
40 import org.onap.portalsdk.core.restful.domain.EcompRole;
41 import org.onap.portalsdk.core.restful.domain.EcompUser;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import com.fasterxml.jackson.databind.type.TypeFactory;
47
48 public class PortalRestAPICentralServiceImpl
49     implements IPortalRestCentralService, IPortalRestAPIService {
50
51   private static final Logger LOG = LoggerFactory.getLogger(PortalRestAPICentralServiceImpl.class);
52   public static final String API_REDIRECT_VERSION = "/v4";
53   private static final String ERROR_MESSAGE = "Failed to {0} user [loginId:{1}]";
54   private List<EcompUser> usersList;
55   private final ObjectMapper mapper;
56
57
58   /**
59    * Initialize user list array.
60    */
61   public PortalRestAPICentralServiceImpl() {
62     usersList = new ArrayList<>();
63     mapper = new ObjectMapper();
64   }
65
66
67   @Override
68   public Map<String, String> getAppCredentials() throws PortalAPIException {
69     PortalAuthenticationConfig config = PortalAuthenticationConfig.getInstance();
70     Map<String, String> appCredentialsMap = new HashMap<>();
71     String appUserName = config.getUsername();
72     String appPassword = config.getPassword();
73
74     appCredentialsMap.put("username", appUserName);
75     appCredentialsMap.put("password", appPassword);
76     return appCredentialsMap;
77   }
78
79   @Override
80   public void pushUser(EcompUser user) throws PortalAPIException {
81     // Do we really need to save the users? Can this method be just empty and not throw an
82     // exception?
83     LOG.debug("Push user [loginId:" + user.getLoginId() + "]");
84     if (usersList.size() == 0) {
85       usersList.add(user);
86     } else {
87       for (EcompUser existingUser : this.usersList) {
88         if (existingUser.getLoginId().equals(user.getLoginId())) {
89           String message =
90               getMessage(ERROR_MESSAGE, "push", user.getLoginId()) + ", user is already stored";
91           LOG.error(message);
92           throw new PortalAPIException(message);
93         }
94         usersList.add(user);
95
96       }
97     }
98   }
99
100   @Override
101   public void editUser(String loginId, EcompUser user) throws PortalAPIException {
102     // Do we really need to save the users? Can this method be just empty and not throw an
103     // exception?
104     LOG.debug("Edit user [loginId:" + loginId + "]");
105     boolean isRemoved = false;
106     if (usersList.size() == 0) {
107       usersList.add(user);
108     } else {
109       for (EcompUser existingUser : this.usersList) {
110         if (existingUser.getLoginId().equals(loginId)) {
111           isRemoved = usersList.remove(existingUser);
112         }
113         if (isRemoved) {
114           usersList.add(user);
115         }
116
117       }
118     }
119   }
120
121   @Override
122   public String getUserId(HttpServletRequest request) throws PortalAPIException {
123     return EcompSso.validateEcompSso(request);
124   }
125
126   private String getMessage(String message, Object... args) {
127     MessageFormat formatter = new MessageFormat("");
128     formatter.applyPattern(message);
129     return formatter.format(args);
130   }
131
132   public List<EcompUser> getUsersList() {
133     return usersList;
134   }
135
136
137   public void setUsersList(List<EcompUser> usersList) {
138     this.usersList = usersList;
139   }
140
141
142   @Override
143   public EcompUser getUser(String loginId) throws PortalAPIException {
144     EcompUser user = new EcompUser();
145     String responseString = null;
146     try {
147       responseString = RestWebServiceClient.getInstance().getPortalContent(
148           API_REDIRECT_VERSION + "/user/" + loginId, null, null, null,
149           getCredentials().get("username"), getCredentials().get("password"), true);
150       LOG.debug("responseString is: " + responseString);
151       user = mapper.readValue(responseString, EcompUser.class);
152
153     } catch (IOException e) {
154       String response = "PortalRestAPICentralServiceImpl.getUser failed";
155       LOG.error(response, e);
156       throw new PortalAPIException(response, e);
157     }
158     return user;
159   }
160
161
162   @Override
163   public List<EcompUser> getUsers() throws PortalAPIException {
164     List<EcompUser> usersList = new ArrayList<>();
165     String responseString = null;
166     try {
167       responseString =
168           RestWebServiceClient.getInstance().getPortalContent(API_REDIRECT_VERSION + "/users", null,
169               null, null, getCredentials().get("username"), getCredentials().get("password"), true);
170       LOG.debug("responseString is: " + responseString);
171       usersList = mapper.readValue(responseString,
172           TypeFactory.defaultInstance().constructCollectionType(List.class, EcompUser.class));
173
174     } catch (IOException e) {
175       String response = "PortalRestAPICentralServiceImpl.getUsers failed";
176       LOG.error(response, e);
177       throw new PortalAPIException(response, e);
178     }
179     return usersList;
180   }
181
182
183   @Override
184   public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
185     List<EcompRole> rolesList = new ArrayList<>();
186     String responseString = null;
187     try {
188       responseString = RestWebServiceClient.getInstance().getPortalContent(
189           API_REDIRECT_VERSION + "/roles", requestedLoginId, null, null,
190           getCredentials().get("username"), getCredentials().get("password"), true);
191       LOG.debug("responseString is: " + responseString);
192       rolesList = mapper.readValue(responseString,
193           TypeFactory.defaultInstance().constructCollectionType(List.class, EcompRole.class));
194
195     } catch (IOException e) {
196       String response = "PortalRestAPICentralServiceImpl.getRoles failed";
197       LOG.error(response, e);
198       throw new PortalAPIException(response, e);
199     }
200     return rolesList;
201   }
202
203
204   @Override
205   public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
206     throw new PortalAPIException("Please use Portal for Role Management");
207   }
208
209
210   @Override
211   public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
212     List<EcompRole> userRoles = new ArrayList<>();
213     EcompUser user = new EcompUser();
214     String responseString = null;
215     try {
216       responseString = RestWebServiceClient.getInstance().getPortalContent(
217           API_REDIRECT_VERSION + "/user/" + loginId, null, null, null,
218           getCredentials().get("username"), getCredentials().get("password"), true);
219       LOG.debug("responseString is: " + responseString);
220       user = mapper.readValue(responseString, EcompUser.class);
221       Set roles = user.getRoles();
222       userRoles = (List<EcompRole>) roles.stream().collect(Collectors.toList());
223
224     } catch (IOException e) {
225       String response = "PortalRestAPICentralServiceImpl.getUserRoles failed";
226       LOG.error(response, e);
227       throw new PortalAPIException(response, e);
228     }
229     return userRoles;
230   }
231
232
233   @Override
234   public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
235     LOG.debug("Authentication request");
236     PortalAuthenticationConfig config = PortalAuthenticationConfig.getInstance();
237     String restUsername = request.getHeader(PortalAuthenticationConfig.PROP_USERNAME);
238     String restPassword = request.getHeader(PortalAuthenticationConfig.PROP_PASSWORD);
239     return restUsername != null && restPassword != null && restUsername.equals(config.getUsername())
240         && restPassword.equals(config.getPassword());
241   }
242
243
244   @Override
245   public Map<String, String> getCredentials() throws PortalAPIException {
246     PortalAuthenticationConfig config = PortalAuthenticationConfig.getInstance();
247     Map<String, String> credentialsMap = new HashMap<>();
248     String appUserName = config.getUsername();
249     String appPassword = config.getPassword();
250
251     credentialsMap.put("username", appUserName);
252     credentialsMap.put("password", appPassword);
253     return credentialsMap;
254   }
255
256 }