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