UserRolesController methods up
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / user / FnUserService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ===================================================================
9  *
10  * Unless otherwise specified, all software contained herein is licensed
11  * under the Apache License, Version 2.0 (the "License");
12  * you may not use this software except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *             http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * Unless otherwise specified, all documentation contained herein is licensed
24  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
25  * you may not use this documentation except in compliance with the License.
26  * You may obtain a copy of the License at
27  *
28  *             https://creativecommons.org/licenses/by/4.0/
29  *
30  * Unless required by applicable law or agreed to in writing, documentation
31  * distributed under the License is distributed on an "AS IS" BASIS,
32  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33  * See the License for the specific language governing permissions and
34  * limitations under the License.
35  *
36  * ============LICENSE_END============================================
37  *
38  *
39  */
40
41 package org.onap.portal.service.user;
42
43 import java.io.BufferedReader;
44 import java.io.IOException;
45 import java.io.InputStreamReader;
46 import java.net.HttpURLConnection;
47 import java.net.URL;
48 import java.nio.charset.StandardCharsets;
49 import java.util.ArrayList;
50 import java.util.List;
51 import java.util.Optional;
52 import org.hibernate.criterion.Criterion;
53 import org.hibernate.criterion.Restrictions;
54 import org.json.JSONArray;
55 import org.json.JSONObject;
56 import org.onap.portal.domain.db.fn.FnUser;
57 import org.onap.portal.utils.EPCommonSystemProperties;
58 import org.onap.portal.utils.EPSystemProperties;
59 import org.onap.portalsdk.core.domain.FusionObject.Utilities;
60 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
61 import org.onap.portalsdk.core.util.SystemProperties;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.data.repository.query.Param;
64 import org.springframework.security.core.userdetails.UserDetailsService;
65 import org.springframework.security.core.userdetails.UsernameNotFoundException;
66 import org.springframework.stereotype.Service;
67 import org.springframework.transaction.annotation.Transactional;
68
69 @Service
70 @Transactional
71 public class FnUserService implements UserDetailsService {
72
73     private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class);
74
75     private final FnUserDao fnUserDao;
76
77     @Autowired
78     public FnUserService(FnUserDao fnUserDao) {
79         this.fnUserDao = fnUserDao;
80     }
81
82     @Override
83     public FnUser loadUserByUsername(final String username) throws UsernameNotFoundException {
84         Optional<FnUser> fnUser = fnUserDao.findByLoginId(username);
85         if (fnUser.isPresent()) {
86             return fnUser.get();
87         } else {
88             throw new UsernameNotFoundException("User not found for username: " + username);
89         }
90     }
91
92     public FnUser saveFnUser(final FnUser fnUser) {
93         return fnUserDao.save(fnUser);
94     }
95
96     public Optional<FnUser> getUser(final Long id) {
97         return Optional.of(fnUserDao.getOne(id));
98     }
99
100     public List<FnUser> getUserWithOrgUserId(final String orgUserIdValue) {
101         return fnUserDao.getUserWithOrgUserId(orgUserIdValue).orElse(new ArrayList<>());
102     }
103
104     public List<FnUser> getUsersByOrgIds(final List<String> orgIds) {
105         return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>());
106     }
107
108     public List<FnUser> getActiveUsers() {
109         return fnUserDao.getActiveUsers().orElse(new ArrayList<>());
110     }
111
112     public void deleteUser(final FnUser fnUser) {
113         fnUserDao.delete(fnUser);
114     }
115
116     public boolean existById(final Long userId) {
117         return fnUserDao.existsById(userId);
118     }
119
120     public List<FnUser> findAll() {
121         return fnUserDao.findAll();
122     }
123
124     public List<FnUser> saveAll(final List<FnUser> fnUsers) {
125         return fnUserDao.saveAll(fnUsers);
126     }
127
128     public FnUser save(final FnUser user) {
129         return fnUserDao.save(user);
130     }
131
132     public void delete(final FnUser user) {
133         fnUserDao.delete(user);
134     }
135
136     public List<FnUser> findByFirstNameAndLastName(final String firstName, final String lastName) {
137         return fnUserDao.findByFirstNameAndLastName(firstName, lastName).orElse(new ArrayList<>());
138     }
139
140     public List<FnUser> getUserByUserId(String userId) {
141         if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
142             List<FnUser> users = new ArrayList<>();
143             List<FnUser> filterdUsers = new ArrayList<>();
144             BufferedReader in = null;
145             HttpURLConnection con = null;
146             try {
147                 String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER);
148                 URL obj = new URL(url);
149
150                 con = (HttpURLConnection) obj.openConnection();
151
152                 // optional default is GET
153                 con.setRequestMethod("GET");
154                 con.setConnectTimeout(3000);
155                 con.setReadTimeout(8000);
156
157                 StringBuffer response = new StringBuffer();
158
159                 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
160                 String inputLine;
161                 while ((inputLine = in.readLine()) != null) {
162                     response.append(inputLine);
163                 }
164                 JSONObject jObject = new JSONObject(response.toString()); // json
165                 JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object
166                 for (int i = 0; i < jsonUsers.length(); i++) {
167                     JSONObject eachObject = jsonUsers.getJSONObject(i);
168                     FnUser eachUser = new FnUser();
169                     eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id"));
170                     eachUser.setFirstName(eachObject.get("givenName").toString());
171                     eachUser.setLastName(eachObject.get("familyName").toString());
172                     eachUser.setEmail(eachObject.get("email").toString());
173                     users.add(eachUser);
174                 }
175
176                 for (FnUser user : users) {
177
178                     if (Utilities.nvl(userId).length() > 0) {
179                         if (!userId.equalsIgnoreCase(user.getOrgUserId())) {
180                             continue;
181                         }
182                     }
183                     filterdUsers.add(user);
184
185                 }
186
187             } catch (Exception e) {
188                 logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId failed", e);
189             } finally {
190                 try {
191                     if (in != null) {
192                         in.close();
193                     }
194                     con.disconnect();
195                 } catch (IOException e) {
196                     logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId 2 failed", e);
197                 }
198             }
199             return filterdUsers;
200         } else {
201             List<FnUser> list = this.getUserWithOrgUserId(userId);
202             return (list == null || list.size() == 0) ? null : list;
203         }
204
205     }
206
207     public List<FnUser> getUserByFirstLastName(String firstName, String lastName) {
208         if (!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
209             List<FnUser> list = this.findByFirstNameAndLastName(firstName, lastName);
210             return (list == null || list.size() == 0) ? null : list;
211         } else {
212             List<FnUser> users = new ArrayList<>();
213             List<FnUser> filterdUsers = new ArrayList<>();
214             BufferedReader in = null;
215             HttpURLConnection con = null;
216             try {
217                 String url = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER);
218                 URL obj = new URL(url);
219                 con = (HttpURLConnection) obj.openConnection();
220                 con.setRequestMethod("GET");
221                 con.setConnectTimeout(3000);
222                 con.setReadTimeout(8000);
223                 StringBuffer response = new StringBuffer();
224                 in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
225                 String inputLine;
226                 while ((inputLine = in.readLine()) != null) {
227                     response.append(inputLine);
228                 }
229                 JSONObject jObject = new JSONObject(response.toString());
230                 JSONArray jsonUsers = jObject.getJSONArray("response");
231                 for (int i = 0; i < jsonUsers.length(); i++) {
232                     JSONObject eachObject = jsonUsers.getJSONObject(i);
233                     FnUser eachUser = new FnUser();
234                     eachUser.setOrgUserId(eachObject.get("id").toString());
235                     eachUser.setFirstName(eachObject.get("givenName").toString());
236                     eachUser.setLastName(eachObject.get("familyName").toString());
237                     eachUser.setEmail(eachObject.get("email").toString());
238                     users.add(eachUser);
239                 }
240                 for (FnUser user : users) {
241                     if (Utilities.nvl(firstName).length() > 0) {
242                         if (!firstName.equalsIgnoreCase(user.getFirstName())) {
243                             continue;
244                         }
245                     }
246                     if (Utilities.nvl(lastName).length() > 0) {
247                         if (!lastName.equalsIgnoreCase(user.getLastName())) {
248                             continue;
249                         }
250                     }
251                     filterdUsers.add(user);
252                 }
253             } catch (Exception e) {
254                 logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed", e);
255             } finally {
256                 try {
257                     if (in != null) {
258                         in.close();
259                         con.disconnect();
260                     }
261                 } catch (IOException e) {
262                     logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed to close", e);
263                 }
264             }
265             return filterdUsers;
266         }
267     }
268 }