Repository navigation
Expand file tree
/
Copy pathAdminUserAuthorizationResource.java
More file actions
445 lines (406 loc) · 17.7 KB
/
Copy pathAdminUserAuthorizationResource.java
File metadata and controls
445 lines (406 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.semoss.web.services.local.auth;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.Gson;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import prerna.auth.AuthProvider;
import prerna.auth.User;
import prerna.auth.access.ModelUsageLimit;
import prerna.auth.utils.AbstractSecurityUtils;
import prerna.auth.utils.SecurityAdminUtils;
import prerna.auth.utils.SecurityModelUsageLimitUtils;
import prerna.auth.utils.SecurityUpdateUtils;
import prerna.semoss.web.services.local.ResourceUtility;
import prerna.util.Constants;
import prerna.util.ValueUtils;
import prerna.web.services.util.WebUtility;
@Path("/auth/admin/user")
@PermitAll
public class AdminUserAuthorizationResource extends AbstractAdminResource {
private static final Logger classLogger = LogManager.getLogger(AdminUserAuthorizationResource.class);
/**
* The registerUser form field for the person's all-models default, as JSON,
* empty for no limit defined
*/
private static final String MODEL_USAGE_LIMIT = "modelUsageLimit";
private static final String USER_ID_REQUIRED = "The user id ('userId') cannot be null or empty";
private static final String TYPE_REQUIRED = "The login type ('type') cannot be null or empty";
@GET
@Path("/isAdminUser")
@Produces("application/json")
public Response isAdminUser(@Context HttpServletRequest request) {
User user = null;
try {
user = ResourceUtility.getUser(request);
} catch (IllegalAccessException e) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "User session is invalid");
return WebUtility.getResponse(errorMap, 401);
}
boolean isAdmin = SecurityAdminUtils.userIsAdmin(user);
return WebUtility.getResponse(isAdmin, 200);
}
/**
* Registers a person. Their all-models default is sent as
* {@code modelUsageLimit} (JSON, empty or left out for no limit defined).
*
* @param request the request
* @param form the form
* @return whether the person was registered
*/
@POST
@Path("/registerUser")
@Produces("application/json")
public Response registerUser(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
String newUserId = form.getFirst("userId");
return ResourceUtility.respondAsAdmin(request, "register user " + newUserId, user -> {
if (newUserId == null || newUserId.isEmpty()) {
throw new IllegalArgumentException("The user id cannot be null or empty");
}
String type = requireLoginType(WebUtility.inputSanitizer(form.getFirst("type")));
String name = WebUtility.inputSQLSanitizer(form.getFirst("name"));
String email = WebUtility.inputSQLSanitizer(form.getFirst("email"));
String phone = WebUtility.inputSanitizer(request.getParameter("phone"));
String phoneExtension = WebUtility.inputSanitizer(request.getParameter("phoneextension"));
String countryCode = WebUtility.inputSanitizer(request.getParameter("countrycode"));
Boolean newUserAdmin = Boolean.parseBoolean(form.getFirst("admin"));
Boolean publisher = Boolean.parseBoolean(form.getFirst("publisher"));
Boolean exporter = Boolean.parseBoolean(form.getFirst("exporter"));
String password = WebUtility.inputSQLSanitizer(form.getFirst("password"));
ModelUsageLimit modelUsageLimit = SecurityModelUsageLimitUtils.readJson(form.getFirst(MODEL_USAGE_LIMIT));
// each check throws an IllegalArgumentException, answered with 400
if (email != null && !email.isEmpty()) {
AbstractSecurityUtils.validEmail(email, true);
}
if (phone != null && !phone.isEmpty()) {
phone = AbstractSecurityUtils.formatPhone(phone);
}
// password is only defined if native type
if (password != null && !password.isEmpty()) {
AbstractSecurityUtils.validPassword(newUserId, AuthProvider.NATIVE, password);
}
return SecurityUpdateUtils.registerUser(newUserId, name, email, password, type, phone, phoneExtension,
countryCode, newUserAdmin, publisher, exporter, modelUsageLimit);
});
}
/**
* Set user as publisher
*
* @param request
* @param form
* @return
*/
@POST
@Path("/setUserPublisher")
@Produces("application/json")
public Response setUserPublisher(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to update user publisher.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String userId = WebUtility.inputSQLSanitizer(form.getFirst("userId"));
String type = AuthProvider.getProviderLabel(WebUtility.inputSQLSanitizer(form.getFirst("type")));
boolean isPublisher = Boolean.parseBoolean(form.getFirst("isPublisher"));
try {
adminUtils.setUserPublisher(ValueUtils.requireNonBlank(userId, USER_ID_REQUIRED),
ValueUtils.requireNonBlank(type, TYPE_REQUIRED), isPublisher);
} catch (Exception e) {
classLogger.error("Failed to update user publisher.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 400);
}
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("success", true);
return WebUtility.getResponse(ret, 200);
}
/**
* Set user as locked/unlocked
*
* @param request
* @param form
* @return
*/
@POST
@Path("/setUserLocked")
@Produces("application/json")
public Response setUserLocked(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to update user locked.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String userId = WebUtility.inputSQLSanitizer(form.getFirst("userId"));
String type = WebUtility.inputSQLSanitizer(form.getFirst("type"));
boolean isLocked = Boolean.parseBoolean(form.getFirst("isLocked"));
try {
adminUtils.setUserLock(userId, type, isLocked);
} catch (Exception e) {
classLogger.error("Failed to update user locked.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 400);
}
Map<String, Object> ret = new HashMap<String, Object>();
ret.put("success", true);
return WebUtility.getResponse(ret, 200);
}
/**
* Edit user properties. The user JSON can carry the person's all-models default
* as {@code model_usage_limit}, null for no limit defined; without the key, the
* default is kept as it is.
*
* @param request
* @param form
* @return true if the edition was performed
*/
@POST
@Path("/editUser")
@Produces("application/json")
public Response editUser(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to update user.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
Gson gson = new Gson();
Map<String, Object> userInfo = gson.fromJson(form.getFirst("user"), Map.class);
Boolean adminChange = null;
if (userInfo.containsKey("admin")) {
if (userInfo.get("admin") instanceof Number) {
adminChange = ((Number) userInfo.get("admin")).intValue() == 1;
classLogger.info("User has edited user {} to admin level {}", userInfo.get("id"),
userInfo.get("admin"));
} else {
adminChange = Boolean.parseBoolean(userInfo.get("admin") + "");
classLogger.info("User has edited user {} to admin level {}", userInfo.get("id"),
userInfo.get("admin"));
}
}
if (adminChange != null && !adminChange) {
// if you are making this user not an admin
// need to make sure they are not the last admin for the instance
synchronized (AdminUserAuthorizationResource.class) {
int numAdmins = adminUtils.getNumAdmins();
if (numAdmins == 1) {
Object[] adminUser = adminUtils.getAdminUserIdAndType();
String thisUserId = userInfo.get("id") + "";
String thisUserType = userInfo.get("type") + "";
if (thisUserId.equals(adminUser[0]) && thisUserType.equals(adminUser[1])) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE,
"You cannot remove the last admin from having admin level permissions. Please assign a new admin before removing admin access.");
return WebUtility.getResponse(errorMap, 400);
}
}
}
}
boolean ret = false;
try {
ret = adminUtils.editUser(userInfo);
} catch (IllegalArgumentException e) {
Map<String, String> retMap = new HashMap<>();
retMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(retMap, 400);
}
if (!ret) {
Map<String, String> retMap = new HashMap<>();
retMap.put(Constants.ERROR_MESSAGE, "Unknown error occurred with updating user. Please try again.");
return WebUtility.getResponse(retMap, 400);
}
return WebUtility.getResponse(ret, 200);
}
@POST
@Path("/deleteUser")
@Produces("application/json")
public Response deleteUser(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to delete user.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String userIdToDelete = WebUtility.inputSQLSanitizer(form.getFirst("userId"));
String userTypeToDelete = AuthProvider.getProviderLabel(WebUtility.inputSQLSanitizer(form.getFirst("type")));
if (userIdToDelete == null || userIdToDelete.isBlank() || userTypeToDelete == null
|| userTypeToDelete.isBlank()) {
// a user is an id and a login type; without the type, the last-admin check
// below would look for a user that does not exist
return ResourceUtility.errorResponse("The user id ('userId') and login type ('type') are required", 400);
}
boolean isDeletedUserAdmin = adminUtils.userIsAdmin(userIdToDelete, userTypeToDelete);
if (isDeletedUserAdmin) {
// need to make sure there are other admins and we are not deleting the last
// admin
if (!adminUtils.otherAdminsExist(userIdToDelete, userTypeToDelete)) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE,
"You cannot delete this user as it is the last admin. Please assign a new admin before deleting this user.");
return WebUtility.getResponse(errorMap, 400);
}
}
// log the operation
classLogger.info("User has deleted user {} with provider {}", userIdToDelete, userTypeToDelete);
boolean success = adminUtils.deleteUser(userIdToDelete, userTypeToDelete);
return WebUtility.getResponse(success, 200);
}
/**
* Returns the label of a login type a request sends, such as NATIVE for
* "native" or MICROSOFT for "ms". Any provider SEMOSS has is accepted, whether
* or not its login is turned on here.
*
* @param type the login type the request sends
* @return the provider's label
* @throws IllegalArgumentException when the type is missing or names no
* provider
*/
private static String requireLoginType(String type) {
String sent = ValueUtils.requireNonBlank(type, TYPE_REQUIRED);
AuthProvider provider = AuthProvider.getSocialPropKeysToEnum().get(sent.trim().toLowerCase(Locale.ROOT));
if (provider == null) {
throw new IllegalArgumentException(
"The login type ('type') is not a known login type. Received value = " + sent);
}
return provider.getLabel();
}
@GET
@Path("/getAllUsers")
@Produces("application/json")
public Response getAllUsers(@Context HttpServletRequest request, @QueryParam("filterWord") String searchTerm,
@QueryParam("limit") long limit, @QueryParam("offset") long offset) {
searchTerm = WebUtility.inputSQLSanitizer(searchTerm);
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to search term.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
List<Map<String, Object>> ret = adminUtils.getAllUsers(searchTerm, limit, offset);
return WebUtility.getResponse(ret, 200);
}
@GET
@Path("/getNumUsers")
@Produces("application/json")
public Response getNumUsers(@Context HttpServletRequest request, @QueryParam("filterWord") String searchTerm) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to retrieve num users.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
Long ret = adminUtils.getNumUsers(searchTerm);
return WebUtility.getResponse(ret, 200);
}
@GET
@Path("/getAllAPIUsers")
@Produces("application/json")
public Response getAllAPIUsers(@Context HttpServletRequest request, @QueryParam("filterWord") String searchTerm,
@QueryParam("limit") long limit, @QueryParam("offset") long offset) {
searchTerm = WebUtility.inputSQLSanitizer(searchTerm);
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to search term.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
List<Map<String, Object>> ret = adminUtils.getAllAPIUsers(searchTerm, limit, offset);
return WebUtility.getResponse(ret, 200);
}
@GET
@Path("/getNumAPIUsers")
@Produces("application/json")
public Response getNumAPIUsers(@Context HttpServletRequest request, @QueryParam("filterWord") String searchTerm) {
SecurityAdminUtils adminUtils = null;
User user = null;
try {
user = ResourceUtility.getUser(request);
adminUtils = performAdminCheck(request, user);
} catch (IllegalAccessException e) {
classLogger.error("Failed to retrieve num users.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
Long ret = adminUtils.getNumAPIUsers(searchTerm);
return WebUtility.getResponse(ret, 200);
}
}