-
Notifications
You must be signed in to change notification settings - Fork 476
/
Admin.java
1510 lines (1383 loc) · 59.6 KB
/
Admin.java
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package edu.harvard.iq.dataverse.api;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.DataFileServiceBean;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetServiceBean;
import edu.harvard.iq.dataverse.DatasetVersion;
import edu.harvard.iq.dataverse.DatasetVersionServiceBean;
import edu.harvard.iq.dataverse.Dataverse;
import edu.harvard.iq.dataverse.DataverseRequestServiceBean;
import edu.harvard.iq.dataverse.DataverseSession;
import edu.harvard.iq.dataverse.DvObject;
import edu.harvard.iq.dataverse.EMailValidator;
import edu.harvard.iq.dataverse.EjbDataverseEngine;
import edu.harvard.iq.dataverse.GlobalId;
import edu.harvard.iq.dataverse.RoleAssignment;
import edu.harvard.iq.dataverse.UserServiceBean;
import edu.harvard.iq.dataverse.actionlogging.ActionLogRecord;
import edu.harvard.iq.dataverse.api.dto.RoleDTO;
import edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo;
import edu.harvard.iq.dataverse.authorization.AuthenticationProvider;
import edu.harvard.iq.dataverse.authorization.UserIdentifier;
import edu.harvard.iq.dataverse.authorization.exceptions.AuthenticationProviderFactoryNotFoundException;
import edu.harvard.iq.dataverse.authorization.exceptions.AuthorizationSetupException;
import edu.harvard.iq.dataverse.authorization.groups.GroupServiceBean;
import edu.harvard.iq.dataverse.authorization.providers.AuthenticationProviderRow;
import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUser;
import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUserServiceBean;
import edu.harvard.iq.dataverse.authorization.providers.shib.ShibAuthenticationProvider;
import edu.harvard.iq.dataverse.authorization.providers.shib.ShibServiceBean;
import edu.harvard.iq.dataverse.authorization.providers.shib.ShibUtil;
import edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser;
import edu.harvard.iq.dataverse.confirmemail.ConfirmEmailData;
import edu.harvard.iq.dataverse.confirmemail.ConfirmEmailException;
import edu.harvard.iq.dataverse.confirmemail.ConfirmEmailInitResponse;
import edu.harvard.iq.dataverse.dataaccess.DataAccessOption;
import edu.harvard.iq.dataverse.dataaccess.StorageIO;
import edu.harvard.iq.dataverse.engine.command.impl.AbstractSubmitToArchiveCommand;
import edu.harvard.iq.dataverse.engine.command.impl.PublishDataverseCommand;
import edu.harvard.iq.dataverse.settings.Setting;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import static edu.harvard.iq.dataverse.util.json.NullSafeJsonBuilder.jsonObjectBuilder;
import static edu.harvard.iq.dataverse.util.json.JsonPrinter.*;
import java.io.InputStream;
import java.io.StringReader;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.io.IOUtils;
import java.util.List;
import edu.harvard.iq.dataverse.authorization.AuthTestDataServiceBean;
import edu.harvard.iq.dataverse.authorization.RoleAssignee;
import edu.harvard.iq.dataverse.authorization.UserRecordIdentifier;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.dataset.DatasetThumbnail;
import edu.harvard.iq.dataverse.dataset.DatasetUtil;
import edu.harvard.iq.dataverse.engine.command.DataverseRequest;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.impl.MergeInAccountCommand;
import edu.harvard.iq.dataverse.engine.command.impl.ChangeUserIdentifierCommand;
import edu.harvard.iq.dataverse.engine.command.impl.RegisterDvObjectCommand;
import edu.harvard.iq.dataverse.ingest.IngestServiceBean;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.userdata.UserListMaker;
import edu.harvard.iq.dataverse.userdata.UserListResult;
import edu.harvard.iq.dataverse.util.ArchiverUtil;
import edu.harvard.iq.dataverse.util.BundleUtil;
import edu.harvard.iq.dataverse.util.FileUtil;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import javax.inject.Inject;
import javax.persistence.Query;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
/**
* Where the secure, setup API calls live.
*
* @author michael
*/
@Stateless
@Path("admin")
public class Admin extends AbstractApiBean {
private static final Logger logger = Logger.getLogger(Admin.class.getName());
@EJB
BuiltinUserServiceBean builtinUserService;
@EJB
ShibServiceBean shibService;
@EJB
AuthTestDataServiceBean authTestDataService;
@EJB
UserServiceBean userService;
@EJB
IngestServiceBean ingestService;
@EJB
DataFileServiceBean fileService;
@EJB
DatasetServiceBean datasetService;
@EJB
DatasetVersionServiceBean datasetversionService;
@Inject
DataverseRequestServiceBean dvRequestService;
@EJB
EjbDataverseEngine commandEngine;
@EJB
GroupServiceBean groupService;
@EJB
SettingsServiceBean settingsService;
// Make the session available
@Inject
DataverseSession session;
public static final String listUsersPartialAPIPath = "list-users";
public static final String listUsersFullAPIPath = "/api/admin/" + listUsersPartialAPIPath;
@Path("settings")
@GET
public Response listAllSettings() {
JsonObjectBuilder bld = jsonObjectBuilder();
settingsSvc.listAll().forEach(s -> bld.add(s.getName(), s.getContent()));
return ok(bld);
}
@Path("settings/{name}")
@PUT
public Response putSetting(@PathParam("name") String name, String content) {
Setting s = settingsSvc.set(name, content);
return ok(jsonObjectBuilder().add(s.getName(), s.getContent()));
}
@Path("settings/{name}")
@GET
public Response getSetting(@PathParam("name") String name) {
String s = settingsSvc.get(name);
return (s != null) ? ok(s) : notFound("Setting " + name + " not found");
}
@Path("settings/{name}")
@DELETE
public Response deleteSetting(@PathParam("name") String name) {
settingsSvc.delete(name);
return ok("Setting " + name + " deleted.");
}
@Path("authenticationProviderFactories")
@GET
public Response listAuthProviderFactories() {
return ok(authSvc.listProviderFactories().stream()
.map(f -> jsonObjectBuilder().add("alias", f.getAlias()).add("info", f.getInfo()))
.collect(toJsonArray()));
}
@Path("authenticationProviders")
@GET
public Response listAuthProviders() {
return ok(em.createNamedQuery("AuthenticationProviderRow.findAll", AuthenticationProviderRow.class)
.getResultList().stream().map(r -> json(r)).collect(toJsonArray()));
}
@Path("authenticationProviders")
@POST
public Response addProvider(AuthenticationProviderRow row) {
try {
AuthenticationProviderRow managed = em.find(AuthenticationProviderRow.class, row.getId());
if (managed != null) {
managed = em.merge(row);
} else {
em.persist(row);
managed = row;
}
if (managed.isEnabled()) {
AuthenticationProvider provider = authSvc.loadProvider(managed);
authSvc.deregisterProvider(provider.getId());
authSvc.registerProvider(provider);
}
return created("/api/admin/authenticationProviders/" + managed.getId(), json(managed));
} catch (AuthorizationSetupException e) {
return error(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
@Path("authenticationProviders/{id}")
@GET
public Response showProvider(@PathParam("id") String id) {
AuthenticationProviderRow row = em.find(AuthenticationProviderRow.class, id);
return (row != null) ? ok(json(row))
: error(Status.NOT_FOUND, "Can't find authetication provider with id '" + id + "'");
}
@POST
@Path("authenticationProviders/{id}/:enabled")
public Response enableAuthenticationProvider_deprecated(@PathParam("id") String id, String body) {
return enableAuthenticationProvider(id, body);
}
@PUT
@Path("authenticationProviders/{id}/enabled")
@Produces("application/json")
public Response enableAuthenticationProvider(@PathParam("id") String id, String body) {
body = body.trim();
if (!Util.isBoolean(body)) {
return error(Response.Status.BAD_REQUEST, "Illegal value '" + body + "'. Use 'true' or 'false'");
}
boolean enable = Util.isTrue(body);
AuthenticationProviderRow row = em.find(AuthenticationProviderRow.class, id);
if (row == null) {
return notFound("Can't find authentication provider with id '" + id + "'");
}
row.setEnabled(enable);
em.merge(row);
if (enable) {
// enable a provider
if (authSvc.getAuthenticationProvider(id) != null) {
return ok(String.format("Authentication provider '%s' already enabled", id));
}
try {
authSvc.registerProvider(authSvc.loadProvider(row));
return ok(String.format("Authentication Provider %s enabled", row.getId()));
} catch (AuthenticationProviderFactoryNotFoundException ex) {
return notFound(String.format("Can't instantiate provider, as there's no factory with alias %s",
row.getFactoryAlias()));
} catch (AuthorizationSetupException ex) {
logger.log(Level.WARNING, "Error instantiating authentication provider: " + ex.getMessage(), ex);
return error(Status.INTERNAL_SERVER_ERROR,
String.format("Can't instantiate provider: %s", ex.getMessage()));
}
} else {
// disable a provider
authSvc.deregisterProvider(id);
return ok("Authentication Provider '" + id + "' disabled. "
+ (authSvc.getAuthenticationProviderIds().isEmpty()
? "WARNING: no enabled authentication providers left."
: ""));
}
}
@GET
@Path("authenticationProviders/{id}/enabled")
public Response checkAuthenticationProviderEnabled(@PathParam("id") String id) {
List<AuthenticationProviderRow> prvs = em
.createNamedQuery("AuthenticationProviderRow.findById", AuthenticationProviderRow.class)
.setParameter("id", id).getResultList();
if (prvs.isEmpty()) {
return notFound("Can't find a provider with id '" + id + "'.");
} else {
return ok(Boolean.toString(prvs.get(0).isEnabled()));
}
}
@DELETE
@Path("authenticationProviders/{id}/")
public Response deleteAuthenticationProvider(@PathParam("id") String id) {
authSvc.deregisterProvider(id);
AuthenticationProviderRow row = em.find(AuthenticationProviderRow.class, id);
if (row != null) {
em.remove(row);
}
return ok("AuthenticationProvider " + id + " deleted. "
+ (authSvc.getAuthenticationProviderIds().isEmpty()
? "WARNING: no enabled authentication providers left."
: ""));
}
@GET
@Path("authenticatedUsers/{identifier}/")
public Response getAuthenticatedUser(@PathParam("identifier") String identifier) {
AuthenticatedUser authenticatedUser = authSvc.getAuthenticatedUser(identifier);
if (authenticatedUser != null) {
return ok(json(authenticatedUser));
}
return error(Response.Status.BAD_REQUEST, "User " + identifier + " not found.");
}
@DELETE
@Path("authenticatedUsers/{identifier}/")
public Response deleteAuthenticatedUser(@PathParam("identifier") String identifier) {
AuthenticatedUser user = authSvc.getAuthenticatedUser(identifier);
if (user != null) {
authSvc.deleteAuthenticatedUser(user.getId());
return ok("AuthenticatedUser " + identifier + " deleted. ");
}
return error(Response.Status.BAD_REQUEST, "User " + identifier + " not found.");
}
@POST
@Path("publishDataverseAsCreator/{id}")
public Response publishDataverseAsCreator(@PathParam("id") long id) {
try {
Dataverse dataverse = dataverseSvc.find(id);
if (dataverse != null) {
AuthenticatedUser authenticatedUser = dataverse.getCreator();
return ok(json(execCommand(
new PublishDataverseCommand(createDataverseRequest(authenticatedUser), dataverse))));
} else {
return error(Status.BAD_REQUEST, "Could not find dataverse with id " + id);
}
} catch (WrappedResponse wr) {
return wr.getResponse();
}
}
@Deprecated
@GET
@Path("authenticatedUsers")
public Response listAuthenticatedUsers() {
try {
AuthenticatedUser user = findAuthenticatedUserOrDie();
if (!user.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
JsonArrayBuilder userArray = Json.createArrayBuilder();
authSvc.findAllAuthenticatedUsers().stream().forEach((user) -> {
userArray.add(json(user));
});
return ok(userArray);
}
@GET
@Path(listUsersPartialAPIPath)
@Produces({ "application/json" })
public Response filterAuthenticatedUsers(@QueryParam("searchTerm") String searchTerm,
@QueryParam("selectedPage") Integer selectedPage, @QueryParam("itemsPerPage") Integer itemsPerPage) {
User authUser;
try {
authUser = this.findUserOrDie();
} catch (AbstractApiBean.WrappedResponse ex) {
return error(Response.Status.FORBIDDEN,
BundleUtil.getStringFromBundle("dashboard.list_users.api.auth.invalid_apikey"));
}
if (!authUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN,
BundleUtil.getStringFromBundle("dashboard.list_users.api.auth.not_superuser"));
}
UserListMaker userListMaker = new UserListMaker(userService);
String sortKey = null;
UserListResult userListResult = userListMaker.runUserSearch(searchTerm, itemsPerPage, selectedPage, sortKey);
return ok(userListResult.toJSON());
}
/**
* @todo Make this support creation of BuiltInUsers.
*
* @todo Add way more error checking. Only the happy path is tested by AdminIT.
*/
@POST
@Path("authenticatedUsers")
public Response createAuthenicatedUser(JsonObject jsonObject) {
logger.fine("JSON in: " + jsonObject);
String persistentUserId = jsonObject.getString("persistentUserId");
String identifier = jsonObject.getString("identifier");
String proposedAuthenticatedUserIdentifier = identifier.replaceFirst("@", "");
String firstName = jsonObject.getString("firstName");
String lastName = jsonObject.getString("lastName");
String emailAddress = jsonObject.getString("email");
String position = null;
String affiliation = null;
UserRecordIdentifier userRecordId = new UserRecordIdentifier(jsonObject.getString("authenticationProviderId"),
persistentUserId);
AuthenticatedUserDisplayInfo userDisplayInfo = new AuthenticatedUserDisplayInfo(firstName, lastName,
emailAddress, affiliation, position);
boolean generateUniqueIdentifier = true;
AuthenticatedUser authenticatedUser = authSvc.createAuthenticatedUser(userRecordId,
proposedAuthenticatedUserIdentifier, userDisplayInfo, true);
return ok(json(authenticatedUser));
}
//TODO: Delete this endpoint after 4.9.3. Was updated with change in docs. --MAD
/**
* curl -X PUT -d "shib@mailinator.com"
* http://localhost:8080/api/admin/authenticatedUsers/id/11/convertShibToBuiltIn
*
* @deprecated We have documented this API endpoint so we'll keep in around for
* a while but we should encourage everyone to switch to the
* "convertRemoteToBuiltIn" endpoint and then remove this
* Shib-specfic one.
*/
@PUT
@Path("authenticatedUsers/id/{id}/convertShibToBuiltIn")
@Deprecated
public Response convertShibUserToBuiltin(@PathParam("id") Long id, String newEmailAddress) {
try {
AuthenticatedUser user = findAuthenticatedUserOrDie();
if (!user.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
try {
BuiltinUser builtinUser = authSvc.convertRemoteToBuiltIn(id, newEmailAddress);
if (builtinUser == null) {
return error(Response.Status.BAD_REQUEST, "User id " + id
+ " could not be converted from Shibboleth to BuiltIn. An Exception was not thrown.");
}
AuthenticatedUser authUser = authSvc.getAuthenticatedUser(builtinUser.getUserName());
JsonObjectBuilder output = Json.createObjectBuilder();
output.add("email", authUser.getEmail());
output.add("username", builtinUser.getUserName());
return ok(output);
} catch (Throwable ex) {
StringBuilder sb = new StringBuilder();
sb.append(ex + " ");
while (ex.getCause() != null) {
ex = ex.getCause();
sb.append(ex + " ");
}
String msg = "User id " + id
+ " could not be converted from Shibboleth to BuiltIn. Details from Exception: " + sb;
logger.info(msg);
return error(Response.Status.BAD_REQUEST, msg);
}
}
@PUT
@Path("authenticatedUsers/id/{id}/convertRemoteToBuiltIn")
public Response convertOAuthUserToBuiltin(@PathParam("id") Long id, String newEmailAddress) {
try {
AuthenticatedUser user = findAuthenticatedUserOrDie();
if (!user.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
try {
BuiltinUser builtinUser = authSvc.convertRemoteToBuiltIn(id, newEmailAddress);
//AuthenticatedUser authUser = authService.getAuthenticatedUser(aUser.getUserName());
if (builtinUser == null) {
return error(Response.Status.BAD_REQUEST, "User id " + id
+ " could not be converted from remote to BuiltIn. An Exception was not thrown.");
}
AuthenticatedUser authUser = authSvc.getAuthenticatedUser(builtinUser.getUserName());
JsonObjectBuilder output = Json.createObjectBuilder();
output.add("email", authUser.getEmail());
output.add("username", builtinUser.getUserName());
return ok(output);
} catch (Throwable ex) {
StringBuilder sb = new StringBuilder();
sb.append(ex + " ");
while (ex.getCause() != null) {
ex = ex.getCause();
sb.append(ex + " ");
}
String msg = "User id " + id + " could not be converted from remote to BuiltIn. Details from Exception: "
+ sb;
logger.info(msg);
return error(Response.Status.BAD_REQUEST, msg);
}
}
/**
* This is used in testing via AdminIT.java but we don't expect sysadmins to use
* this.
*/
@Path("authenticatedUsers/convert/builtin2shib")
@PUT
public Response builtin2shib(String content) {
logger.info("entering builtin2shib...");
try {
AuthenticatedUser userToRunThisMethod = findAuthenticatedUserOrDie();
if (!userToRunThisMethod.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
boolean disabled = false;
if (disabled) {
return error(Response.Status.BAD_REQUEST, "API endpoint disabled.");
}
AuthenticatedUser builtInUserToConvert = null;
String emailToFind;
String password;
String authuserId = "0"; // could let people specify id on authuser table. probably better to let them
// tell us their
String newEmailAddressToUse;
try {
String[] args = content.split(":");
emailToFind = args[0];
password = args[1];
newEmailAddressToUse = args[2];
// authuserId = args[666];
} catch (ArrayIndexOutOfBoundsException ex) {
return error(Response.Status.BAD_REQUEST, "Problem with content <<<" + content + ">>>: " + ex.toString());
}
AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailToFind);
String existing = "NOT FOUND";
if (existingAuthUserFoundByEmail != null) {
builtInUserToConvert = existingAuthUserFoundByEmail;
existing = existingAuthUserFoundByEmail.getIdentifier();
} else {
long longToLookup = Long.parseLong(authuserId);
AuthenticatedUser specifiedUserToConvert = authSvc.findByID(longToLookup);
if (specifiedUserToConvert != null) {
builtInUserToConvert = specifiedUserToConvert;
} else {
return error(Response.Status.BAD_REQUEST,
"No user to convert. We couldn't find a *single* existing user account based on " + emailToFind
+ " and no user was found using specified id " + longToLookup);
}
}
String shibProviderId = ShibAuthenticationProvider.PROVIDER_ID;
Map<String, String> randomUser = authTestDataService.getRandomUser();
// String eppn = UUID.randomUUID().toString().substring(0, 8);
String eppn = randomUser.get("eppn");
String idPEntityId = randomUser.get("idp");
String notUsed = null;
String separator = "|";
UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(idPEntityId + separator + eppn, notUsed);
String overwriteFirstName = randomUser.get("firstName");
String overwriteLastName = randomUser.get("lastName");
String overwriteEmail = randomUser.get("email");
overwriteEmail = newEmailAddressToUse;
logger.info("overwriteEmail: " + overwriteEmail);
boolean validEmail = EMailValidator.isEmailValid(overwriteEmail, null);
if (!validEmail) {
// See https://github.com/IQSS/dataverse/issues/2998
return error(Response.Status.BAD_REQUEST, "invalid email: " + overwriteEmail);
}
/**
* @todo If affiliation is not null, put it in RoleAssigneeDisplayInfo
* constructor.
*/
/**
* Here we are exercising (via an API test) shibService.getAffiliation with the
* TestShib IdP and a non-production DevShibAccountType.
*/
idPEntityId = ShibUtil.testShibIdpEntityId;
String overwriteAffiliation = shibService.getAffiliation(idPEntityId,
ShibServiceBean.DevShibAccountType.RANDOM);
logger.info("overwriteAffiliation: " + overwriteAffiliation);
/**
* @todo Find a place to put "position" in the authenticateduser table:
* https://github.com/IQSS/dataverse/issues/1444#issuecomment-74134694
*/
String overwritePosition = "staff;student";
AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo(overwriteFirstName,
overwriteLastName, overwriteEmail, overwriteAffiliation, overwritePosition);
JsonObjectBuilder response = Json.createObjectBuilder();
JsonArrayBuilder problems = Json.createArrayBuilder();
if (password != null) {
response.add("password supplied", password);
boolean knowsExistingPassword = false;
BuiltinUser oldBuiltInUser = builtinUserService.findByUserName(builtInUserToConvert.getUserIdentifier());
if (oldBuiltInUser != null) {
String usernameOfBuiltinAccountToConvert = oldBuiltInUser.getUserName();
response.add("old username", usernameOfBuiltinAccountToConvert);
AuthenticatedUser authenticatedUser = authSvc.canLogInAsBuiltinUser(usernameOfBuiltinAccountToConvert,
password);
if (authenticatedUser != null) {
knowsExistingPassword = true;
AuthenticatedUser convertedUser = authSvc.convertBuiltInToShib(builtInUserToConvert, shibProviderId,
newUserIdentifierInLookupTable);
if (convertedUser != null) {
/**
* @todo Display name is not being overwritten. Logic must be in Shib backing
* bean
*/
AuthenticatedUser updatedInfoUser = authSvc.updateAuthenticatedUser(convertedUser, displayInfo);
if (updatedInfoUser != null) {
response.add("display name overwritten with", updatedInfoUser.getName());
} else {
problems.add("couldn't update display info");
}
} else {
problems.add("unable to convert user");
}
}
} else {
problems.add("couldn't find old username");
}
if (!knowsExistingPassword) {
String message = "User doesn't know password.";
problems.add(message);
/**
* @todo Someday we should make a errorResponse method that takes JSON arrays
* and objects.
*/
return error(Status.BAD_REQUEST, problems.build().toString());
}
// response.add("knows existing password", knowsExistingPassword);
}
response.add("user to convert", builtInUserToConvert.getIdentifier());
response.add("existing user found by email (prompt to convert)", existing);
response.add("changing to this provider", shibProviderId);
response.add("value to overwrite old first name", overwriteFirstName);
response.add("value to overwrite old last name", overwriteLastName);
response.add("value to overwrite old email address", overwriteEmail);
if (overwriteAffiliation != null) {
response.add("affiliation", overwriteAffiliation);
}
response.add("problems", problems);
return ok(response);
}
/**
* This is used in testing via AdminIT.java but we don't expect sysadmins to use
* this.
*/
@Path("authenticatedUsers/convert/builtin2oauth")
@PUT
public Response builtin2oauth(String content) {
logger.info("entering builtin2oauth...");
try {
AuthenticatedUser userToRunThisMethod = findAuthenticatedUserOrDie();
if (!userToRunThisMethod.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
} catch (WrappedResponse ex) {
return error(Response.Status.FORBIDDEN, "Superusers only.");
}
boolean disabled = false;
if (disabled) {
return error(Response.Status.BAD_REQUEST, "API endpoint disabled.");
}
AuthenticatedUser builtInUserToConvert = null;
String emailToFind;
String password;
String authuserId = "0"; // could let people specify id on authuser table. probably better to let them
// tell us their
String newEmailAddressToUse;
String newProviderId;
String newPersistentUserIdInLookupTable;
logger.info("content: " + content);
try {
String[] args = content.split(":");
emailToFind = args[0];
password = args[1];
newEmailAddressToUse = args[2];
newProviderId = args[3];
newPersistentUserIdInLookupTable = args[4];
// authuserId = args[666];
} catch (ArrayIndexOutOfBoundsException ex) {
return error(Response.Status.BAD_REQUEST, "Problem with content <<<" + content + ">>>: " + ex.toString());
}
AuthenticatedUser existingAuthUserFoundByEmail = shibService.findAuthUserByEmail(emailToFind);
String existing = "NOT FOUND";
if (existingAuthUserFoundByEmail != null) {
builtInUserToConvert = existingAuthUserFoundByEmail;
existing = existingAuthUserFoundByEmail.getIdentifier();
} else {
long longToLookup = Long.parseLong(authuserId);
AuthenticatedUser specifiedUserToConvert = authSvc.findByID(longToLookup);
if (specifiedUserToConvert != null) {
builtInUserToConvert = specifiedUserToConvert;
} else {
return error(Response.Status.BAD_REQUEST,
"No user to convert. We couldn't find a *single* existing user account based on " + emailToFind
+ " and no user was found using specified id " + longToLookup);
}
}
// String shibProviderId = ShibAuthenticationProvider.PROVIDER_ID;
Map<String, String> randomUser = authTestDataService.getRandomUser();
// String eppn = UUID.randomUUID().toString().substring(0, 8);
String eppn = randomUser.get("eppn");
String idPEntityId = randomUser.get("idp");
String notUsed = null;
String separator = "|";
// UserIdentifier newUserIdentifierInLookupTable = new
// UserIdentifier(idPEntityId + separator + eppn, notUsed);
UserIdentifier newUserIdentifierInLookupTable = new UserIdentifier(newPersistentUserIdInLookupTable, notUsed);
String overwriteFirstName = randomUser.get("firstName");
String overwriteLastName = randomUser.get("lastName");
String overwriteEmail = randomUser.get("email");
overwriteEmail = newEmailAddressToUse;
logger.info("overwriteEmail: " + overwriteEmail);
boolean validEmail = EMailValidator.isEmailValid(overwriteEmail, null);
if (!validEmail) {
// See https://github.com/IQSS/dataverse/issues/2998
return error(Response.Status.BAD_REQUEST, "invalid email: " + overwriteEmail);
}
/**
* @todo If affiliation is not null, put it in RoleAssigneeDisplayInfo
* constructor.
*/
/**
* Here we are exercising (via an API test) shibService.getAffiliation with the
* TestShib IdP and a non-production DevShibAccountType.
*/
// idPEntityId = ShibUtil.testShibIdpEntityId;
// String overwriteAffiliation = shibService.getAffiliation(idPEntityId,
// ShibServiceBean.DevShibAccountType.RANDOM);
String overwriteAffiliation = null;
logger.info("overwriteAffiliation: " + overwriteAffiliation);
/**
* @todo Find a place to put "position" in the authenticateduser table:
* https://github.com/IQSS/dataverse/issues/1444#issuecomment-74134694
*/
String overwritePosition = "staff;student";
AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo(overwriteFirstName,
overwriteLastName, overwriteEmail, overwriteAffiliation, overwritePosition);
JsonObjectBuilder response = Json.createObjectBuilder();
JsonArrayBuilder problems = Json.createArrayBuilder();
if (password != null) {
response.add("password supplied", password);
boolean knowsExistingPassword = false;
BuiltinUser oldBuiltInUser = builtinUserService.findByUserName(builtInUserToConvert.getUserIdentifier());
if (oldBuiltInUser != null) {
String usernameOfBuiltinAccountToConvert = oldBuiltInUser.getUserName();
response.add("old username", usernameOfBuiltinAccountToConvert);
AuthenticatedUser authenticatedUser = authSvc.canLogInAsBuiltinUser(usernameOfBuiltinAccountToConvert,
password);
if (authenticatedUser != null) {
knowsExistingPassword = true;
AuthenticatedUser convertedUser = authSvc.convertBuiltInUserToRemoteUser(builtInUserToConvert,
newProviderId, newUserIdentifierInLookupTable);
if (convertedUser != null) {
/**
* @todo Display name is not being overwritten. Logic must be in Shib backing
* bean
*/
AuthenticatedUser updatedInfoUser = authSvc.updateAuthenticatedUser(convertedUser, displayInfo);
if (updatedInfoUser != null) {
response.add("display name overwritten with", updatedInfoUser.getName());
} else {
problems.add("couldn't update display info");
}
} else {
problems.add("unable to convert user");
}
}
} else {
problems.add("couldn't find old username");
}
if (!knowsExistingPassword) {
String message = "User doesn't know password.";
problems.add(message);
/**
* @todo Someday we should make a errorResponse method that takes JSON arrays
* and objects.
*/
return error(Status.BAD_REQUEST, problems.build().toString());
}
// response.add("knows existing password", knowsExistingPassword);
}
response.add("user to convert", builtInUserToConvert.getIdentifier());
response.add("existing user found by email (prompt to convert)", existing);
response.add("changing to this provider", newProviderId);
response.add("value to overwrite old first name", overwriteFirstName);
response.add("value to overwrite old last name", overwriteLastName);
response.add("value to overwrite old email address", overwriteEmail);
if (overwriteAffiliation != null) {
response.add("affiliation", overwriteAffiliation);
}
response.add("problems", problems);
return ok(response);
}
@DELETE
@Path("authenticatedUsers/id/{id}/")
public Response deleteAuthenticatedUserById(@PathParam("id") Long id) {
AuthenticatedUser user = authSvc.findByID(id);
if (user != null) {
authSvc.deleteAuthenticatedUser(user.getId());
return ok("AuthenticatedUser " + id + " deleted. ");
}
return error(Response.Status.BAD_REQUEST, "User " + id + " not found.");
}
@Path("roles")
@POST
public Response createNewBuiltinRole(RoleDTO roleDto) {
ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.Admin, "createBuiltInRole")
.setInfo(roleDto.getAlias() + ":" + roleDto.getDescription());
try {
return ok(json(rolesSvc.save(roleDto.asRole())));
} catch (Exception e) {
alr.setActionResult(ActionLogRecord.Result.InternalError);
alr.setInfo(alr.getInfo() + "// " + e.getMessage());
return error(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
} finally {
actionLogSvc.log(alr);
}
}
@Path("roles")
@GET
public Response listBuiltinRoles() {
try {
return ok(rolesToJson(rolesSvc.findBuiltinRoles()));
} catch (Exception e) {
return error(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
@Path("superuser/{identifier}")
@POST
public Response toggleSuperuser(@PathParam("identifier") String identifier) {
ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.Admin, "toggleSuperuser")
.setInfo(identifier);
try {
AuthenticatedUser user = authSvc.getAuthenticatedUser(identifier);
user.setSuperuser(!user.isSuperuser());
return ok("User " + user.getIdentifier() + " " + (user.isSuperuser() ? "set" : "removed")
+ " as a superuser.");
} catch (Exception e) {
alr.setActionResult(ActionLogRecord.Result.InternalError);
alr.setInfo(alr.getInfo() + "// " + e.getMessage());
return error(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
} finally {
actionLogSvc.log(alr);
}
}
@GET
@Path("validate/datasets")
@Produces({"application/json"})
public Response validateAllDatasets(@QueryParam("variables") boolean includeVariables) {
// Streaming output: the API will start producing
// the output right away, as it goes through the list
// of the datasets; there's potentially a lot of content
// to validate, so we don't want to wait for the process
// to finish. Or to wait to encounter the first invalid
// object - so we'll be reporting both the success and failure
// outcomes for all the validated datasets, to give the user
// an indication of the progress.
// This is the first streaming API that produces json that
// we have; there may be better ways to stream json - but
// what I have put together below works. -- L.A.
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
os.write("{\"datasets\": [\n".getBytes());
boolean wroteObject = false;
for (Long datasetId : datasetService.findAllLocalDatasetIds()) {
// Potentially, there's a godzillion datasets in this Dataverse.
// This is why we go through the list of ids here, and instantiate
// only one dataset at a time.
boolean success = false;
boolean constraintViolationDetected = false;
JsonObjectBuilder output = Json.createObjectBuilder();
output.add("datasetId", datasetId);
try {
datasetService.instantiateDatasetInNewTransaction(datasetId, includeVariables);
success = true;
} catch (Exception ex) {
Throwable cause = ex;
while (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
for (ConstraintViolation<?> constraintViolation : constraintViolationException
.getConstraintViolations()) {
String databaseRow = constraintViolation.getLeafBean().toString();
String field = constraintViolation.getPropertyPath().toString();
String invalidValue = null;
if (constraintViolation.getInvalidValue() != null) {
invalidValue = constraintViolation.getInvalidValue().toString();
}
output.add("status", "invalid");
output.add("entityClassDatabaseTableRowId", databaseRow);
output.add("field", field);
output.add("invalidValue", invalidValue == null ? "NULL" : invalidValue);
constraintViolationDetected = true;
break;
}
}
cause = cause.getCause();
}
}
if (success) {
output.add("status", "valid");
} else if (!constraintViolationDetected) {
output.add("status", "unknown");
}
// write it out:
if (wroteObject) {
os.write(",\n".getBytes());
}
os.write(output.build().toString().getBytes("UTF8"));
if (!wroteObject) {
wroteObject = true;
}
}
os.write("\n]\n}\n".getBytes());
}
};
return Response.ok(stream).build();
}
@Path("validate/dataset/{id}")
@GET
public Response validateDataset(@PathParam("id") String id, @QueryParam("variables") boolean includeVariables) {
Dataset dataset;
try {
dataset = findDatasetOrDie(id);
} catch (Exception ex) {
return error(Response.Status.NOT_FOUND, "No Such Dataset");
}
Long dbId = dataset.getId();
String msg = "unknown";
try {
datasetService.instantiateDatasetInNewTransaction(dbId, includeVariables);
msg = "valid";
} catch (Exception ex) {
Throwable cause = ex;
while (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
for (ConstraintViolation<?> constraintViolation : constraintViolationException
.getConstraintViolations()) {
String databaseRow = constraintViolation.getLeafBean().toString();
String field = constraintViolation.getPropertyPath().toString();
String invalidValue = null;
if (constraintViolation.getInvalidValue() != null) {
invalidValue = constraintViolation.getInvalidValue().toString();
}
JsonObjectBuilder violation = Json.createObjectBuilder();
violation.add("entityClassDatabaseTableRowId", databaseRow);
violation.add("field", field);
violation.add("invalidValue", invalidValue == null ? "NULL" : invalidValue);
return ok(violation);
}
}
cause = cause.getCause();
}
}
return ok(msg);
}
@Path("assignments/assignees/{raIdtf: .*}")
@GET
public Response getAssignmentsFor(@PathParam("raIdtf") String raIdtf) {
JsonArrayBuilder arr = Json.createArrayBuilder();
roleAssigneeSvc.getAssignmentsFor(raIdtf).forEach(a -> arr.add(json(a)));
return ok(arr);
}