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 "); } } }