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