login and Certman AAF Integration 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  * 
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                         
165                         //                      if("true".equalsIgnoreCase(remotecentralizedsystemaccess)){
166                         //                              importFromExternalAuth();
167                         //                      }                       
168                 } catch (Exception e) {
169                         logger.error(EELFLoggerDelegate.errorLogger, "init failed", e);
170                 }
171         }
172
173         /**
174          * Does a sync on functions, roles and role functions based on namespace 
175          * for all the centralized applications between AAF and ONAP, updates
176          * fn_user and fn_user_role with user information from AAF.
177          * 
178          * This is being handled in AAF directly, so it has been deprecated
179          * 
180          */
181         @Deprecated
182         private void importFromExternalAuth() throws Exception {
183                 JSONArray aafAppRoles = new JSONArray();
184                 JSONArray aafUserList = new JSONArray();
185                 List<EPApp> appList;
186                 //to get all centralized apps           
187                 List<EPApp> centralizedAppList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null);         
188                 if(centralizedAppList != null && !centralizedAppList.isEmpty()){
189                         for(int i = 0; i < centralizedAppList.size(); i++){
190                                 //syncRoles(does a sync on functions, roles and role functions)
191                                 externalAccessRolesService.syncApplicationRolesWithEcompDB(centralizedAppList.get(i));
192                                 //retrieve roles based on NS
193                                 aafAppRoles = externalAccessRolesService.getAppRolesJSONFromExtAuthSystem(centralizedAppList.get(i));
194                                 if(aafAppRoles != null && aafAppRoles.length() > 0){
195                                         for(int j = 0; j < aafAppRoles.length(); j++){
196                                                 ObjectMapper mapper = new ObjectMapper();
197                                                 String name = aafAppRoles.getJSONObject(j).getString("name");
198                                                 String desc = aafAppRoles.getJSONObject(j).getString("description");
199                                                 ExternalRoleDescription externalRoleDescription = mapper.readValue(desc, ExternalRoleDescription.class);
200                                                 aafUserList = externalAccessRolesService.getAllUsersByRole(name);       
201                                                 if(aafUserList != null && aafUserList.length() > 0){
202                                                         for(int k = 0; k < aafUserList.length(); k++){
203                                                                 EPUser user = null;
204                                                                 List<EPUser> usersList = null;                                                          
205                                                                 List<EPUserApp> userRolesList = new ArrayList<>();
206                                                                 JSONObject userRole = (JSONObject) aafUserList.get(k);
207                                                                 Gson gson = new Gson();
208                                                                 ExternalAuthUserRole userRoleObj = gson.fromJson(userRole.toString(), ExternalAuthUserRole.class);
209                                                                 if(userRoleObj.getUser() != null){
210                                                                         userRoleObj.setUser(userRoleObj.getUser().substring(0, userRoleObj.getUser().indexOf("@")));
211                                                                 }                                                       
212                                                                 //for each role and user in that role, check if user exists in fn_user. If not, add 
213                                                                 Map<String, String> orgUserId = new HashMap<>();
214                                                                 orgUserId.put("orgUserIdValue", userRoleObj.getUser());
215                                                                 usersList = dataAccessService.executeNamedQuery("epUserAppId", orgUserId, null);
216                                                                 if(usersList != null && !usersList.isEmpty()){
217                                                                         user = usersList.get(0);
218                                                                 }                                                       
219                                                                 if(user == null){
220                                                                         // add user to fn_user(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         @Override
236         public String[] tileDefinitions() {
237                 return super.tileDefinitions();
238         }
239
240         public List<String> addTileDefinitions() {
241                 List<String> definitions = new ArrayList<>();
242                 definitions.add("/WEB-INF/defs/definitions.xml");
243                 return definitions;
244         }
245
246         @Bean
247         public AbstractCacheManager cacheManager() {
248                 return new CacheManager();
249         }
250
251         @Bean
252         public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
253                 return new SessionTimeoutInterceptor();
254         }
255
256         @Bean
257         public PortalResourceInterceptor portalResourceInterceptor() {
258                 return new PortalResourceInterceptor();
259         }
260
261         @Bean
262         public EPLoginService eploginService() {
263                 return new EPLoginServiceImpl();
264         }
265
266         @Bean
267         public org.onap.portalsdk.core.auth.LoginStrategy coreLoginStrategy() {
268                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
269                         return new OpenIdConnectLoginStrategy();
270                 else
271                         return new SimpleLoginStrategy();
272         }
273
274         @Bean
275         public LoginStrategy loginStrategy() {
276
277                 if ("OIDC".equalsIgnoreCase(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim()))
278                         return new OpenIdConnectLoginStrategy();
279                 else
280                         return new SimpleLoginStrategy();
281         }
282
283         public FnMenuService fnMenuService() {
284                 return new FnMenuServiceImpl();
285         }
286
287         @Override
288         public void addInterceptors(InterceptorRegistry registry) {
289                 registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck",
290                                 "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/",
291                                 "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external",
292                                 "/login_external.htm*", "login", "/login.htm*", "/auxapi/**/*", "/context/*", "/api*",
293                                 "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm");
294
295                 registry.addInterceptor(portalResourceInterceptor());
296
297         }
298
299         /**
300          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
301          * populates it with triggers.
302          *
303          * @return New instance of {@link SchedulerFactoryBean}
304          */
305
306 /*      @Bean
307         public EPUebHelper epUebHelper() {
308                 return new EPUebHelper();
309         }
310 */
311         @Bean
312         public HealthMonitor healthMonitor() {
313                 return new HealthMonitor();
314         }
315
316         /**
317          * Creates and returns a new instance of a {@link MainUebHandler}.
318          * 
319          * @return New instance of {@link MainUebHandler}.
320          */
321         @Bean
322         public MainUebHandler mainUebHandler() {
323                 return new MainUebHandler();
324         }
325
326         /**
327          * Creates and returns a new instance of a {@link InitUebHandler}.
328          * 
329          * @return New instance of {@link InitUebHandler}.
330          */
331         @Bean
332         public InitUebHandler initUebHandler() {
333                 return new InitUebHandler();
334         }
335
336         /**
337          * Creates and returns a new instance of a {@link WidgetNotificationHandler}
338          * .
339          * 
340          * @return New instance of {@link WidgetNotificationHandler}.
341          */
342         @Bean
343         public WidgetNotificationHandler widgetNotificationHandler() {
344                 return new WidgetNotificationHandler();
345         }
346
347         /**
348          * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
349          * 
350          * @return New instance of {@link FunctionalMenuHandler}.
351          */
352         @Bean
353         public FunctionalMenuHandler functionalMenuHandler() {
354                 return new FunctionalMenuHandler();
355         }
356
357         /**
358          * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
359          * populates it with triggers.
360          *
361          * @return New instance of {@link SchedulerFactoryBean}
362          * @throws Exception if dataSource fails
363          */
364         // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
365         @Bean // ANNOTATION COMMENTED OUT
366         public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
367                 SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
368                 scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
369                 scheduler.setDataSource(dataSource());
370                 scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
371                 scheduler.setSchedulerName(getScheduleName());
372                 return scheduler;
373         }
374
375         protected String getScheduleName() {
376                 final String CRON_SITE_NAME = "cron_site_name";
377                 String cronSiteVal = "Default";
378                 try {
379                         cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
380                 } catch (Exception e) {
381                         logger.error(EELFLoggerDelegate.errorLogger, "getScheduleName failed", e);
382                         logger.warn(EELFLoggerDelegate.errorLogger,
383                                         "Cron site name not added in property file, using Default value");
384                 }
385
386                 String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
387
388                 SimpleDateFormat dateFormat = new SimpleDateFormat();
389                 dateFormat.applyPattern("YYYYMMdd");
390                 String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
391
392                 return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
393         }
394
395         /**
396          * Sets the scheduler registry adapter.
397          *
398          * @param schedulerRegistryAdapter
399          *            Scheduler registry adapter
400          */
401         @Autowired
402         public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
403                 this.schedulerRegistryAdapter = schedulerRegistryAdapter;
404         }
405
406 }