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