use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class CreateRoleCommandTest method testSuperUsersAddRoles.
@Test
public void testSuperUsersAddRoles() throws CommandException {
DataverseRole dvr = new DataverseRole();
dvr.setAlias("roleTest");
dvr.setName("Tester Role");
dvr.addPermission(Permission.AddDataset);
Dataverse dv = MocksFactory.makeDataverse();
dvr.setOwner(dv);
AuthenticatedUser normalUser = new AuthenticatedUser();
normalUser.setSuperuser(true);
CreateRoleCommand sut = new CreateRoleCommand(dvr, new DataverseRequest(normalUser, IpAddress.valueOf("89.17.33.33")), dv);
engine.submit(sut);
assertTrue("CreateRoleCommand did not call save on the created role.", saveCalled);
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class DataverseUserPage method validateUserEmail.
public void validateUserEmail(FacesContext context, UIComponent toValidate, Object value) {
String userEmail = (String) value;
boolean emailValid = EMailValidator.isEmailValid(userEmail, null);
if (!emailValid) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("oauth2.newAccount.emailInvalid"), null);
context.addMessage(toValidate.getClientId(context), message);
logger.info("Email is not valid: " + userEmail);
return;
}
boolean userEmailFound = false;
AuthenticatedUser aUser = authenticationService.getAuthenticatedUserByEmail(userEmail);
if (editMode == EditMode.CREATE) {
if (aUser != null) {
userEmailFound = true;
}
} else {
// user doing the editing by checking ids
if (aUser != null && !aUser.getId().equals(currentUser.getId())) {
userEmailFound = true;
}
}
if (userEmailFound) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, BundleUtil.getStringFromBundle("user.email.taken"), null);
context.addMessage(toValidate.getClientId(context), message);
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser 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.users.AuthenticatedUser in project dataverse by IQSS.
the class AuthenticationServiceBean method canLogInAsBuiltinUser.
public AuthenticatedUser canLogInAsBuiltinUser(String username, String password) {
logger.fine("checking to see if " + username + " knows the password...");
if (password == null) {
logger.info("password was null");
return null;
}
AuthenticationRequest authReq = new AuthenticationRequest();
/**
* @todo Should this really be coming from a bundle like this? Added
* because that's what BuiltinAuthenticationProvider does.
*/
authReq.putCredential(BundleUtil.getStringFromBundle("login.builtin.credential.usernameOrEmail"), username);
authReq.putCredential(BundleUtil.getStringFromBundle("login.builtin.credential.password"), password);
/**
* @todo Should probably set IP address here.
*/
// authReq.setIpAddress(session.getUser().getRequestMetadata().getIpAddress());
String credentialsAuthProviderId = BuiltinAuthenticationProvider.PROVIDER_ID;
try {
AuthenticatedUser au = getCreateAuthenticatedUser(credentialsAuthProviderId, authReq);
logger.fine("User authenticated:" + au.getEmail());
return au;
} catch (AuthenticationFailedException ex) {
logger.info("The username and/or password entered is invalid: " + ex.getResponse().getMessage());
if (AuthenticationResponse.Status.BREAKOUT.equals(ex.getResponse().getStatus())) {
/**
* Note that this "BREAKOUT" status creates PasswordResetData!
* We'll delete it just before blowing away the BuiltinUser in
* AuthenticationServiceBean.convertBuiltInToShib
*/
logger.info("AuthenticationFailedException caught in canLogInAsBuiltinUser: The username and/or password entered is invalid: " + ex.getResponse().getMessage() + " - Maybe the user (" + username + ") hasn't upgraded their password? Checking the old password...");
BuiltinUser builtinUser = builtinUserServiceBean.findByUsernameOrEmail(username);
if (builtinUser != null) {
boolean userAuthenticated = PasswordEncryption.getVersion(builtinUser.getPasswordEncryptionVersion()).check(password, builtinUser.getEncryptedPassword());
if (userAuthenticated == true) {
AuthenticatedUser authUser = lookupUser(BuiltinAuthenticationProvider.PROVIDER_ID, builtinUser.getUserName());
if (authUser != null) {
return authUser;
} else {
logger.info("canLogInAsBuiltinUser: Couldn't find AuthenticatedUser based on BuiltinUser username " + builtinUser.getUserName());
}
} else {
logger.info("canLogInAsBuiltinUser: User doesn't know old pre-bcrypt password either.");
}
} else {
logger.info("canLogInAsBuiltinUser: Couldn't run `check` because no BuiltinUser found with username " + username);
}
}
return null;
} catch (EJBException ex) {
Throwable cause = ex;
StringBuilder sb = new StringBuilder();
sb.append(ex + " ");
while (cause.getCause() != null) {
cause = cause.getCause();
sb.append(cause.getClass().getCanonicalName() + " ");
sb.append(cause.getMessage()).append(" ");
/**
* @todo Investigate why authSvc.authenticate is throwing
* NullPointerException. If you convert a Shib user or an OAuth
* user to a Builtin user, the password will be null.
*/
if (cause instanceof NullPointerException) {
for (int i = 0; i < 2; i++) {
StackTraceElement stacktrace = cause.getStackTrace()[i];
if (stacktrace != null) {
String classCanonicalName = stacktrace.getClass().getCanonicalName();
String methodName = stacktrace.getMethodName();
int lineNumber = stacktrace.getLineNumber();
String error = "at " + stacktrace.getClassName() + "." + stacktrace.getMethodName() + "(" + stacktrace.getFileName() + ":" + lineNumber + ") ";
sb.append(error);
}
}
}
}
logger.info("When trying to validate password, exception calling authSvc.authenticate: " + sb.toString());
return null;
}
}
use of edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser in project dataverse by IQSS.
the class AuthenticationServiceBean method deleteAuthenticatedUser.
/**
* Use with care! This method was written primarily for developers
* interested in API testing who want to:
*
* 1. Create a temporary user and get an API token.
*
* 2. Do some work with that API token.
*
* 3. Delete all the stuff that was created with the API token.
*
* 4. Delete the temporary user.
*
* Before calling this method, make sure you've deleted all the stuff tied
* to the user, including stuff they've created, role assignments, group
* assignments, etc.
*
* Longer term, the intention is to have a "disableAuthenticatedUser"
* method/command. See https://github.com/IQSS/dataverse/issues/2419
*/
public void deleteAuthenticatedUser(Object pk) {
AuthenticatedUser user = em.find(AuthenticatedUser.class, pk);
if (user != null) {
ApiToken apiToken = findApiTokenByUser(user);
if (apiToken != null) {
em.remove(apiToken);
}
ConfirmEmailData confirmEmailData = confirmEmailService.findSingleConfirmEmailDataByUser(user);
if (confirmEmailData != null) {
/**
* @todo This could probably be a cascade delete instead.
*/
em.remove(confirmEmailData);
}
userNotificationService.findByUser(user.getId()).forEach(userNotificationService::delete);
AuthenticationProvider prv = lookupProvider(user);
if (prv != null && prv.isUserDeletionAllowed()) {
prv.deleteUser(user.getAuthenticatedUserLookup().getPersistentUserId());
}
actionLogSvc.log(new ActionLogRecord(ActionLogRecord.ActionType.Auth, "deleteUser").setInfo(user.getUserIdentifier()));
em.remove(user.getAuthenticatedUserLookup());
em.remove(user);
}
}
Aggregations