use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class AuthenticationServiceBean method convertRemoteToBuiltIn.
/**
* @param idOfAuthUserToConvert The id of the remote AuthenticatedUser
* (Shibboleth user or OAuth user) to convert to a BuiltinUser.
* @param newEmailAddress The new email address that will be used instead of
* the user's old email address from the institution that they have left.
* @return BuiltinUser
* @throws java.lang.Exception You must catch and report back to the user (a
* superuser) any Exceptions.
*/
public BuiltinUser convertRemoteToBuiltIn(Long idOfAuthUserToConvert, String newEmailAddress) throws Exception {
AuthenticatedUser authenticatedUser = findByID(idOfAuthUserToConvert);
if (authenticatedUser == null) {
throw new Exception("User id " + idOfAuthUserToConvert + " not found.");
}
AuthenticatedUser existingUserWithSameEmail = getAuthenticatedUserByEmail(newEmailAddress);
if (existingUserWithSameEmail != null) {
throw new Exception("User id " + idOfAuthUserToConvert + " (" + authenticatedUser.getIdentifier() + ") cannot be converted from remote to BuiltIn because the email address " + newEmailAddress + " is already in use by user id " + existingUserWithSameEmail.getId() + " (" + existingUserWithSameEmail.getIdentifier() + ").");
}
BuiltinUser builtinUser = new BuiltinUser();
builtinUser.setUserName(authenticatedUser.getUserIdentifier());
builtinUser.setFirstName(authenticatedUser.getFirstName());
builtinUser.setLastName(authenticatedUser.getLastName());
// Bean Validation will check for null and invalid email addresses
builtinUser.setEmail(newEmailAddress);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<BuiltinUser>> violations = validator.validate(builtinUser);
int numViolations = violations.size();
if (numViolations > 0) {
StringBuilder logMsg = new StringBuilder();
for (ConstraintViolation<?> violation : violations) {
logMsg.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
}
throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because of constraint violations on the BuiltIn user that would be created: " + numViolations + ". Details: " + logMsg);
}
try {
builtinUser = builtinUserServiceBean.save(builtinUser);
} catch (IllegalArgumentException ex) {
throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because of an IllegalArgumentException creating the row in the builtinuser table: " + ex);
}
AuthenticatedUserLookup lookup = authenticatedUser.getAuthenticatedUserLookup();
if (lookup == null) {
throw new Exception("User id " + idOfAuthUserToConvert + " does not have an 'authenticateduserlookup' row");
}
String providerId = lookup.getAuthenticationProviderId();
if (providerId == null) {
throw new Exception("User id " + idOfAuthUserToConvert + " provider id is null.");
}
String builtinProviderId = BuiltinAuthenticationProvider.PROVIDER_ID;
if (providerId.equals(builtinProviderId)) {
throw new Exception("User id " + idOfAuthUserToConvert + " cannot be converted from remote to BuiltIn because current provider id is '" + providerId + "' which is the same as '" + builtinProviderId + "'. This user is already a BuiltIn user.");
}
lookup.setAuthenticationProviderId(BuiltinAuthenticationProvider.PROVIDER_ID);
lookup.setPersistentUserId(authenticatedUser.getUserIdentifier());
em.persist(lookup);
authenticatedUser.setEmail(newEmailAddress);
em.persist(authenticatedUser);
em.flush();
return builtinUser;
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class AuthenticationServiceBean method getCreateAuthenticatedUser.
/**
* Returns an {@link AuthenticatedUser} matching the passed provider id and the authentication request. If
* no such user exist, it is created and then returned.
*
* <strong>Invariant:</strong> upon successful return from this call, an {@link AuthenticatedUser} record
* matching the request and provider exists in the database.
*
* @param authenticationProviderId
* @param req
* @return The authenticated user for the passed provider id and authentication request.
* @throws AuthenticationFailedException
*/
public AuthenticatedUser getCreateAuthenticatedUser(String authenticationProviderId, AuthenticationRequest req) throws AuthenticationFailedException {
AuthenticationProvider prv = getAuthenticationProvider(authenticationProviderId);
if (prv == null)
throw new IllegalArgumentException("No authentication provider listed under id " + authenticationProviderId);
if (!(prv instanceof CredentialsAuthenticationProvider)) {
throw new IllegalArgumentException(authenticationProviderId + " does not support credentials-based authentication.");
}
AuthenticationResponse resp = ((CredentialsAuthenticationProvider) prv).authenticate(req);
if (resp.getStatus() == AuthenticationResponse.Status.SUCCESS) {
// yay! see if we already have this user.
AuthenticatedUser user = lookupUser(authenticationProviderId, resp.getUserId());
if (user != null) {
user = userService.updateLastLogin(user);
}
if (user == null) {
return createAuthenticatedUser(new UserRecordIdentifier(authenticationProviderId, resp.getUserId()), resp.getUserId(), resp.getUserDisplayInfo(), true);
} else {
if (BuiltinAuthenticationProvider.PROVIDER_ID.equals(user.getAuthenticatedUserLookup().getAuthenticationProviderId())) {
return user;
} else {
return updateAuthenticatedUser(user, resp.getUserDisplayInfo());
}
}
} else {
throw new AuthenticationFailedException(resp, "Authentication Failed: " + resp.getMessage());
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class AuthenticationServiceBean method createAuthenticatedUser.
/**
* Creates an authenticated user based on the passed
* {@code userDisplayInfo}, a lookup entry for them based
* UserIdentifier.getLookupStringPerAuthProvider (within the supplied
* authentication provider), and internal user identifier (used for role
* assignments, etc.) based on UserIdentifier.getInternalUserIdentifer.
*
* @param userRecordId
* @param proposedAuthenticatedUserIdentifier
* @param userDisplayInfo
* @param generateUniqueIdentifier if {@code true}, create a new, unique user identifier for the created user, if the suggested one exists.
* @return the newly created user, or {@code null} if the proposed identifier exists and {@code generateUniqueIdentifier} was {@code false}.
* @throws EJBException which may wrap an ConstraintViolationException if the proposed user does not pass bean validation.
*/
public AuthenticatedUser createAuthenticatedUser(UserRecordIdentifier userRecordId, String proposedAuthenticatedUserIdentifier, AuthenticatedUserDisplayInfo userDisplayInfo, boolean generateUniqueIdentifier) {
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
// set account creation time & initial login time (same timestamp)
authenticatedUser.setCreatedTime(new Timestamp(new Date().getTime()));
authenticatedUser.setLastLoginTime(authenticatedUser.getCreatedTime());
authenticatedUser.applyDisplayInfo(userDisplayInfo);
// we have no desire for leading or trailing whitespace in identifiers
if (proposedAuthenticatedUserIdentifier != null) {
proposedAuthenticatedUserIdentifier = proposedAuthenticatedUserIdentifier.trim();
}
// we now select a username for the generated AuthenticatedUser, or give up
String internalUserIdentifer = proposedAuthenticatedUserIdentifier;
// TODO should lock table authenticated users for write here
if (identifierExists(internalUserIdentifer)) {
if (!generateUniqueIdentifier) {
return null;
}
int i = 1;
String identifier = internalUserIdentifer + i;
while (identifierExists(identifier)) {
i += 1;
}
authenticatedUser.setUserIdentifier(identifier);
} else {
authenticatedUser.setUserIdentifier(internalUserIdentifer);
}
authenticatedUser = save(authenticatedUser);
// TODO should unlock table authenticated users for write here
AuthenticatedUserLookup auusLookup = userRecordId.createAuthenticatedUserLookup(authenticatedUser);
em.persist(auusLookup);
authenticatedUser.setAuthenticatedUserLookup(auusLookup);
if (ShibAuthenticationProvider.PROVIDER_ID.equals(auusLookup.getAuthenticationProviderId())) {
Timestamp emailConfirmedNow = new Timestamp(new Date().getTime());
// Email addresses for Shib users are confirmed by the Identity Provider.
authenticatedUser.setEmailConfirmed(emailConfirmedNow);
authenticatedUser = save(authenticatedUser);
} else {
/* @todo Rather than creating a token directly here it might be
* better to do something like "startConfirmEmailProcessForNewUser". */
confirmEmailService.createToken(authenticatedUser);
}
actionLogSvc.log(new ActionLogRecord(ActionLogRecord.ActionType.Auth, "createUser").setInfo(authenticatedUser.getIdentifier()));
return authenticatedUser;
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class Dataverses method addDataverse.
@POST
@Path("{identifier}")
public Response addDataverse(String body, @PathParam("identifier") String parentIdtf) {
Dataverse d;
JsonObject dvJson;
try (StringReader rdr = new StringReader(body)) {
dvJson = Json.createReader(rdr).readObject();
d = jsonParser().parseDataverse(dvJson);
} catch (JsonParsingException jpe) {
LOGGER.log(Level.SEVERE, "Json: {0}", body);
return error(Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
} catch (JsonParseException ex) {
Logger.getLogger(Dataverses.class.getName()).log(Level.SEVERE, "Error parsing dataverse from json: " + ex.getMessage(), ex);
return error(Response.Status.BAD_REQUEST, "Error parsing the POSTed json into a dataverse: " + ex.getMessage());
}
try {
if (!parentIdtf.isEmpty()) {
Dataverse owner = findDataverseOrDie(parentIdtf);
d.setOwner(owner);
}
// set the dataverse - contact relationship in the contacts
for (DataverseContact dc : d.getDataverseContacts()) {
dc.setDataverse(d);
}
AuthenticatedUser u = findAuthenticatedUserOrDie();
d = execCommand(new CreateDataverseCommand(d, createDataverseRequest(u), null, null));
return created("/dataverses/" + d.getAlias(), json(d));
} catch (WrappedResponse ww) {
Throwable cause = ww.getCause();
StringBuilder sb = new StringBuilder();
if (cause == null) {
return ww.refineResponse("cause was null!");
}
while (cause.getCause() != null) {
cause = cause.getCause();
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());
}
}
}
String error = sb.toString();
if (!error.isEmpty()) {
LOGGER.log(Level.INFO, error);
return ww.refineResponse(error);
}
return ww.getResponse();
} catch (EJBException ex) {
Throwable cause = ex;
StringBuilder sb = new StringBuilder();
sb.append("Error creating dataverse.");
while (cause.getCause() != null) {
cause = cause.getCause();
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.log(Level.SEVERE, sb.toString());
return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + sb.toString());
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Error creating dataverse", ex);
return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + ex.getMessage());
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class HarvestingClients method startHarvestingJob.
// TODO:
// add a @DELETE method
// (there is already a DeleteHarvestingClient command)
// Methods for managing harvesting runs (jobs):
// This POST starts a new harvesting run:
@POST
@Path("{nickName}/run")
public Response startHarvestingJob(@PathParam("nickName") String clientNickname, @QueryParam("key") String apiKey) throws IOException {
try {
AuthenticatedUser authenticatedUser = null;
try {
authenticatedUser = findAuthenticatedUserOrDie();
} catch (WrappedResponse wr) {
return error(Response.Status.UNAUTHORIZED, "Authentication required to use this API method");
}
if (authenticatedUser == null || !authenticatedUser.isSuperuser()) {
return error(Response.Status.FORBIDDEN, "Only the Dataverse Admin user can run harvesting jobs");
}
HarvestingClient harvestingClient = harvestingClientService.findByNickname(clientNickname);
if (harvestingClient == null) {
return error(Response.Status.NOT_FOUND, "No such dataverse: " + clientNickname);
}
DataverseRequest dataverseRequest = createDataverseRequest(authenticatedUser);
harvesterService.doAsyncHarvest(dataverseRequest, harvestingClient);
} catch (Exception e) {
return this.error(Response.Status.BAD_REQUEST, "Exception thrown when running harvesting client\"" + clientNickname + "\" via REST API; " + e.getMessage());
}
return this.accepted();
}
Aggregations