862bf399ba65bc79651d4d24608224874ff2f986
[portal.git] / ecomp-portal-BE-os / src / main / java / org / onap / portalapp / conf / ExternalAppConfig.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright © 2018 IBM.
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  * 
39  */
40 package org.onap.portalapp.conf;
41
42 import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
43 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
44 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
45 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
46 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
47 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
48
49 import java.net.InetAddress;
50 import java.text.SimpleDateFormat;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.HashMap;
54 import java.util.List;
55 import java.util.Map;
56
57 import javax.annotation.PostConstruct;
58
59 import org.json.JSONArray;
60 import org.json.JSONObject;
61 import org.onap.portalapp.authentication.LoginStrategy;
62 import org.onap.portalapp.authentication.OpenIdConnectLoginStrategy;
63 import org.onap.portalapp.authentication.SimpleLoginStrategy;
64 import org.onap.portalapp.controller.core.LogoutController;
65 import org.onap.portalapp.controller.core.SDKLoginController;
66 import org.onap.portalapp.music.conf.MusicSessionConfig;
67 import org.onap.portalapp.portal.domain.EPApp;
68 import org.onap.portalapp.portal.domain.EPUser;
69 import org.onap.portalapp.portal.domain.EPUserApp;
70 import org.onap.portalapp.portal.interceptor.PortalResourceInterceptor;
71 import org.onap.portalapp.portal.interceptor.SessionTimeoutInterceptor;
72 import org.onap.portalapp.portal.listener.HealthMonitor;
73 import org.onap.portalapp.portal.service.EPLoginService;
74 import org.onap.portalapp.portal.service.EPLoginServiceImpl;
75 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
76 import org.onap.portalapp.portal.service.UserRolesService;
77 import org.onap.portalapp.portal.transport.ExternalAuthUserRole;
78 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
79 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
80 import org.onap.portalapp.portal.utils.EPSystemProperties;
81 import org.onap.portalapp.scheduler.RegistryAdapter;
82 import org.onap.portalapp.uebhandler.FunctionalMenuHandler;
83 import org.onap.portalapp.uebhandler.InitUebHandler;
84 import org.onap.portalapp.uebhandler.MainUebHandler;
85 import org.onap.portalapp.uebhandler.WidgetNotificationHandler;
86 import org.onap.portalsdk.core.conf.AppConfig;
87 import org.onap.portalsdk.core.conf.Configurable;
88 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
89 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
90 import org.onap.portalsdk.core.objectcache.AbstractCacheManager;
91 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
92 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
93 import org.onap.portalsdk.core.service.DataAccessService;
94 import org.onap.portalsdk.core.service.FnMenuService;
95 import org.onap.portalsdk.core.service.FnMenuServiceImpl;
96 import org.onap.portalsdk.core.util.CacheManager;
97 import org.onap.portalsdk.core.util.SystemProperties;
98 import org.slf4j.MDC;
99 import org.springframework.beans.factory.annotation.Autowired;
100 import org.springframework.context.annotation.Bean;
101 import org.springframework.context.annotation.ComponentScan;
102 import org.springframework.context.annotation.ComponentScan.Filter;
103 import org.springframework.context.annotation.Configuration;
104 import org.springframework.context.annotation.FilterType;
105 import org.springframework.context.annotation.Import;
106 import org.springframework.context.annotation.Profile;
107 import org.springframework.scheduling.annotation.EnableAsync;
108 import org.springframework.scheduling.annotation.EnableScheduling;
109 import org.springframework.scheduling.quartz.SchedulerFactoryBean;
110 import org.springframework.web.servlet.ViewResolver;
111 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
112 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
113 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
114
115 import com.fasterxml.jackson.databind.ObjectMapper;
116 import com.google.gson.Gson;
117
118 @Configuration
119 @EnableWebMvc
120 @ComponentScan(basePackages = {"org.onap"}, excludeFilters = {
121                 @Filter(value = { LogoutController.class, SDKLoginController.class}, type = FilterType.ASSIGNABLE_TYPE) })
122 @Profile("src")
123 @EnableAsync
124 @EnableScheduling
125 @Import({ MusicSessionConfig.class })
126 public class ExternalAppConfig extends AppConfig implements Configurable {
127
128         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
129
130         @Autowired
131         private DataAccessService dataAccessService;
132
133         @Autowired
134         private UserRolesService userRolesService;
135
136         @Autowired
137         private ExternalAccessRolesService externalAccessRolesService;
138
139         private RegistryAdapter schedulerRegistryAdapter;
140
141         String uebAppKey = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); 
142
143         public ViewResolver viewResolver() {
144                 return super.viewResolver();
145         }
146
147         @Override
148         public void addResourceHandlers(ResourceHandlerRegistry registry) {
149                 registry.addResourceHandler("/app/fusion/**").addResourceLocations("/app/fusion/");
150                 registry.addResourceHandler("/static/**").addResourceLocations("/static/");
151                 registry.addResourceHandler("/images/**").addResourceLocations("/images/");
152                 registry.addResourceHandler("/**").addResourceLocations("/public/");
153         }
154
155         @PostConstruct
156         private void init() {
157                 String remotecentralizedsystemaccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALIZED_SYSTEM_ACCESS);
158                 try {
159                         // Loading defaults
160                         MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
161                         MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
162                         MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
163                         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
164                         MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
165                         MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
166                         
167                         if("true".equalsIgnoreCase(remotecentralizedsystemaccess)){
168                                 importFromExternalAuth();
169                         }                       
170                 } catch (Exception e) {
171                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
172                 }
173         }
174
175         
176         private void importFromExternalAuth() throws Exception {
177                 JSONArray aafAppRoles = new JSONArray();
178                 JSONArray aafUserList = new JSONArray();
179                 List<EPApp> appList;
180                 //to get all centralized apps           
181                 List<EPApp> centralizedAppList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);         
182                 if(centralizedAppList != null && !centralizedAppList.isEmpty()){
183                         for(int i = 0; i < centralizedAppList.size(); i++){
184                                 //syncRoles(does a sync on functions, roles and role functions)
185                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(centralizedAppList.get(i));
186                                 //retrieve roles based on NS
187                                 aafAppRoles = externalAccessRolesService.getAppRolesJSONFromExtAuthSystem(centralizedAppList.get(i));
188                                 if(aafAppRoles != null && aafAppRoles.length() > 0){
189                                         for(int j = 0; j < aafAppRoles.length(); j++){
190                                                 ObjectMapper mapper = new ObjectMapper();
191                                                 String name = aafAppRoles.getJSONObject(j).getString("name");
192                                                 //String desc = aafAppRoles.getJSONObject(j).getString("description");
193                                                 //ExternalRoleDescription externalRoleDescription = mapper.readValue(desc, ExternalRoleDescription.class);
194                                                 aafUserList = externalAccessRolesService.getAllUsersByRole(name);       
195                                                 if(aafUserList != null && aafUserList.length() > 0){
196                                                         for(int k = 0; k < aafUserList.length(); k++){
197                                                                 EPUser user = null;
198                                                                 List<EPUser> usersList = null;                                                          
199                                                                 List<EPUserApp> userRolesList = new ArrayList<>();
200                                                                 JSONObject userRole = (JSONObject) aafUserList.get(k);
201                                                                 Gson gson = new Gson();
202                                                                 ExternalAuthUserRole userRoleObj = gson.fromJson(userRole.toString(), ExternalAuthUserRole.class);
203                                                                 if(userRoleObj.getUser() != null){
204                                                                         userRoleObj.setUser(userRoleObj.getUser().substring(0, userRoleObj.getUser().indexOf("@")));
205                                                                 }                                                       
206                                                                 //for each role and user in that role, check if user exists in fn_user. If not, add 
207                                                                 Map<String, String> orgUserId = new HashMap<>();
208                                                                 orgUserId.put("orgUserIdValue", userRoleObj.getUser());
209                                                                 usersList = dataAccessService.executeNamedQuery("epUserAppId", orgUserId, null);
210                                                                 if(usersList != null && !usersList.isEmpty()){
211                                                                         user = usersList.get(0);
212                                                                 }                                                       
213                                                                 if(user == null){
214                                                                         // add user to fn_user(needs to be revisited after getting user info from AAF PORTAL-172)                                                               
215                                                                 }
216                                                         }
217                                                 }
218
219                                         }
220                                 }
221                         }                       
222                 }
223         }
224
225         @Override
226         public String[] tileDefinitions() {
227                 return super.tileDefinitions();
228         }
229
230         public List<String> addTileDefinitions() {
231                 List<String> definitions = new ArrayList<>();
232                 definitions.add("/WEB-INF/defs/definitions.xml");
233                 return definitions;
234         }
235
236         @Bean
237         public AbstractCacheManager cacheManager() {
238                 return new CacheManager();
239         }
240
241         @Bean
242         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
243                 return new SessionTimeoutInterceptor();
244         }
245
246         @Bean
247         public PortalResourceInterceptor portalResourceInterceptor() {
248                 return new PortalResourceInterceptor();
249         }
250
251         @Bean
252         public EPLoginService eploginService() {
253                 return new EPLoginServiceImpl();
254         }
255
256         @Bean
257         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
258                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
259                         return new OpenIdConnectLoginStrategy();
260                 else
261                         return new SimpleLoginStrategy();
262         }
263
264         @Bean
265         public LoginStrategy loginStrategy() {
266
267                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
268                         return new OpenIdConnectLoginStrategy();
269                 else
270                         return new SimpleLoginStrategy();
271         }
272
273         public FnMenuService fnMenuService() {
274                 return new FnMenuServiceImpl();
275         }
276
277         @Override
278         public void addInterceptors(InterceptorRegistry registry) {
279                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
280                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
281                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
282                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/**/*", "/context/*", "/api*",
283                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
284
285                 registry.addInterceptor(portalResourceInterceptor());
286
287         }
288
289         /**
290          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
291          * populates it with triggers.
292          *
293          * @return New instance of {@link SchedulerFactoryBean}
294          */
295
296 /*      @Bean
297         public EPUebHelper epUebHelper() {
298                 return new EPUebHelper();
299         }
300 */
301         @Bean
302         public HealthMonitor healthMonitor() {
303                 return new HealthMonitor();
304         }
305
306         /**
307          * Creates and returns a new instance of a {@link MainUebHandler}.
308          * 
309          * @return New instance of {@link MainUebHandler}.
310          */
311         @Bean
312         public MainUebHandler mainUebHandler() {
313                 return new MainUebHandler();
314         }
315
316         /**
317          * Creates and returns a new instance of a {@link InitUebHandler}.
318          * 
319          * @return New instance of {@link InitUebHandler}.
320          */
321         @Bean
322         public InitUebHandler initUebHandler() {
323                 return new InitUebHandler();
324         }
325
326         /**
327          * Creates and returns a new instance of a {@link WidgetNotificationHandler}
328          * .
329          * 
330          * @return New instance of {@link WidgetNotificationHandler}.
331          */
332         @Bean
333         public WidgetNotificationHandler widgetNotificationHandler() {
334                 return new WidgetNotificationHandler();
335         }
336
337         /**
338          * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
339          * 
340          * @return New instance of {@link FunctionalMenuHandler}.
341          */
342         @Bean
343         public FunctionalMenuHandler functionalMenuHandler() {
344                 return new FunctionalMenuHandler();
345         }
346
347         /**
348          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
349          * populates it with triggers.
350          *
351          * @return New instance of {@link SchedulerFactoryBean}
352          * @throws Exception if dataSource fails
353          */
354         // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
355         @Bean // ANNOTATION COMMENTED OUT
356         public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
357                 SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
358                 scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
359                 scheduler.setDataSource(dataSource());
360                 scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
361                 scheduler.setSchedulerName(getScheduleName());
362                 return scheduler;
363         }
364
365         protected String getScheduleName() {
366                 final String CRON_SITE_NAME = "cron_site_name";
367                 String cronSiteVal = "Default";
368                 try {
369                         cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
370                 } catch (Exception e) {
371                         logger.error(EELFLoggerDelegate.errorLogger, "getScheduleName failed", e);
372                         logger.warn(EELFLoggerDelegate.errorLogger,
373                                         "Cron site name not added in property file, using Default value");
374                 }
375
376                 String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
377
378                 SimpleDateFormat dateFormat = new SimpleDateFormat();
379                 dateFormat.applyPattern("YYYYMMdd");
380                 String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
381
382                 return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
383         }
384
385         /**
386          * Sets the scheduler registry adapter.
387          *
388          * @param schedulerRegistryAdapter
389          *            Scheduler registry adapter
390          */
391         @Autowired
392         public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
393                 this.schedulerRegistryAdapter = schedulerRegistryAdapter;
394         }
395
396 }