d2ccfc2e62c64d0f5e7dc8641bc1ebe192abd166
[portal/sdk.git] /
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
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.portalsdk.external.authorization.service;
39
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47
48 import javax.servlet.http.HttpServletRequest;
49
50 import org.onap.portalsdk.core.command.LoginBean;
51 import org.onap.portalsdk.core.domain.Role;
52 import org.onap.portalsdk.core.domain.User;
53 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
54 import org.onap.portalsdk.core.menu.MenuBuilder;
55 import org.onap.portalsdk.core.service.DataAccessService;
56 import org.onap.portalsdk.core.service.LoginServiceCentralizedImpl;
57 import org.onap.portalsdk.core.util.SystemProperties;
58 import org.onap.portalsdk.core.web.support.AppUtils;
59 import org.onap.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.stereotype.Service;
62
63 @Service("loginExternalAuthService")
64 public class LoginExternalAuthServiceImpl implements LoginExternalAuthService {
65
66         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginServiceCentralizedImpl.class);
67
68         @Autowired
69         private DataAccessService dataAccessService;
70
71         @Autowired
72         private UserApiService userApiService;
73
74         @Override
75         public LoginBean findUser(LoginBean bean, String menuPropertiesFilename,
76                         @SuppressWarnings("rawtypes") Map additionalParams, HttpServletRequest request) throws Exception {
77                 return findUser(bean, menuPropertiesFilename, additionalParams, true, request);
78         }
79
80         @Override
81         @SuppressWarnings("rawtypes")
82         public LoginBean findUser(LoginBean bean, String menuPropertiesFilename, Map additionalParams,
83                         boolean matchPassword, HttpServletRequest request) throws  Exception {
84
85                 User user;
86                 if (bean.getUserid() != null) {
87                         user = findUser(bean, request);
88                 } else {
89                         if (matchPassword)
90                                 user = findUser(bean.getLoginId(), bean.getLoginPwd());
91                         else
92                                 user = findUserWithoutPwd(bean.getLoginId());
93                 }
94
95                 if (user != null) {
96                         if (AppUtils.isApplicationLocked()
97                                         && !UserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
98                                 bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
99                         }
100
101                         // raise an error if the user is inactive
102                         if (!user.getActive()) {
103                                 bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
104                         }
105
106                         if (!userHasActiveRoles(user)) {
107                                 bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
108                         }
109                         // only login the user if no errors have occurred
110                         if (bean.getLoginErrorMessage() == null) {
111
112                                 // this will be a snapshot of the user's information as
113                                 // retrieved from the database
114                                 User userCopy = null;
115                                 try {
116                                         userCopy = (User) user.clone();
117                                 } catch (CloneNotSupportedException ex) {
118                                         // Never happens
119                                         logger.error(EELFLoggerDelegate.errorLogger, "findUser failed", ex);
120                                 }
121
122                                 User appuser = findUserWithoutPwd(user.getLoginId());
123
124                                 if (appuser == null && userHasRoleFunctions(user)) {
125                                         createUserIfNecessary(user);
126                                 } else {
127                                         appuser.setLastLoginDate(new Date());
128
129                                         // update the last logged in date for the user
130                                         dataAccessService.saveDomainObject(appuser, additionalParams);
131                                 }
132                                 // update the audit log of the user
133                                 // Check for the client device type and set log attributes
134                                 // appropriately
135
136                                 // save the above changes to the User and their audit trail
137
138                                 // create the application menu based on the user's privileges
139
140                                 Set appMenu = getMenuBuilder().getMenu(
141                                                 SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
142                                 bean.setMenu(appMenu != null ? appMenu : new HashSet());
143                                 Set businessDirectMenu = getMenuBuilder().getMenu(
144                                                 SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),
145                                                 dataAccessService);
146                                 bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
147
148                                 bean.setUser(userCopy);
149                         }
150                 }
151
152                 return bean;
153         }
154
155         private void createUserIfNecessary(User user) {
156                 logger.debug(EELFLoggerDelegate.debugLogger, "createUser: " + user.getOrgUserId());
157                 User user1 = new User();
158                 user1.setEmail(user.getEmail());
159                 user1.setEmail(user.getEmail());
160                 user1.setFirstName(user.getFirstName());
161                 user1.setHrid(user.getHrid());
162                 user1.setJobTitle(user.getJobTitle());
163                 user1.setLastName(user.getLastName());
164                 user1.setLoginId(user.getLoginId());
165                 user1.setOrgManagerUserId(user.getOrgManagerUserId());
166                 user1.setMiddleInitial(user.getMiddleInitial());
167                 user1.setOrgCode(user.getOrgCode());
168                 user1.setOrgId(user.getOrgId());
169                 user1.setPhone(user.getPhone());
170                 user1.setOrgUserId(user.getOrgUserId());
171                 user1.setActive(user.getActive());
172                 user1.setLastLoginDate(new Date());
173
174                 try {
175                         dataAccessService.saveDomainObject(user1, null);
176                         logger.debug(EELFLoggerDelegate.debugLogger, "createdUser Successfully: " + user.getOrgUserId());
177                 } catch (Exception ex) {
178                         logger.error(EELFLoggerDelegate.errorLogger, "createUserIfNecessary failed", ex);
179                 }
180
181         }
182
183         private boolean userHasActiveRoles(User user) {
184                 boolean hasActiveRole = false;
185                 @SuppressWarnings("rawtypes")
186                 Iterator roles = user.getRoles().iterator();
187                 while (roles.hasNext()) {
188                         Role role = (Role) roles.next();
189                         if (role.getActive()) {
190                                 hasActiveRole = true;
191                                 break;
192                         }
193                 }
194                 return hasActiveRole;
195         }
196
197         private boolean userHasRoleFunctions(User user) {
198                 boolean hasRoleFunctions = false;
199                 @SuppressWarnings("rawtypes")
200                 Iterator roles = user.getRoles().iterator();
201                 while (roles.hasNext()) {
202                         Role role = (Role) roles.next();
203                         if (role.getActive() && role.getRoleFunctions() != null && !role.getRoleFunctions().isEmpty()) {
204                                 hasRoleFunctions = true;
205                                 break;
206                         }
207                 }
208                 return hasRoleFunctions;
209         }
210
211         private User findUser(LoginBean bean, HttpServletRequest request) throws Exception {
212                 User user =  userApiService.getUser(bean.getUserid(), request);
213                 user.setId(getUserIdByOrgUserId(user.getOrgUserId()));
214                 user.setLoginId(bean.getUserid());
215                 logger.debug(EELFLoggerDelegate.debugLogger, "findUser: Returning final user roles and permissions", user.toString());
216                 return user;
217         }
218         
219         private Long getUserIdByOrgUserId(String orgUserId) {
220                 Map<String, String> params = new HashMap<>();
221                 params.put("orgUserId", orgUserId);
222                 @SuppressWarnings("rawtypes")
223                 List list = dataAccessService.executeNamedQuery("getUserIdByorgUserId", params, null);
224                 Long userId = null;
225                 if (list != null && !list.isEmpty())
226                         userId = (Long) list.get(0);
227                 return userId;
228         }
229
230         @SuppressWarnings("rawtypes")
231         private User findUser(String loginId, String password) {
232                 Map<String, String> params = new HashMap<>();
233                 params.put("login_id", loginId);
234                 params.put("login_pwd", password);
235                 List list = dataAccessService.executeNamedQuery("getUserByLoginIdLoginPwd", params, new HashMap());
236                 return (list == null || list.isEmpty()) ? null : (User) list.get(0);
237         }
238
239         @SuppressWarnings("rawtypes")
240         @Override
241         public User findUserWithoutPwd(String loginId) {
242                 Map<String, String> params = new HashMap<>();
243                 params.put("org_user_id", loginId);
244                 List list = dataAccessService.executeNamedQuery("getUserByOrgUserId", params, new HashMap());
245                 return (list == null || list.isEmpty()) ? null : (User) list.get(0);
246         }
247
248         private MenuBuilder getMenuBuilder() {
249                 return new MenuBuilder();
250         }
251
252 }