diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index f73c295..a5a5269 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -11,6 +11,9 @@ + + uses + diff --git a/pom.xml b/pom.xml index aafba99..d5f638e 100644 --- a/pom.xml +++ b/pom.xml @@ -46,6 +46,31 @@ + + org.gcube.common + event-publisher-library + provided + + + org.gcube.portal + event-publisher-portal + provided + + + org.gcube.common + storagehub-client-library + 1.3.0 + + + org.gcube.portal + oidc-library-portal + provided + + + com.googlecode.json-simple + json-simple + provided + org.gcube.dvos usermanagement-core @@ -64,6 +89,21 @@ org.gcube.core common-encryption + + org.gcube.portal + social-networking-library + provided + + + org.gcube.portal + invites-common-library + [1.4.0-SNAPSHOT, 2.0.0-SNAPSHOT) + + + org.gcube.portal.mailing + email-templates-library + [1.4.3-SNAPSHOT, 2.0.0-SNAPSHOT) + com.liferay.portal portal-service diff --git a/src/main/java/org/gcube/portlets/user/moving/CompileForm.java b/src/main/java/org/gcube/portlets/user/moving/CompileForm.java index 79b0dd7..16a0a98 100644 --- a/src/main/java/org/gcube/portlets/user/moving/CompileForm.java +++ b/src/main/java/org/gcube/portlets/user/moving/CompileForm.java @@ -127,8 +127,8 @@ public class CompileForm extends MVCPortlet { Connection conn = DatabaseConnection.getInstance("/"+PortalContext.getConfiguration().getInfrastructureName()).getConnection(); String insertTableSQL = "INSERT INTO forms(name, surname, organisation, organisation_type, email, " + "country, activities_participation, main_motivation, elaborated_motivation, area_of_expertise, " - + "elaborated_expertise, degree_of_participation, data_management, processed_form, user_accepted) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + + "elaborated_expertise, degree_of_participation, data_management, datecreated, processed_form, user_accepted) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,current_timestamp,?,?)"; PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL); preparedStatement.setString(1, name); diff --git a/src/main/java/org/gcube/portlets/user/moving/FilledForm.java b/src/main/java/org/gcube/portlets/user/moving/FilledForm.java index f025920..0e6dd12 100644 --- a/src/main/java/org/gcube/portlets/user/moving/FilledForm.java +++ b/src/main/java/org/gcube/portlets/user/moving/FilledForm.java @@ -1,6 +1,7 @@ package org.gcube.portlets.user.moving; import java.io.Serializable; +import java.sql.Timestamp; @SuppressWarnings("serial") public class FilledForm implements Serializable { @@ -19,13 +20,17 @@ public class FilledForm implements Serializable { private String elaborated_expertise; private String degree_of_participation; private boolean data_management; + private Timestamp dateCreated; private boolean processed_form; private boolean user_accepted; - public FilledForm(long id, String name, String surname, String organisation, String organisationTyp, String emailAddress, - String areaOfExpertise, String country, boolean participatedInActivities, String mainMotivation, - String textareaMotivation, String elaborated_expertise, String degree_of_participation, - boolean data_management, boolean processed_form, boolean user_accepted) { + + + public FilledForm(long id, String name, String surname, String organisation, String organisationTyp, + String emailAddress, String areaOfExpertise, String country, boolean participatedInActivities, + String mainMotivation, String textareaMotivation, String elaborated_expertise, + String degree_of_participation, boolean data_management, Timestamp dateCreated, boolean processed_form, + boolean user_accepted) { super(); this.id = id; this.name = name; @@ -41,6 +46,7 @@ public class FilledForm implements Serializable { this.elaborated_expertise = elaborated_expertise; this.degree_of_participation = degree_of_participation; this.data_management = data_management; + this.dateCreated = dateCreated; this.processed_form = processed_form; this.user_accepted = user_accepted; } @@ -172,17 +178,27 @@ public class FilledForm implements Serializable { public void setUser_accepted(boolean user_accepted) { this.user_accepted = user_accepted; } + + + public Timestamp getDateCreated() { + return dateCreated; + } + + public void setDateCreated(Timestamp dateCreated) { + this.dateCreated = dateCreated; + } @Override public String toString() { - return "FilledForm [name=" + name + ", surname=" + surname + ", organisation=" + organisation + return "FilledForm [id=" + id + ", name=" + name + ", surname=" + surname + ", organisation=" + organisation + ", organisationTyp=" + organisationTyp + ", emailAddress=" + emailAddress + ", areaOfExpertise=" + areaOfExpertise + ", country=" + country + ", participatedInActivities=" + participatedInActivities + ", mainMotivation=" + mainMotivation + ", textareaMotivation=" + textareaMotivation + ", elaborated_expertise=" + elaborated_expertise + ", degree_of_participation=" - + degree_of_participation + ", data_management=" + data_management + ", processed_form=" - + processed_form + ", user_accepted=" + user_accepted + "]"; + + degree_of_participation + ", data_management=" + data_management + ", dateCreated=" + dateCreated + + ", processed_form=" + processed_form + ", user_accepted=" + user_accepted + "]"; } + diff --git a/src/main/java/org/gcube/portlets/user/moving/MConstants.java b/src/main/java/org/gcube/portlets/user/moving/MConstants.java new file mode 100644 index 0000000..285f3b1 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/moving/MConstants.java @@ -0,0 +1,33 @@ +package org.gcube.portlets.user.moving; + +public class MConstants { + + public static final String MAIL_SERVICE_HOST = "localhost"; + public static final String MAIL_SERVICE_PORT = "25"; + + public static final String MAIL_SUBJECT_FEEDBACK = "MOVING EU Multi-Actor Platform: Expression of Interest application feedback"; + + public static final String MAIL_BODY_REJECT = "Dear Sir/Madam,\n" + + "\n" + + "After a careful review and consideration of your expression of interest to join the MOVING EU-level Multi-Actor Platform (MAP), we regret to inform you that your request has not been granted. \n" + + "\n" + + "The MOVING EU MAP aims to form a dynamic and relevant community, ensuring a balanced representation of actors at different levels and covering a diversity of topics and knowledge relevant to the core objective of the project.\n" + + "\n" + + "If you would like to keep up to date with MOVING, please subscribe to our newsletter (https://mailchi.mp/4f25e203112c/movingnewsletter) or follow us online.\n" + + "\n" + + "Thank you for your interest.\n" + + "\n" + + "Best regards,\n" + + "MOVING team\n" + + ""; + + public static final String MAIL_BODY_ACCEPT = "Dear Sir/Madam,\n" + + "\n" + + "After a careful review and consideration of your expression of interest to join the MOVING EU-level Multi-Actor Platform (MAP), we are happy to inform you that your request has been accepted.\n" + + "\n" + + "You will soon receive an email with link to access the EU MAP set up on the Virtual Research Environment (VRE). \n" + + "\n" + + "Best regards,\n" + + "MOVING team\n"; + +} diff --git a/src/main/java/org/gcube/portlets/user/moving/ManageForms.java b/src/main/java/org/gcube/portlets/user/moving/ManageForms.java index 85f6185..974da7a 100644 --- a/src/main/java/org/gcube/portlets/user/moving/ManageForms.java +++ b/src/main/java/org/gcube/portlets/user/moving/ManageForms.java @@ -5,6 +5,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -19,12 +20,19 @@ import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; +import javax.portlet.ResourceRequest; +import javax.portlet.ResourceResponse; import javax.portlet.WindowState; +import javax.servlet.http.HttpServletRequest; import org.gcube.common.portal.PortalContext; +import org.gcube.portlets.user.moving.createaccounts.CreateUserAccount; +import com.liferay.portal.kernel.json.JSONFactoryUtil; +import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; /** @@ -32,34 +40,7 @@ import com.liferay.util.bridges.mvc.MVCPortlet; */ public class ManageForms extends MVCPortlet { private static com.liferay.portal.kernel.log.Log _log = LogFactoryUtil.getLog(ManageForms.class); - private String mailServiceHost = "localhost"; - private String mailServicePort = "25"; - - private static final String MAIL_SUBJECT = "MOVING EU Multi-Actor Platform: Expression of Interest application feedback"; - - private static final String MAIL_BODY_REJECT = "Dear Sir/Madam,\n" - + "\n" - + "After a careful review and consideration of your expression of interest to join the MOVING EU-level Multi-Actor Platform (MAP), we regret to inform you that your request has not been granted. \n" - + "\n" - + "The MOVING EU MAP aims to form a dynamic and relevant community, ensuring a balanced representation of actors at different levels and covering a diversity of topics and knowledge relevant to the core objective of the project.\n" - + "\n" - + "If you would like to keep up to date with MOVING, please subscribe to our newsletter (https://mailchi.mp/4f25e203112c/movingnewsletter) or follow us online.\n" - + "\n" - + "Thank you for your interest.\n" - + "\n" - + "Best regards,\n" - + "MOVING team\n" - + ""; - - private static final String MAIL_BODY_ACCEPT = "Dear Sir/Madam,\n" - + "\n" - + "After a careful review and consideration of your expression of interest to join the MOVING EU-level Multi-Actor Platform (MAP), we are happy to inform you that your request has been accepted.\n" - + "\n" - + "You will soon receive an email with link to access the EU MAP set up on the Virtual Research Environment (VRE). \n" - + "\n" - + "Best regards,\n" - + "MOVING team\n"; - + @Override public void render(RenderRequest renderRequest, RenderResponse renderResponse) { Connection conn = null; @@ -75,10 +56,22 @@ public class ManageForms extends MVCPortlet { } } - - public void acceptApplication(ActionRequest request, ActionResponse actionResponse) throws IOException, PortletException { - _log.info("accepting form"); - String formId = ParamUtil.getString(request, "applicationItem"); + public static String getCurrentContext(long groupId) { + try { + PortalContext pContext = PortalContext.getConfiguration(); + return pContext.getCurrentScope(""+groupId); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * used to accept the application + */ + public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { + String formId = ParamUtil.getString(resourceRequest, "applicationItemId", null); + System.out.println("\n\n *** formId="+formId); Connection conn = null; try { conn = DatabaseConnection.getInstance("/"+PortalContext.getConfiguration().getInfrastructureName()).getConnection(); @@ -87,29 +80,46 @@ public class ManageForms extends MVCPortlet { boolean user_accepted = true; setFormProcessedAndStateById(conn, formId, user_accepted); _log.info("UPDATED FORM ON DB to Accepted, formId="+formId); - - _log.info("Sending email to user"); - Properties props = System.getProperties(); - Session session = null; - props.put("mail.smtp.host", mailServiceHost); - props.put("mail.smtp.port", mailServicePort); - //use localhost (probaly postfix instance) - session = Session.getDefaultInstance(props); - Message message = new MimeMessage(session); - message.setFrom(new InternetAddress(CompileForm.MAIL_FROM)); - message.setRecipients( - Message.RecipientType.TO, InternetAddress.parse(filledForm.getEmailAddress())); - message.setSubject(MAIL_SUBJECT); - message.setText(MAIL_BODY_ACCEPT); - // Send message - Transport.send(message); - _log.info("Sending confirmation email done"); - - } catch (Exception e) { - _log.error("Something wrong with Databaseconnection or with getting FORMS from DB", e); - } - } + try { + _log.info("Sending email to user"); + Properties props = System.getProperties(); + Session session = null; + props.put("mail.smtp.host", MConstants.MAIL_SERVICE_HOST); + props.put("mail.smtp.port", MConstants.MAIL_SERVICE_PORT); + //use localhost (probaly postfix instance) + session = Session.getDefaultInstance(props); + Message message = new MimeMessage(session); + message.setFrom(new InternetAddress(CompileForm.MAIL_FROM)); + message.setRecipients( + Message.RecipientType.TO, InternetAddress.parse(filledForm.getEmailAddress())); + message.setSubject(MConstants.MAIL_SUBJECT_FEEDBACK); + message.setText(MConstants.MAIL_BODY_ACCEPT); + // Send message + Transport.send(message); + } catch (Exception e) { + _log.error("Something wrong with sending email", e); + } + _log.info("Sending acceptance email done, adding user to the VRE and creating account if needed"); + HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(resourceRequest)); + CreateUserAccount.register( + httpRequest, + filledForm.getName(), + filledForm.getSurname(), + filledForm.getOrganisation(), + filledForm.getEmailAddress(), + true, + true, filledForm.getDateCreated()); + + _log.info("acceptApplication completed"); + + } catch (Exception e) { + _log.error("Something wrong with Database connection or with getting FORMS from DB", e); + } + JSONObject fileObject = JSONFactoryUtil.createJSONObject(); + fileObject.put("success", "OK"); + resourceResponse.getWriter().println(fileObject); + } public void rejectApplication(ActionRequest request, ActionResponse actionResponse) throws IOException, PortletException { _log.info("rejecting form"); @@ -122,24 +132,24 @@ public class ManageForms extends MVCPortlet { boolean user_accepted = false; setFormProcessedAndStateById(conn, formId, user_accepted); _log.info("UPDATED FORM ON DB to Rejected, formId="+formId); - + _log.info("Sending email to user"); Properties props = System.getProperties(); Session session = null; - props.put("mail.smtp.host", mailServiceHost); - props.put("mail.smtp.port", mailServicePort); + props.put("mail.smtp.host", MConstants.MAIL_SERVICE_HOST); + props.put("mail.smtp.port", MConstants.MAIL_SERVICE_PORT); //use localhost (probaly postfix instance) session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(CompileForm.MAIL_FROM)); message.setRecipients( - Message.RecipientType.TO, InternetAddress.parse(filledForm.getEmailAddress())); - message.setSubject(MAIL_SUBJECT); - message.setText(MAIL_BODY_REJECT); - // Send message - Transport.send(message); - _log.info("Sending confirmation email done"); - + Message.RecipientType.TO, InternetAddress.parse(filledForm.getEmailAddress())); + message.setSubject(MConstants.MAIL_SUBJECT_FEEDBACK); + message.setText(MConstants.MAIL_BODY_REJECT); + // Send message + Transport.send(message); + _log.info("Sending Rejection email done"); + } catch (Exception e) { _log.error("Something wrong with Databaseconnection or with getting FORMS from DB", e); } @@ -182,11 +192,12 @@ public class ManageForms extends MVCPortlet { String elaborated_expertise = rs.getString("elaborated_expertise"); String degree_of_participation = rs.getString("degree_of_participation"); boolean data_management = rs.getBoolean("data_management"); + Timestamp dateCreated = rs.getTimestamp("datecreated"); boolean processed_form = rs.getBoolean("processed_form"); boolean form_accepted = rs.getBoolean("user_accepted"); FilledForm toAdd = new FilledForm(id, name, surname, organisation, organisationType, emailAddress, areaOfExpertise, country, participatedInActivities, mainMotivation, textareaMotivation, - elaborated_expertise, degree_of_participation, data_management, processed_form, form_accepted); + elaborated_expertise, degree_of_participation, data_management, dateCreated, processed_form, form_accepted); _log.info("Adding non processed form" + toAdd); toReturn.add(toAdd); } @@ -212,8 +223,8 @@ public class ManageForms extends MVCPortlet { return false; } } - - + + private static FilledForm getFormById(Connection conn, String formId) throws Exception { _log.debug("getting form by id from DB "); @@ -237,11 +248,12 @@ public class ManageForms extends MVCPortlet { String elaborated_expertise = rs.getString("elaborated_expertise"); String degree_of_participation = rs.getString("degree_of_participation"); boolean data_management = rs.getBoolean("data_management"); + Timestamp dateCreated = rs.getTimestamp("datecreated"); boolean processed_form = rs.getBoolean("processed_form"); boolean form_accepted = rs.getBoolean("user_accepted"); FilledForm toAdd = new FilledForm(id, name, surname, organisation, organisationType, emailAddress, areaOfExpertise, country, participatedInActivities, mainMotivation, textareaMotivation, - elaborated_expertise, degree_of_participation, data_management, processed_form, form_accepted); + elaborated_expertise, degree_of_participation, data_management, dateCreated, processed_form, form_accepted); _log.info("Adding non processed form" + toAdd); return toAdd; } diff --git a/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAccount.java b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAccount.java new file mode 100644 index 0000000..36c32d7 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAccount.java @@ -0,0 +1,314 @@ +package org.gcube.portlets.user.moving.createaccounts; + +import static org.gcube.common.authorization.client.Constants.authorizationService; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import javax.servlet.http.HttpServletRequest; + +import org.gcube.common.authorization.library.provider.AccessTokenProvider; +import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +import org.gcube.common.portal.PortalContext; +import org.gcube.common.storagehub.client.dsl.StorageHubClient; +import org.gcube.portal.mailing.message.Recipient; +import org.gcube.portal.mailing.service.EmailTemplateService; +import org.gcube.portal.mailing.templates.TemplateUserApprovedRequestVRE; +import org.gcube.portal.mailing.templates.TemplateWelcomeCreatedAccount; +import org.gcube.portal.oidc.lr62.OIDCUmaUtil; +import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; +import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException; +import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; +import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault; +import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; +import org.gcube.vomanagement.usermanagement.model.GCubeGroup; +import org.gcube.vomanagement.usermanagement.model.GCubeRole; +import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames; + +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.User; +import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.util.PortalUtil; + +public class CreateUserAccount { + private static com.liferay.portal.kernel.log.Log logger = LogFactoryUtil.getLog(CreateUserAccount.class); + + private static final String INITIAL_PWD = "training1"; + + public static final String DEFAULT_COMPANY_WEB_ID = "liferay.com"; + + + public CreateUserAccount() { + // TODO Auto-generated constructor stub + } + + /** + * + * @param httpRequest + * @param name + * @param surname + * @param institution + * @param email + * @param sendEmail + * @param isMale + * @return + */ + public static boolean register(HttpServletRequest httpRequest, String name, String surname, String institution, + String email, boolean sendEmail, boolean isMale, Timestamp dateCreated) { + + + PortalContext pContext = PortalContext.getConfiguration(); + //checking if the user has been already registered or is already in the portal + LiferayUserManager userManager = new LiferayUserManager(); + boolean exists = userManager.userExistsByEmail(email); + + if(exists){ + logger.debug("User with this email already present , adding the user to the VRE"); + try { + GCubeUser theUser = userManager.getUserByEmail(email); + userManager.assignUserToGroup(getCurrentGroupID(httpRequest), theUser.getUserId()); + Date dateCreatedConverted =new Date(dateCreated.getTime()); + sendEmailToUserRegisterVRE(httpRequest, theUser, dateCreatedConverted); + } catch (UserManagementSystemException | GroupRetrievalFault | UserRetrievalFault + | UserManagementPortalException e) { + e.printStackTrace(); + return false; + } + return true; + } + else{ + logger.debug("Trying to add user: " + name + ", " + surname + ", " + email + ", " + institution); + try { + User user = createLRAccount(httpRequest, name, surname, email, institution, sendEmail); + logger.debug("User registered to the Site, username assigned=" + user.getScreenName()); + //here we wait that the user-registration-hook performs all the tasks + int numOfTries = 0; + do { + logger.debug("Waiting for user-registration-hook to finish create workspace via shub for "+ user.getScreenName() + ",\n attempt: " + (numOfTries+1)); + Thread.sleep(500); + numOfTries++; + } while ( ( !workspaceExists( user.getScreenName()) ) && numOfTries < 10); + if (numOfTries >= 10) { + logger.error("Something wrong for this user, the workspace of " + user.getScreenName() + " could not be found") ; + return false; + } + logger.info("Create workspace via shub has been done, proceed with user add to VRE"); + // adding to the current VRE + long userId = userManager.getUserId(user.getScreenName()); + logger.info("trying to send the event to create the account for this user to the orchestrator"); + long currGroupId = pContext.getCurrentGroupId(httpRequest); + Group theVRE = GroupLocalServiceUtil.getGroup(currGroupId); + new CreateUserAddToVrePublisher().publish( + CreateUserAddToVre.newEvent(user.getScreenName(), name, surname, email, INITIAL_PWD, theVRE)); + logger.debug("... sleeping 5 seconds"); + Thread.sleep(5000); + logger.debug("... now adding his user to the VRE"); + userManager.assignUserToGroup(getCurrentGroupID(httpRequest), userId); + + if (sendEmail) + sendEmailToUserCreatedAccount(httpRequest, email, name + " " + surname); + } + catch(Exception e){ + // unable to create.. we need to delete it from the list of users + logger.error("Unable to create the user " + email + ""); + return false; + } + + + return true; + } + + } + + private static long getCurrentGroupID(HttpServletRequest httpRequest) { + try { + return PortalUtil.getScopeGroupId(httpRequest); + } catch (PortalException | SystemException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return 0; + } + + + + + private static User createLRAccount(HttpServletRequest httpRequest, String firstName, String lastName, String email, String institution, boolean sendEmail) { + User toReturn = null; + try{ + logger.debug("Trying createuser and instatiate serviceContext" + email); + Long defaultCompanyId = PortalUtil.getDefaultCompanyId(); + Long defaultUserId = UserLocalServiceUtil.getDefaultUserId(defaultCompanyId); + PortalContext pContext = PortalContext.getConfiguration(); + //ServiceContext instanciated as follows is needed when the Email verification is sent + ServiceContext serviceContext = new ServiceContext(); + serviceContext.setScopeGroupId(pContext.getCurrentGroupId(httpRequest)); + serviceContext.setPortalURL(pContext.getGatewayURL(httpRequest)); + serviceContext.setPathMain("/c"); + + boolean autoPassword = false; + Locale locale = new Locale("en_US"); + int prefixId = 0; + int suffixId = 0; + int birthdayMonth = 1; + int birthdayDay = 1; + int birthdayYear = 1970; + String password1 = "training1"; + String password2 = password1; + toReturn = UserLocalServiceUtil.addUser( + defaultUserId, + defaultCompanyId, + autoPassword, + password1, + password2, + true, + "", + email, + 0L, + "", + locale, + firstName, + "", + lastName, + prefixId, + suffixId, + true, + birthdayMonth, + birthdayDay, + birthdayYear, + institution, + null, + null, + null, + null, + false, + serviceContext); + logger.debug("Created User on LR " + lastName + " SUCCESS"); + UserLocalServiceUtil.updateEmailAddressVerified(toReturn.getUserId(), true); + //UserLocalServiceUtil.updateAgreedToTermsOfUse(toReturn.getUserId(), true); + //UserLocalServiceUtil.updatePasswordReset(toReturn.getUserId(), true); + UserLocalServiceUtil.updateReminderQuery(toReturn.getUserId(), "What was your initial password?", "training1"); + logger.debug("User " + lastName + " has agreed to ToU"); + logger.debug("User " + lastName + " has verified the Email"); + logger.debug("User " + lastName + " updatePasswordReset & updateReminderQuery"); + + + } + catch(Exception e){ + // unable to create.. we need to delete it from the list of users + logger.error("Unable to create the user " + email + " in liferay.", e); + + } + return toReturn; + } + + private static boolean workspaceExists(String usernameToCheck) { + String previousToken = SecurityTokenProvider.instance.get(); + String previousUMAToken = AccessTokenProvider.instance.get(); + boolean toReturn = false; + try { + //get the super user + logger.info("Getting super user with role " + GatewayRolesNames.INFRASTRUCTURE_MANAGER.getRoleName()); + //get the super user + String infraContext = "/"+PortalContext.getConfiguration().getInfrastructureName(); + long rootgroupId = new LiferayGroupManager().getGroupIdFromInfrastructureScope(infraContext); + + User theAdmin = LiferayUserManager.getRandomUserWithRole(rootgroupId, GatewayRolesNames.INFRASTRUCTURE_MANAGER); + if (theAdmin == null) { + logger.error("Cannot check if workspace exists, could not find any " + GatewayRolesNames.INFRASTRUCTURE_MANAGER + " on context: " + infraContext); + return false; + } + String adminUsername = theAdmin.getScreenName(); + String theAdminToken = PortalContext.getConfiguration().getCurrentUserToken(infraContext, adminUsername); + List rolesString = new ArrayList(); + List theAdminRoles = new LiferayRoleManager().listRolesByUserAndGroup(theAdmin.getUserId(), rootgroupId); + for (GCubeRole gCubeRole : theAdminRoles) { + rolesString.add(gCubeRole.getRoleName()); + } + rolesString.add(GatewayRolesNames.INFRASTRUCTURE_MANAGER.getRoleName()); + logger.debug("legacy authorizationService().setTokenRoles done"); + authorizationService().setTokenRoles(theAdminToken, rolesString); + SecurityTokenProvider.instance.set(theAdminToken); + OIDCUmaUtil.provideConfiguredPortalClientUMATokenInThreadLocal("/" + PortalContext.getConfiguration().getInfrastructureName()); + logger.info("\nCreateUser.workspaceExists() new authorizationService PortalClient UMA-Token In ThreadLocal done\n"); + //here we actually make the authorised call to check if the workspace exists through shub + StorageHubClient shc = new StorageHubClient(); + toReturn = shc.userExists(usernameToCheck); + logger.info("\nshub userExists(" + usernameToCheck + ") returns "+toReturn); + AccessTokenProvider.instance.set(previousUMAToken); + SecurityTokenProvider.instance.set(previousToken); + return toReturn; + } catch (Exception e) { + AccessTokenProvider.instance.set(previousUMAToken); + SecurityTokenProvider.instance.set(previousToken); + logger.error("Cannot check if worspace exists for " + usernameToCheck, e); + return false; + } + } + + + private static void sendEmailToUserCreatedAccount(HttpServletRequest request, String email, String nameCreatedUser) { + try{ + logger.debug("Sending welcome message to user with email " + email); + PortalContext context = PortalContext.getConfiguration(); + String gatewayName = context.getGatewayName(request); + String gatewayURL = context.getGatewayURL(request); + long groupId = context.getCurrentGroupId(request); + GCubeGroup currVRE = new LiferayGroupManager().getGroup(groupId); + + GCubeUser theManagerUser =context.getCurrentUser(request); + + String subject = "Your user account for " + currVRE.getGroupName() + " VRE has been created"; + EmailTemplateService.send( + subject, + new TemplateWelcomeCreatedAccount( + gatewayName, + gatewayURL, + email, + nameCreatedUser, + theManagerUser, currVRE), request, new Recipient(email)); + + }catch(Exception e){ + logger.error("Error while sending email to user " + email, e); + } + + } + + + private static void sendEmailToUserRegisterVRE(HttpServletRequest request, GCubeUser theRequestingUser, Date dateCreated) { + try{ + logger.debug("Sending welcome message to user " + theRequestingUser.getFullname()); + PortalContext context = PortalContext.getConfiguration(); + String gatewayName = context.getGatewayName(request); + String gatewayURL = context.getGatewayURL(request); + long groupId = context.getCurrentGroupId(request); + GCubeGroup currVRE = new LiferayGroupManager().getGroup(groupId); + + GCubeUser theManagerUser =context.getCurrentUser(request); + + String subject = "MOVING EU Multi-Actor VRE has been granted"; + EmailTemplateService.send( + subject, + new TemplateUserApprovedRequestVRE(theRequestingUser, theManagerUser, currVRE, dateCreated, gatewayName, gatewayURL), request, new Recipient(theRequestingUser.getEmail())); + + + + }catch(Exception e){ + logger.error("Error while sending email to user "); + } + + } + + +} diff --git a/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVre.java b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVre.java new file mode 100644 index 0000000..7a87079 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVre.java @@ -0,0 +1,75 @@ +package org.gcube.portlets.user.moving.createaccounts; + +import org.gcube.portal.event.publisher.lr62.PortalEvent; + +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.model.Group; + +public class CreateUserAddToVre extends PortalEvent { + + private static final long serialVersionUID = 1499288552188273747L; + + public static final String NAME = "create-user-add-to-vre"; + public static final String FIRST_NAME_ENTRY = "first-name"; + public static final String LAST_NAME_ENTRY = "last-name"; + public static final String EMAIL_ENTRY = "email"; + public static final String PASSWORD_ENTRY = "password"; + + private CreateUserAddToVre(String username, String firstname, String lastname, String email, String password, Group group) + throws PortalException, SystemException { + + super(NAME); + setUser(username); + setFirstname(firstname); + setLastname(lastname); + setEmail(email); + setPassword(password); + setGroup(group); + } + + public static CreateUserAddToVre newEvent(String username, String firstname, String lastname, String email, String password, + Group group) { + + try { + return new CreateUserAddToVre(username, firstname, lastname, email, password, group); + } catch (PortalException | SystemException e) { + log.error("Cannot create event from group model object", e); + return null; + } + } + + + public void setFirstname(String firstname) { + set(FIRST_NAME_ENTRY, firstname); + } + + public String getFirstname() { + return (String) get(FIRST_NAME_ENTRY); + } + + public void setLastname(String lastname) { + set(LAST_NAME_ENTRY, lastname); + } + + public String getLastname() { + return (String) get(LAST_NAME_ENTRY); + } + + public void setEmail(String email) { + set(EMAIL_ENTRY, email); + } + + public String getEmail() { + return (String) get(EMAIL_ENTRY); + } + + public void setPassword(String password) { + set(PASSWORD_ENTRY, password); + } + + public String getPassword() { + return (String) get(PASSWORD_ENTRY); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVrePublisher.java b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVrePublisher.java new file mode 100644 index 0000000..c8faec7 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/moving/createaccounts/CreateUserAddToVrePublisher.java @@ -0,0 +1,11 @@ +package org.gcube.portlets.user.moving.createaccounts; + +import org.gcube.portal.event.publisher.lr62.AbstractLR62EventPublisher; + +public class CreateUserAddToVrePublisher extends AbstractLR62EventPublisher { + + public CreateUserAddToVrePublisher() { + super(); + } + +} diff --git a/src/main/webapp/html/manageforms/manage-forms.jsp b/src/main/webapp/html/manageforms/manage-forms.jsp index b1882c2..b6fdae0 100644 --- a/src/main/webapp/html/manageforms/manage-forms.jsp +++ b/src/main/webapp/html/manageforms/manage-forms.jsp @@ -9,10 +9,43 @@ pageContext.setAttribute("filledForms", filledForms); - + @@ -80,4 +113,11 @@ function performAction(action) { + + + \ No newline at end of file