d04509660069838801b30f241481b3e2fc64265c
[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.core.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                     if (appuser != null) {
130                         appuser.setLastLoginDate(new Date());
131                     }
132                                         // update the last logged in date for the user
133                                         dataAccessService.saveDomainObject(appuser, additionalParams);
134                                 }
135                                 // update the audit log of the user
136                                 // Check for the client device type and set log attributes
137                                 // appropriately
138
139                                 // save the above changes to the User and their audit trail
140
141                                 // create the application menu based on the user's privileges
142
143                                 Set appMenu = getMenuBuilder().getMenu(
144                                                 SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
145                                 bean.setMenu(appMenu != null ? appMenu : new HashSet());
146                                 Set businessDirectMenu = getMenuBuilder().getMenu(
147                                                 SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME),
148                                                 dataAccessService);
149                                 bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
150
151                                 bean.setUser(userCopy);
152                         }
153                 }
154
155                 return bean;
156         }
157
158         private void createUserIfNecessary(User user) {
159                 logger.debug(EELFLoggerDelegate.debugLogger, "createUser: " + user.getOrgUserId());
160                 User user1 = new User();
161                 user1.setEmail(user.getEmail());
162                 user1.setEmail(user.getEmail());
163                 user1.setFirstName(user.getFirstName());
164                 user1.setHrid(user.getHrid());
165                 user1.setJobTitle(user.getJobTitle());
166                 user1.setLastName(user.getLastName());
167                 user1.setLoginId(user.getLoginId());
168                 user1.setOrgManagerUserId(user.getOrgManagerUserId());
169                 user1.setMiddleInitial(user.getMiddleInitial());
170                 user1.setOrgCode(user.getOrgCode());
171                 user1.setOrgId(user.getOrgId());
172                 user1.setPhone(user.getPhone());
173                 user1.setOrgUserId(user.getOrgUserId());
174                 user1.setActive(user.getActive());
175                 user1.setLastLoginDate(new Date());
176
177                 try {
178                         dataAccessService.saveDomainObject(user1, null);
179                         logger.debug(EELFLoggerDelegate.debugLogger, "createdUser Successfully: " + user.getOrgUserId());
180                 } catch (Exception ex) {
181                         logger.error(EELFLoggerDelegate.errorLogger, "createUserIfNecessary failed", ex);
182                 }
183
184         }
185
186         private boolean userHasActiveRoles(User user) {
187                 boolean hasActiveRole = false;
188                 @SuppressWarnings("rawtypes")
189                 Iterator roles = user.getRoles().iterator();
190                 while (roles.hasNext()) {
191                         Role role = (Role) roles.next();
192                         if (role.getActive()) {
193                                 hasActiveRole = true;
194                                 break;
195                         }
196                 }
197                 return hasActiveRole;
198         }
199
200         private boolean userHasRoleFunctions(User user) {
201                 boolean hasRoleFunctions = false;
202                 @SuppressWarnings("rawtypes")
203                 Iterator roles = user.getRoles().iterator();
204                 while (roles.hasNext()) {
205                         Role role = (Role) roles.next();
206                         if (role.getActive() && role.getRoleFunctions() != null && !role.getRoleFunctions().isEmpty()) {
207                                 hasRoleFunctions = true;
208                                 break;
209                         }
210                 }
211                 return hasRoleFunctions;
212         }
213
214         private User findUser(LoginBean bean, HttpServletRequest request) throws Exception {
215                 User user =  userApiService.getUser(bean.getUserid(), request);
216                 user.setId(getUserIdByOrgUserId(user.getOrgUserId()));
217                 user.setLoginId(bean.getUserid());
218                 logger.debug(EELFLoggerDelegate.debugLogger, "findUser: Returning final user roles and permissions", user.toString());
219                 return user;
220         }
221         
222         private Long getUserIdByOrgUserId(String orgUserId) {
223                 Map<String, String> params = new HashMap<>();
224                 params.put("orgUserId", orgUserId);
225                 @SuppressWarnings("rawtypes")
226                 List list = dataAccessService.executeNamedQuery("getUserIdByorgUserId", params, null);
227                 Long userId = null;
228                 if (list != null && !list.isEmpty())
229                         userId = (Long) list.get(0);
230                 return userId;
231         }
232
233         @SuppressWarnings("rawtypes")
234         private User findUser(String loginId, String password) {
235                 Map<String, String> params = new HashMap<>();
236                 params.put("login_id", loginId);
237                 params.put("login_pwd", password);
238                 List list = dataAccessService.executeNamedQuery("getUserByLoginIdLoginPwd", params, new HashMap());
239                 return (list == null || list.isEmpty()) ? null : (User) list.get(0);
240         }
241
242         @SuppressWarnings("rawtypes")
243         @Override
244         public User findUserWithoutPwd(String loginId) {
245                 Map<String, String> params = new HashMap<>();
246                 params.put("org_user_id", loginId);
247                 List list = dataAccessService.executeNamedQuery("getUserByOrgUserId", params, new HashMap());
248                 return (list == null || list.isEmpty()) ? null : (User) list.get(0);
249         }
250
251         private MenuBuilder getMenuBuilder() {
252                 return new MenuBuilder();
253         }
254
255 }