use of edu.harvard.iq.dataverse.authorization.UserRecordIdentifier in project dataverse by IQSS.
the class DataverseUserPage method save.
public String save() {
boolean passwordChanged = false;
if (editMode == EditMode.CHANGE_PASSWORD) {
final AuthenticationProvider prv = getUserAuthProvider();
if (prv.isPasswordUpdateAllowed()) {
if (!prv.verifyPassword(currentUser.getAuthenticatedUserLookup().getPersistentUserId(), currentPassword)) {
FacesContext.getCurrentInstance().addMessage("currentPassword", new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.error.wrongPassword"), null));
return null;
}
prv.updatePassword(currentUser.getAuthenticatedUserLookup().getPersistentUserId(), inputPassword);
passwordChanged = true;
} else {
// erroneous state - we can't change the password for this user, so should not have gotten here. Log and bail out.
logger.log(Level.WARNING, "Attempt to change a password on {0}, whose provider ({1}) does not support password change", new Object[] { currentUser.getIdentifier(), prv });
JH.addMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.error.cannotChangePassword"));
return null;
}
}
if (editMode == EditMode.CREATE) {
// Create a new built-in user.
BuiltinUser builtinUser = new BuiltinUser();
builtinUser.setUserName(getUsername());
builtinUser.applyDisplayInfo(userDisplayInfo);
builtinUser.updateEncryptedPassword(PasswordEncryption.get().encrypt(inputPassword), PasswordEncryption.getLatestVersionNumber());
AuthenticatedUser au = authenticationService.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, builtinUser.getUserName()), builtinUser.getUserName(), builtinUser.getDisplayInfo(), false);
if (au == null) {
// Username already exists, show an error message
getUsernameField().setValid(false);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.username.taken"), null);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(getUsernameField().getClientId(context), message);
return null;
}
// The Authenticated User was just created via the UI, add an initial login timestamp
au = userService.updateLastLogin(au);
// Authenticated user registered. Save the new bulitin, and log in.
builtinUserService.save(builtinUser);
session.setUser(au);
/**
* @todo Move this to
* AuthenticationServiceBean.createAuthenticatedUser
*/
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
// go back to where user came from
if ("dataverse.xhtml".equals(redirectPage)) {
redirectPage = redirectPage + "?alias=" + dataverseService.findRootDataverse().getAlias();
}
try {
redirectPage = URLDecoder.decode(redirectPage, "UTF-8");
} catch (UnsupportedEncodingException ex) {
logger.log(Level.SEVERE, "Server does not support 'UTF-8' encoding.", ex);
redirectPage = "dataverse.xhtml?alias=" + dataverseService.findRootDataverse().getAlias();
}
logger.log(Level.FINE, "Sending user to = {0}", redirectPage);
return redirectPage + (!redirectPage.contains("?") ? "?" : "&") + "faces-redirect=true";
// Happens if user is logged out while editing
} else if (!session.getUser().isAuthenticated()) {
logger.info("Redirecting");
return permissionsWrapper.notAuthorized() + "faces-redirect=true";
} else {
String emailBeforeUpdate = currentUser.getEmail();
AuthenticatedUser savedUser = authenticationService.updateAuthenticatedUser(currentUser, userDisplayInfo);
String emailAfterUpdate = savedUser.getEmail();
editMode = null;
StringBuilder msg = new StringBuilder(passwordChanged ? "Your account password has been successfully changed." : "Your account information has been successfully updated.");
if (!emailBeforeUpdate.equals(emailAfterUpdate)) {
String expTime = ConfirmEmailUtil.friendlyExpirationTime(systemConfig.getMinutesUntilConfirmEmailTokenExpires());
msg.append(" Your email address has changed and must be re-verified. Please check your inbox at ").append(currentUser.getEmail()).append(" and follow the link we've sent. \n\nAlso, please note that the link will only work for the next ").append(expTime).append(" before it has expired.");
// delete unexpired token, if it exists (clean slate)
confirmEmailService.deleteTokenForUser(currentUser);
try {
confirmEmailService.beginConfirm(currentUser);
} catch (ConfirmEmailException ex) {
logger.log(Level.INFO, "Unable to send email confirmation link to user id {0}", savedUser.getId());
}
session.setUser(currentUser);
JsfHelper.addSuccessMessage(msg.toString());
} else {
JsfHelper.addFlashMessage(msg.toString());
}
return null;
}
}
use of edu.harvard.iq.dataverse.authorization.UserRecordIdentifier in project dataverse by IQSS.
the class Shib method confirmAndCreateAccount.
public String confirmAndCreateAccount() {
ShibAuthenticationProvider shibAuthProvider = new ShibAuthenticationProvider();
String lookupStringPerAuthProvider = userPersistentId;
AuthenticatedUser au = null;
try {
au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(shibAuthProvider.getId(), lookupStringPerAuthProvider), internalUserIdentifer, displayInfo, true);
} catch (EJBException ex) {
/**
* @todo Show the ConstraintViolationException, if any.
*/
logger.info("Couldn't create user " + userPersistentId + " due to exception: " + ex.getCause());
}
if (au != null) {
logger.fine("created user " + au.getIdentifier());
logInUserAndSetShibAttributes(au);
/**
* @todo Move this to
* AuthenticationServiceBean.createAuthenticatedUser
*/
userNotificationService.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
return "/dataverseuser.xhtml?selectTab=accountInfo&faces-redirect=true";
} else {
JsfHelper.addErrorMessage("Couldn't create user.");
}
return getPrettyFacesHomePageString(true);
}
use of edu.harvard.iq.dataverse.authorization.UserRecordIdentifier in project dataverse by IQSS.
the class Admin method createAuthenicatedUser.
/**
* @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));
}
use of edu.harvard.iq.dataverse.authorization.UserRecordIdentifier in project dataverse by IQSS.
the class BuiltinUsers method internalSave.
private Response internalSave(BuiltinUser user, String password, String key) {
String expectedKey = settingsSvc.get(API_KEY_IN_SETTINGS);
if (expectedKey == null) {
return error(Status.SERVICE_UNAVAILABLE, "Dataverse config issue: No API key defined for built in user management");
}
if (!expectedKey.equals(key)) {
return badApiKey(key);
}
ActionLogRecord alr = new ActionLogRecord(ActionLogRecord.ActionType.BuiltinUser, "create");
try {
if (password != null) {
user.updateEncryptedPassword(PasswordEncryption.get().encrypt(password), PasswordEncryption.getLatestVersionNumber());
}
// Make sure the identifier is unique
if ((builtinUserSvc.findByUserName(user.getUserName()) != null) || (authSvc.identifierExists(user.getUserName()))) {
return error(Status.BAD_REQUEST, "username '" + user.getUserName() + "' already exists");
}
user = builtinUserSvc.save(user);
AuthenticatedUser au = authSvc.createAuthenticatedUser(new UserRecordIdentifier(BuiltinAuthenticationProvider.PROVIDER_ID, user.getUserName()), user.getUserName(), user.getDisplayInfo(), false);
/**
* @todo Move this to
* AuthenticationServiceBean.createAuthenticatedUser
*/
boolean rootDataversePresent = false;
try {
Dataverse rootDataverse = dataverseSvc.findRootDataverse();
if (rootDataverse != null) {
rootDataversePresent = true;
}
} catch (Exception e) {
logger.info("The root dataverse is not present. Don't send a notification to dataverseAdmin.");
}
if (rootDataversePresent) {
userNotificationSvc.sendNotification(au, new Timestamp(new Date().getTime()), UserNotification.Type.CREATEACC, null);
}
ApiToken token = new ApiToken();
token.setTokenString(java.util.UUID.randomUUID().toString());
token.setAuthenticatedUser(au);
Calendar c = Calendar.getInstance();
token.setCreateTime(new Timestamp(c.getTimeInMillis()));
c.roll(Calendar.YEAR, 1);
token.setExpireTime(new Timestamp(c.getTimeInMillis()));
authSvc.save(token);
JsonObjectBuilder resp = Json.createObjectBuilder();
resp.add("user", json(user));
resp.add("authenticatedUser", json(au));
resp.add("apiToken", token.getTokenString());
alr.setInfo("builtinUser:" + user.getUserName() + " authenticatedUser:" + au.getIdentifier());
return ok(resp);
} catch (EJBException ejbx) {
alr.setActionResult(ActionLogRecord.Result.InternalError);
alr.setInfo(alr.getInfo() + "// " + ejbx.getMessage());
if (ejbx.getCausedByException() instanceof IllegalArgumentException) {
return error(Status.BAD_REQUEST, "Bad request: can't save user. " + ejbx.getCausedByException().getMessage());
} else {
logger.log(Level.WARNING, "Error saving user: ", ejbx);
return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + ejbx.getMessage());
}
} catch (Exception e) {
logger.log(Level.WARNING, "Error saving user", e);
alr.setActionResult(ActionLogRecord.Result.InternalError);
alr.setInfo(alr.getInfo() + "// " + e.getMessage());
return error(Status.INTERNAL_SERVER_ERROR, "Can't save user: " + e.getMessage());
} finally {
actionLogSvc.log(alr);
}
}
use of edu.harvard.iq.dataverse.authorization.UserRecordIdentifier in project dataverse by IQSS.
the class OAuth2LoginBackingBean method exchangeCodeForToken.
public void exchangeCodeForToken() throws IOException {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
final String code = req.getParameter("code");
if (code == null || code.trim().isEmpty()) {
try (BufferedReader rdr = req.getReader()) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = rdr.readLine()) != null) {
sb.append(line).append("\n");
}
error = new OAuth2Exception(-1, sb.toString(), "Remote system did not return an authorization code.");
logger.log(Level.INFO, "OAuth2Exception getting code parameter. HTTP return code: {0}. Message: {1} Message body: {2}", new Object[] { error.getHttpReturnCode(), error.getLocalizedMessage(), error.getMessageBody() });
return;
}
}
final String state = req.getParameter("state");
try {
AbstractOAuth2AuthenticationProvider idp = parseState(state);
if (idp == null) {
throw new OAuth2Exception(-1, "", "Invalid 'state' parameter.");
}
oauthUser = idp.getUserRecord(code, state, getCallbackUrl());
UserRecordIdentifier idtf = oauthUser.getUserRecordIdentifier();
AuthenticatedUser dvUser = authenticationSvc.lookupUser(idtf);
if (dvUser == null) {
// need to create the user
newAccountPage.setNewUser(oauthUser);
FacesContext.getCurrentInstance().getExternalContext().redirect("/oauth2/firstLogin.xhtml");
} else {
// login the user and redirect to HOME of intended page (if any).
session.setUser(dvUser);
final OAuth2TokenData tokenData = oauthUser.getTokenData();
tokenData.setUser(dvUser);
tokenData.setOauthProviderId(idp.getId());
oauth2Tokens.store(tokenData);
String destination = redirectPage.orElse("/");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
String prettyUrl = response.encodeRedirectURL(destination);
FacesContext.getCurrentInstance().getExternalContext().redirect(prettyUrl);
}
} catch (OAuth2Exception ex) {
error = ex;
logger.log(Level.INFO, "OAuth2Exception caught. HTTP return code: {0}. Message: {1}. Message body: {2}", new Object[] { error.getHttpReturnCode(), error.getLocalizedMessage(), error.getMessageBody() });
Logger.getLogger(OAuth2LoginBackingBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
Aggregations