use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class CollectionDepositManagerImpl method createNew.
@Override
public DepositReceipt createNew(String collectionUri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration config) throws SwordError, SwordServerException, SwordAuthException {
AuthenticatedUser user = swordAuth.auth(authCredentials);
DataverseRequest dvReq = new DataverseRequest(user, request);
urlManager.processUrl(collectionUri);
String dvAlias = urlManager.getTargetIdentifier();
if (urlManager.getTargetType().equals("dataverse") && dvAlias != null) {
logger.log(Level.FINE, "attempting deposit into this dataverse alias: {0}", dvAlias);
Dataverse dvThatWillOwnDataset = dataverseService.findByAlias(dvAlias);
if (dvThatWillOwnDataset != null) {
logger.log(Level.FINE, "multipart: {0}", deposit.isMultipart());
logger.log(Level.FINE, "binary only: {0}", deposit.isBinaryOnly());
logger.log(Level.FINE, "entry only: {0}", deposit.isEntryOnly());
logger.log(Level.FINE, "in progress: {0}", deposit.isInProgress());
logger.log(Level.FINE, "metadata relevant: {0}", deposit.isMetadataRelevant());
if (deposit.isEntryOnly()) {
// do a sanity check on the XML received
try {
SwordEntry swordEntry = deposit.getSwordEntry();
logger.log(Level.FINE, "deposit XML received by createNew():\n{0}", swordEntry.toString());
} catch (ParseException ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Can not create dataset due to malformed Atom entry: " + ex);
}
Dataset dataset = new Dataset();
dataset.setOwner(dvThatWillOwnDataset);
String nonNullDefaultIfKeyNotFound = "";
String protocol = settingsService.getValueForKey(SettingsServiceBean.Key.Protocol, nonNullDefaultIfKeyNotFound);
String authority = settingsService.getValueForKey(SettingsServiceBean.Key.Authority, nonNullDefaultIfKeyNotFound);
String separator = settingsService.getValueForKey(SettingsServiceBean.Key.DoiSeparator, nonNullDefaultIfKeyNotFound);
dataset.setProtocol(protocol);
dataset.setAuthority(authority);
dataset.setDoiSeparator(separator);
// Wait until the create command before actually getting an identifier
// dataset.setIdentifier(datasetService.generateDatasetIdentifier(protocol, authority, separator));
logger.log(Level.FINE, "DS Deposit identifier: {0}", dataset.getIdentifier());
CreateDatasetCommand createDatasetCommand = new CreateDatasetCommand(dataset, dvReq, false);
if (!permissionService.isUserAllowedOn(user, createDatasetCommand, dataset)) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to create a dataset in this dataverse.");
}
DatasetVersion newDatasetVersion = dataset.getEditVersion();
String foreignFormat = SwordUtil.DCTERMS;
try {
importGenericService.importXML(deposit.getSwordEntry().toString(), foreignFormat, newDatasetVersion);
} catch (Exception ex) {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "problem calling importXML: " + ex);
}
swordService.addDatasetContact(newDatasetVersion, user);
swordService.addDatasetDepositor(newDatasetVersion, user);
swordService.addDatasetSubjectIfMissing(newDatasetVersion);
swordService.setDatasetLicenseAndTermsOfUse(newDatasetVersion, deposit.getSwordEntry());
Dataset createdDataset = null;
try {
createdDataset = engineSvc.submit(createDatasetCommand);
} catch (EJBException | CommandException ex) {
Throwable cause = ex;
StringBuilder sb = new StringBuilder();
sb.append(ex.getLocalizedMessage());
while (cause.getCause() != null) {
cause = cause.getCause();
/**
* @todo move this ConstraintViolationException
* check to CreateDatasetCommand. Can be triggered
* if you don't call dataset.setIdentifier() or if
* you feed it date format we don't like. Once this
* is done we should be able to drop EJBException
* from the catch above and only catch
* CommandException
*
* See also Have commands catch
* ConstraintViolationException and turn them into
* something that inherits from CommandException ·
* Issue #1009 · IQSS/dataverse -
* https://github.com/IQSS/dataverse/issues/1009
*/
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
sb.append(" Invalid value: '").append(violation.getInvalidValue()).append("' for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
}
}
}
logger.info(sb.toString());
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Couldn't create dataset: " + sb.toString());
}
if (createdDataset != null) {
ReceiptGenerator receiptGenerator = new ReceiptGenerator();
String baseUrl = urlManager.getHostnamePlusBaseUrlPath(collectionUri);
DepositReceipt depositReceipt = receiptGenerator.createDatasetReceipt(baseUrl, createdDataset);
return depositReceipt;
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem creating dataset. Null returned.");
}
} else if (deposit.isBinaryOnly()) {
// curl --insecure -s --data-binary "@example.zip" -H "Content-Disposition: filename=example.zip" -H "Content-Type: application/zip" https://sword:sword@localhost:8181/dvn/api/data-deposit/v1/swordv2/collection/dataverse/sword/
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Binary deposit to the collection IRI via POST is not supported. Please POST an Atom entry instead.");
} else if (deposit.isMultipart()) {
// "Yeah, multipart is critically broken across all implementations" -- http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00327.html
throw new UnsupportedOperationException("Not yet implemented");
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "expected deposit types are isEntryOnly, isBinaryOnly, and isMultiPart");
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find dataverse: " + dvAlias);
}
} else {
throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine target type or identifier from URL: " + collectionUri);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Admin method convertOAuthUserToBuiltin.
@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);
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.");
}
JsonObjectBuilder output = Json.createObjectBuilder();
output.add("email", builtinUser.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);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Admin method builtin2shib.
/**
* 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;
// could let people specify id on authuser table. probably better to let them tell us their
String authuserId = "0";
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);
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Admin method toggleSuperuser.
@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);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Admin method listAuthenticatedUsers.
@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);
}
Aggregations