Security/ Package Name changes
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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.portal.domain.EPApp;
65 import org.onap.portalapp.portal.domain.EPUser;
66 import org.onap.portalapp.portal.domain.EPUserApp;
67 import org.onap.portalapp.portal.interceptor.PortalResourceInterceptor;
68 import org.onap.portalapp.portal.interceptor.SessionTimeoutInterceptor;
69 import org.onap.portalapp.portal.listener.HealthMonitor;
70 import org.onap.portalapp.portal.service.EPLoginService;
71 import org.onap.portalapp.portal.service.EPLoginServiceImpl;
72 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
73 import org.onap.portalapp.portal.service.UserRolesService;
74 import org.onap.portalapp.portal.transport.ExternalAuthUserRole;
75 import org.onap.portalapp.portal.transport.ExternalRoleDescription;
76 import org.onap.portalapp.portal.ueb.EPUebHelper;
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.Profile;
104 import org.springframework.scheduling.annotation.EnableAsync;
105 import org.springframework.scheduling.annotation.EnableScheduling;
106 import org.springframework.scheduling.quartz.SchedulerFactoryBean;
107 import org.springframework.web.servlet.ViewResolver;
108 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
109 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
110 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
111
112 import com.fasterxml.jackson.databind.ObjectMapper;
113 import com.google.gson.Gson;
114
115 @Configuration
116 @EnableWebMvc
117 @ComponentScan(basePackages = {"org.onap", "org.openecomp" }, excludeFilters = {
118                 @Filter(value = { LogoutController.class, SDKLoginController.class}, type = FilterType.ASSIGNABLE_TYPE) })
119 @Profile("src")
120 @EnableAsync
121 @EnableScheduling
122
123 public class ExternalAppConfig extends AppConfig implements Configurable {
124
125         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
126
127         @Autowired
128         private DataAccessService dataAccessService;
129         
130         @Autowired
131         private UserRolesService userRolesService;
132         
133         @Autowired
134         private ExternalAccessRolesService externalAccessRolesService;
135
136         private RegistryAdapter schedulerRegistryAdapter;
137
138         String UEB_APP_KEY = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY); 
139         
140         public ViewResolver viewResolver() {
141                 return super.viewResolver();
142         }
143
144         @Override
145         public void addResourceHandlers(ResourceHandlerRegistry registry) {
146                 registry.addResourceHandler("/app/fusion/**").addResourceLocations("/app/fusion/");
147                 registry.addResourceHandler("/static/**").addResourceLocations("/static/");
148                 registry.addResourceHandler("/images/**").addResourceLocations("/images/");
149                 registry.addResourceHandler("/**").addResourceLocations("/public/");
150         }
151
152         @PostConstruct
153         private void init() {
154                 String remotecentralizedsystemaccess = SystemProperties.getProperty(EPCommonSystemProperties.REMOTE_CENTRALIZED_SYSTEM_ACCESS);
155                 try {
156                         // Loading defaults
157                         MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
158                         MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
159                         MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
160                         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
161                         MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
162                         MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
163                         if(remotecentralizedsystemaccess.equalsIgnoreCase("true")){
164                                 importFromExternalAuth();
165                         }                       
166                 } catch (Exception e) {
167                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
168                 }
169         }
170         
171         /**
172          * Does a sync on functions, roles and role functions based on namespace 
173          * for all the centralized applications between AAF and ONAP, updates
174          * fn_user and fn_user_role with user information from AAF.
175          * 
176          */
177         private void importFromExternalAuth() throws Exception {
178                 JSONArray aafAppRoles = new JSONArray();
179                 JSONArray aafUserList = new JSONArray();
180                 List<EPApp> appList;
181                 //to get all centralized apps           
182                 List<EPApp> centralizedAppList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);         
183                 if(centralizedAppList != null && centralizedAppList.size() > 0){
184                         for(int i = 0; i < centralizedAppList.size(); i++){
185                                 //syncRoles(does a sync on functions, roles and role functions)
186                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(centralizedAppList.get(i));
187                                 //retrieve roles based on NS
188                                 aafAppRoles = externalAccessRolesService.getAppRolesJSONFromExtAuthSystem(centralizedAppList.get(i));
189                                 if(aafAppRoles != null && aafAppRoles.length() > 0){
190                                         for(int j = 0; j < aafAppRoles.length(); j++){
191                                                 ObjectMapper mapper = new ObjectMapper();
192                                                 String name = aafAppRoles.getJSONObject(j).getString("name");
193                                                 String desc = aafAppRoles.getJSONObject(j).getString("description");
194                                                 ExternalRoleDescription externalRoleDescription = mapper.readValue(desc, ExternalRoleDescription.class);
195                                                 aafUserList = externalAccessRolesService.getAllUsersByRole(name);       
196                                                 if(aafUserList != null && aafUserList.length() > 0){
197                                                         for(int k = 0; k < aafUserList.length(); k++){
198                                                                 EPUser user = null;
199                                                                 List<EPUser> usersList = null;                                                          
200                                                                 List<EPUserApp> userRolesList = new ArrayList<EPUserApp>();
201                                                                 JSONObject userRole = (JSONObject) aafUserList.get(k);
202                                                                 Gson gson = new Gson();
203                                                                 ExternalAuthUserRole userRoleObj = gson.fromJson(userRole.toString(), ExternalAuthUserRole.class);
204                                                                 if(userRoleObj.getUser() != null){
205                                                                         userRoleObj.setUser(userRoleObj.getUser().substring(0, userRoleObj.getUser().indexOf("@")));
206                                                                 }                                                       
207                                                                 //for each role and user in that role, check if user exists in fn_user. If not, add 
208                                                                 Map<String, String> orgUserId = new HashMap<>();
209                                                                 orgUserId.put("orgUserIdValue", userRoleObj.getUser());
210                                                                 usersList = dataAccessService.executeNamedQuery("epUserAppId", orgUserId, null);
211                                                                 if(usersList != null && usersList.size() > 0){
212                                                                         user = usersList.get(0);
213                                                                 }                                                       
214                                                                 if(user == null){
215                                                                         // add user to fn_user(needs to be revisited after getting user info from AAF PORTAL-172)                                                               
216                                                                 }
217                                                                 //for each role and user in that role, check if user exists in fn_user_role. If not, add 
218                                                                 /*userRolesList = userRolesService.getUserRolesList(centralizedAppList.get(0).getId(), user.getId(), Long.valueOf(externalRoleDescription.getId()));
219                                                                 if(userRolesList == null || userRolesList.isEmpty()){                                                           
220                                                                         // add userRole to fn_user_role(needs to be revisited after getting user info from AAF PORTAL-172)
221                                                                 }*/
222                                                         }
223                                                 }
224                                                 
225                                         }
226                                 }
227                         }                       
228                 }
229         }
230                         
231         public DataAccessService dataAccessService() {
232                 return super.dataAccessService();
233         }
234
235         public String[] tileDefinitions() {
236                 return super.tileDefinitions();
237         }
238
239         public List<String> addTileDefinitions() {
240                 List<String> definitions = new ArrayList<String>();
241                 definitions.add("/WEB-INF/defs/definitions.xml");
242                 return definitions;
243         }
244
245         @Bean
246         public AbstractCacheManager cacheManager() {
247                 return new CacheManager();
248         }
249
250         @Bean
251         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
252                 return new SessionTimeoutInterceptor();
253         }
254
255         @Bean
256         public PortalResourceInterceptor portalResourceInterceptor() {
257                 return new PortalResourceInterceptor();
258         }
259
260         @Bean
261         public EPLoginService eploginService() {
262                 return new EPLoginServiceImpl();
263         }
264
265         @Bean
266         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
267                 if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC"))
268                         return new OpenIdConnectLoginStrategy();
269                 else
270                         return new SimpleLoginStrategy();
271         }
272
273         @Bean
274         public LoginStrategy loginStrategy() {
275
276                 if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC"))
277                         return new OpenIdConnectLoginStrategy();
278                 else
279                         return new SimpleLoginStrategy();
280         }
281
282         public FnMenuService fnMenuService() {
283                 return new FnMenuServiceImpl();
284         }
285
286         @Override
287         public void addInterceptors(InterceptorRegistry registry) {
288                 // registry.addInterceptor(new
289                 // StaticResourcesInterceptor()).addPathPatterns("/index.htm",
290                 // "/applicationsHome", "/widgetsHome", "/admins", "/users",
291                 // "/applications", "/widgets");
292                 // Excludes login/logout pages and REST endpoints used by other
293                 // application servers.
294
295                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
296                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
297                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
298                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*",
299                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
300
301                 registry.addInterceptor(portalResourceInterceptor());
302
303         }
304
305         /**
306          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
307          * populates it with triggers.
308          *
309          * @return New instance of {@link SchedulerFactoryBean}
310          */
311
312         @Bean
313         public EPUebHelper epUebHelper() {
314                 return new EPUebHelper();
315         }
316
317         @Bean
318         public HealthMonitor healthMonitor() {
319                 return new HealthMonitor();
320         }
321
322         /**
323          * Creates and returns a new instance of a {@link MainUebHandler}.
324          * 
325          * @return New instance of {@link MainUebHandler}.
326          */
327         @Bean
328         public MainUebHandler mainUebHandler() {
329                 return new MainUebHandler();
330         }
331
332         /**
333          * Creates and returns a new instance of a {@link InitUebHandler}.
334          * 
335          * @return New instance of {@link InitUebHandler}.
336          */
337         @Bean
338         public InitUebHandler initUebHandler() {
339                 return new InitUebHandler();
340         }
341
342         /**
343          * Creates and returns a new instance of a {@link WidgetNotificationHandler}
344          * .
345          * 
346          * @return New instance of {@link WidgetNotificationHandler}.
347          */
348         @Bean
349         public WidgetNotificationHandler widgetNotificationHandler() {
350                 return new WidgetNotificationHandler();
351         }
352
353         /**
354          * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
355          * 
356          * @return New instance of {@link FunctionalMenuHandler}.
357          */
358         @Bean
359         public FunctionalMenuHandler functionalMenuHandler() {
360                 return new FunctionalMenuHandler();
361         }
362
363         /**
364          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
365          * populates it with triggers.
366          *
367          * @return New instance of {@link SchedulerFactoryBean}
368          * @throws Exception if dataSource fails
369          */
370         // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
371         @Bean // ANNOTATION COMMENTED OUT
372         public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
373                 SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
374                 scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
375                 scheduler.setDataSource(dataSource());
376                 scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
377                 scheduler.setSchedulerName(getScheduleName());
378                 return scheduler;
379         }
380
381         protected String getScheduleName() {
382                 final String CRON_SITE_NAME = "cron_site_name";
383                 String cronSiteVal = "Default";
384                 try {
385                         cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
386                 } catch (Exception e) {
387                         logger.error(EELFLoggerDelegate.errorLogger, "getScheduleName failed", e);
388                         logger.warn(EELFLoggerDelegate.errorLogger,
389                                         "Cron site name not added in property file, using Default value");
390                 }
391
392                 String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
393
394                 SimpleDateFormat dateFormat = new SimpleDateFormat();
395                 dateFormat.applyPattern("YYYYMMdd");
396                 String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
397
398                 return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
399         }
400
401         /**
402          * Sets the scheduler registry adapter.
403          *
404          * @param schedulerRegistryAdapter
405          *            Scheduler registry adapter
406          */
407         @Autowired
408         public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
409                 this.schedulerRegistryAdapter = schedulerRegistryAdapter;
410         }
411
412 }