now uses a retry to check that the creates user workspace is created

This commit is contained in:
Massimiliano Assante 2021-02-04 17:42:13 +01:00
parent 7e9ae491af
commit 6f6a6c1ef7
5 changed files with 355 additions and 226 deletions

View File

@ -3,7 +3,9 @@ org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8 org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8 org.eclipse.jdt.core.compiler.source=1.8

View File

@ -1,10 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"> <?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="create-users-portlet"> <wb-module deploy-name="create-users-portlet">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/> <wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/> <wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<dependent-module archiveName="email-templates-library-1.4.4.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/email-templates-library/email-templates-library">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/create-users/target/subscribe-users-1.0.0-SNAPSHOT/WEB-INF/classes"/> <property name="java-output-path" value="/create-users/target/subscribe-users-1.0.0-SNAPSHOT/WEB-INF/classes"/>
<property name="context-root" value="create-users-portlet"/> <property name="context-root" value="create-users-portlet"/>
</wb-module> </wb-module>
</project-modules> </project-modules>

10
pom.xml
View File

@ -71,6 +71,16 @@
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version> <version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-client-library</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>oidc-library-portal</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>com.googlecode.json-simple</groupId> <groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>

View File

@ -1,14 +1,10 @@
package org.gcube.portlets.admin.createusers.orchestrator; package org.gcube.portlets.admin.createusers.orchestrator;
import org.gcube.portal.event.publisher.lr62.PortalEvent; import org.gcube.portal.event.publisher.lr62.PortalEvent;
import org.gcube.portlets.admin.createusers.server.CreateUsersImpl;
import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.Group; import com.liferay.portal.model.Group;
import com.liferay.portal.security.auth.CompanyThreadLocal;
import com.liferay.portal.security.auth.DefaultScreenNameGenerator;
import com.liferay.portal.service.UserLocalServiceUtil;
public class CreateUserAddToVre extends PortalEvent { public class CreateUserAddToVre extends PortalEvent {
@ -20,13 +16,11 @@ public class CreateUserAddToVre extends PortalEvent {
public static final String EMAIL_ENTRY = "email"; public static final String EMAIL_ENTRY = "email";
public static final String PASSWORD_ENTRY = "password"; public static final String PASSWORD_ENTRY = "password";
private static DefaultScreenNameGenerator defaultScreenNameGenerator = new DefaultScreenNameGenerator(); private CreateUserAddToVre(String username, String firstname, String lastname, String email, String password, Group group)
private CreateUserAddToVre(String firstname, String lastname, String email, String password, Group group)
throws PortalException, SystemException { throws PortalException, SystemException {
super(NAME); super(NAME);
setUser(computeUsername(email)); setUser(username);
setFirstname(firstname); setFirstname(firstname);
setLastname(lastname); setLastname(lastname);
setEmail(email); setEmail(email);
@ -34,28 +28,18 @@ public class CreateUserAddToVre extends PortalEvent {
setGroup(group); setGroup(group);
} }
public static CreateUserAddToVre newEvent(String firstname, String lastname, String email, String password, public static CreateUserAddToVre newEvent(String username, String firstname, String lastname, String email, String password,
Group group) { Group group) {
try { try {
return new CreateUserAddToVre(firstname, lastname, email, password, group); return new CreateUserAddToVre(username, firstname, lastname, email, password, group);
} catch (PortalException | SystemException e) { } catch (PortalException | SystemException e) {
log.error("Cannot create event from group model object", e); log.error("Cannot create event from group model object", e);
return null; return null;
} }
} }
protected String computeUsername(String email) {
try {
Long companyId = CreateUsersImpl.getCompany().getCompanyId();
Long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
return defaultScreenNameGenerator.generate(companyId, defaultUserId, email);
} catch (Exception e) {
log.error("Cannot generate username via screen name generator", e);
return "";
}
}
public void setFirstname(String firstname) { public void setFirstname(String firstname) {
set(FIRST_NAME_ENTRY, firstname); set(FIRST_NAME_ENTRY, firstname);
} }

View File

@ -1,4 +1,6 @@
package org.gcube.portlets.admin.createusers.server; package org.gcube.portlets.admin.createusers.server;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -8,22 +10,30 @@ import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.UmaJWTProvider;
import org.gcube.common.portal.PortalContext; import org.gcube.common.portal.PortalContext;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.UserManagerClient;
import org.gcube.portal.mailing.message.Recipient; import org.gcube.portal.mailing.message.Recipient;
import org.gcube.portal.mailing.service.EmailTemplateService; import org.gcube.portal.mailing.service.EmailTemplateService;
import org.gcube.portal.mailing.templates.TemplateWelcomeCreatedAccount; import org.gcube.portal.mailing.templates.TemplateWelcomeCreatedAccount;
import org.gcube.portal.oidc.lr62.OIDCUmaUtil;
import org.gcube.portlets.admin.createusers.client.HandleUsersService; import org.gcube.portlets.admin.createusers.client.HandleUsersService;
import org.gcube.portlets.admin.createusers.orchestrator.CreateUserAddToVre; import org.gcube.portlets.admin.createusers.orchestrator.CreateUserAddToVre;
import org.gcube.portlets.admin.createusers.orchestrator.CreateUserAddToVrePublisher; import org.gcube.portlets.admin.createusers.orchestrator.CreateUserAddToVrePublisher;
import org.gcube.portlets.admin.createusers.shared.VreUserBean; import org.gcube.portlets.admin.createusers.shared.VreUserBean;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException; import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; 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.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup; 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.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -35,9 +45,12 @@ import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.model.Company; import com.liferay.portal.model.Company;
import com.liferay.portal.model.Group; import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.service.CompanyLocalServiceUtil; import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil; import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
/** /**
* The server side implementation of the RPC service. * The server side implementation of the RPC service.
@ -49,7 +62,7 @@ public class CreateUsersImpl extends RemoteServiceServlet implements HandleUsers
private static final long serialVersionUID = -3124676000683430170L; private static final long serialVersionUID = -3124676000683430170L;
private static final String REGISTERED_USERS_TABLE = "registered_users"; private static final String REGISTERED_USERS_TABLE = "registered_users";
private static final String INITIAL_PWD = "training1"; private static final String INITIAL_PWD = "training1";
// SQL TABLE FIELDS // SQL TABLE FIELDS
private static final String FIELD_EMAIL = "email"; private static final String FIELD_EMAIL = "email";
@ -62,23 +75,19 @@ public class CreateUsersImpl extends RemoteServiceServlet implements HandleUsers
public static final String DEFAULT_COMPANY_WEB_ID = "liferay.com"; public static final String DEFAULT_COMPANY_WEB_ID = "liferay.com";
@Override @Override
public void init(){ public void init() {
logger.debug("Trying to get connect to liferay's DB from API");
if(isWithinPortal()){ try {
logger.debug("Trying to get connect to liferay's DB from API"); Connection con = DataAccess.getConnection();
try { boolean exists = tableExists(con);
Connection con = DataAccess.getConnection(); if(exists)
boolean exists = tableExists(con); logger.debug("Table " + REGISTERED_USERS_TABLE + " already exists.");
if(exists) else
logger.debug("Table " + REGISTERED_USERS_TABLE + " already exists."); initializeTable(con);
else } catch (Exception e) {
initializeTable(con); logger.error("Failed to connect to liferay's DB");
} catch (Exception e) { return;
logger.error("Failed to connect to liferay's DB"); }
return;
}
}else
logger.debug("DEV MODE detected");
} }
/** /**
@ -127,222 +136,134 @@ public class CreateUsersImpl extends RemoteServiceServlet implements HandleUsers
} }
} }
/**
* Online or in development mode?
* @return true if you're running into the portal, false if in development
*/
private boolean isWithinPortal() {
try {
UserLocalServiceUtil.getService();
return true;
}
catch (com.liferay.portal.kernel.bean.BeanLocatorException ex) {
logger.trace("Development Mode ON");
return false;
}
}
@Override @Override
public boolean deleteInvitedUser(String email) { public boolean deleteInvitedUser(String email) {
try{
// if in dev mode return some samples Connection con = DataAccess.getConnection();
if (!isWithinPortal()) { boolean deletedLiferay = deleteUserFromLiferay(email);
logger.debug("In dev mode."); boolean deletedTable = deleteUserFromTable(email, con);
return false; return deletedLiferay && deletedTable;
}else{ }catch(SQLException e){
try{ logger.debug("Error while trying to delete user with email = " + email, e);
Connection con = DataAccess.getConnection();
boolean deletedLiferay = deleteUserFromLiferay(email);
boolean deletedTable = deleteUserFromTable(email, con);
return deletedLiferay && deletedTable;
}catch(SQLException e){
logger.debug("Error while trying to delete user with email = " + email, e);
}
return false;
} }
return false;
} }
@Override @Override
public void sendEmailToUser(String email, String nameCreatedUser) { public void sendEmailToUser(String email, String nameCreatedUser) {
if(isWithinPortal()){ try{
try{ logger.debug("Sending welcome message to user with email " + email);
logger.debug("Sending welcome message to user with email " + email); PortalContext context = PortalContext.getConfiguration();
PortalContext context = PortalContext.getConfiguration(); String gatewayName = context.getGatewayName(getThreadLocalRequest());
String gatewayName = context.getGatewayName(getThreadLocalRequest()); String gatewayURL = context.getGatewayURL(getThreadLocalRequest());
String gatewayURL = context.getGatewayURL(getThreadLocalRequest()); long groupId = context.getCurrentGroupId(getThreadLocalRequest());
long groupId = context.getCurrentGroupId(getThreadLocalRequest()); GCubeGroup currVRE = new LiferayGroupManager().getGroup(groupId);
GCubeGroup currVRE = new LiferayGroupManager().getGroup(groupId);
GCubeUser theManagerUser =context.getCurrentUser(getThreadLocalRequest()); GCubeUser theManagerUser =context.getCurrentUser(getThreadLocalRequest());
String subject = "Your user account for " + currVRE.getGroupName() + " VRE has been created"; String subject = "Your user account for " + currVRE.getGroupName() + " VRE has been created";
EmailTemplateService.send( EmailTemplateService.send(
subject, subject,
new TemplateWelcomeCreatedAccount( new TemplateWelcomeCreatedAccount(
gatewayName, gatewayName,
gatewayURL, gatewayURL,
email, email,
nameCreatedUser, nameCreatedUser,
theManagerUser, currVRE), getThreadLocalRequest(), new Recipient(email)); theManagerUser, currVRE), getThreadLocalRequest(), new Recipient(email));
}catch(Exception e){
logger.error("Error while sending email to user " + email, e);
}
}catch(Exception e){
logger.error("Error while sending email to user " + email, e);
}
}else
logger.debug("DEV MODE detected, mail sent...");
} }
@Override @Override
public VreUserBean register(String name, String surname, String institution, public VreUserBean register(String name, String surname, String institution,
String email, boolean sendEmail, boolean isMale) { String email, boolean sendEmail, boolean isMale) {
// if in dev mode return ok
if (!isWithinPortal()) {
logger.debug("In dev mode.");
return new VreUserBean(name, surname, institution, email, false, System.currentTimeMillis(), isMale);
}else{
PortalContext pContext = PortalContext.getConfiguration(); PortalContext pContext = PortalContext.getConfiguration();
String vre = pContext.getCurrentScope(getThreadLocalRequest()); String vre = pContext.getCurrentScope(getThreadLocalRequest());
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
//checking if the user has been already registered or is already in the portal //checking if the user has been already registered or is already in the portal
LiferayUserManager userManager = new LiferayUserManager(); LiferayUserManager userManager = new LiferayUserManager();
boolean exists = userManager.userExistsByEmail(email); boolean exists = userManager.userExistsByEmail(email);
if(exists){ if(exists){
logger.debug("User with this email already present in the portal."); logger.debug("User with this email already present in the portal.");
return null; return null;
}
else{
logger.debug("Trying to add user: " + name + ", " + surname + ", " + email + ", " + institution);
Connection con = null;
try{
con = DataAccess.getConnection();
String insert = "INSERT into " + REGISTERED_USERS_TABLE +
"("+ FIELD_EMAIL + ","
+ FIELD_NAME +","
+ FIELD_SURNAME + ","
+ FIELD_INSTITUTION + ","
+ FIELD_REGISTRATION_DATE + ","
+ FIELD_VRE
+ ") values(?, ?, ?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(insert);
statement.setString(1, email);
statement.setString(2, name);
statement.setString(3, surname);
statement.setString(4, institution);
statement.setTimestamp(5, new Timestamp(timestamp));
statement.setString(6, vre);
int res = statement.executeUpdate();
if(res != 0){
logger.debug("User added in " + REGISTERED_USERS_TABLE);
// add in Keycloak too
try{
logger.debug("trying to send the event to create the account for this user to the orchestrator");
long currGroupId = pContext.getCurrentGroupId(getThreadLocalRequest());
Group theVRE = GroupLocalServiceUtil.getGroup(currGroupId);
new CreateUserAddToVrePublisher().publish(
CreateUserAddToVre.newEvent(name, surname, email, INITIAL_PWD, theVRE));
if (sendEmail)
sendEmailToUser(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 + " in liferay. Removing he/she from the table " +
REGISTERED_USERS_TABLE, e);
deleteUserFromTable(email, con);
return null;
}
}
else{
logger.debug("User NOT added in " + REGISTERED_USERS_TABLE);
return null;
}
}catch(Exception e){
logger.error("Unable to add user, sorry..", e);
return null;
}finally{
try {
if(con != null)
con.close();
} catch (SQLException e) {
logger.error("Unable to close connection to the DB");
}
}
return new VreUserBean(name, surname, institution, email, false, timestamp, isMale);
}
} }
} else{
@Override
public List<VreUserBean> getAlreadyRegisterdUsers() {
List<VreUserBean> toReturn = new ArrayList<VreUserBean>();
// if in dev mode return some samples
if (!isWithinPortal()) {
logger.debug("In dev mode.");
toReturn.add(new VreUserBean("Dylan", "Dog", "ISTI-CNR", "dylan.dog@gmail.com", true, System.currentTimeMillis(), true));
toReturn.add(new VreUserBean("Costantino", "Perciante", "ISTI-CNR", "costantino8@gmail.com", false, System.currentTimeMillis(), true));
return toReturn;
}else{
LiferayUserManager userManager = new LiferayUserManager();
// evaluate current vre
PortalContext pContext = PortalContext.getConfiguration();
String vre = pContext.getCurrentScope(getThreadLocalRequest());
logger.debug("Trying to add user: " + name + ", " + surname + ", " + email + ", " + institution);
Connection con = null; Connection con = null;
try{ try{
con = DataAccess.getConnection(); con = DataAccess.getConnection();
Statement stmt = con.createStatement(); String insert = "INSERT into " + REGISTERED_USERS_TABLE +
"("+ FIELD_EMAIL + ","
+ FIELD_NAME +","
+ FIELD_SURNAME + ","
+ FIELD_INSTITUTION + ","
+ FIELD_REGISTRATION_DATE + ","
+ FIELD_VRE
+ ") values(?, ?, ?, ?, ?, ?)";
String sql = "SELECT * FROM " + REGISTERED_USERS_TABLE + " WHERE " + FIELD_VRE + "='" + vre + "';"; PreparedStatement statement = con.prepareStatement(insert);
ResultSet rs = stmt.executeQuery(sql); statement.setString(1, email);
statement.setString(2, name);
statement.setString(3, surname);
statement.setString(4, institution);
statement.setTimestamp(5, new Timestamp(timestamp));
statement.setString(6, vre);
int res = statement.executeUpdate();
if(res != 0){
logger.debug("User added in " + REGISTERED_USERS_TABLE);
// add in liferay and send event to Keycloak too
try{
User user = register(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(2000);
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 null;
}
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());
userManager.assignUserToGroup(getCurrentGroupID(), userId);
logger.debug("trying to send the event to create the account for this user to the orchestrator");
long currGroupId = pContext.getCurrentGroupId(getThreadLocalRequest());
Group theVRE = GroupLocalServiceUtil.getGroup(currGroupId);
new CreateUserAddToVrePublisher().publish(
CreateUserAddToVre.newEvent(user.getScreenName(), name, surname, email, INITIAL_PWD, theVRE));
if (sendEmail)
sendEmailToUser(email, name + " " + surname);
}catch(Exception e){
while(rs.next()){ // unable to create.. we need to delete it from the list of users
logger.error("Unable to create the user " + email + " in liferay. Removing he/she from the table " +
String name = rs.getString(FIELD_NAME); REGISTERED_USERS_TABLE, e);
String surname = rs.getString(FIELD_SURNAME);
String institution = rs.getString(FIELD_INSTITUTION);
String email = rs.getString(FIELD_EMAIL);
long registrationDate = rs.getTimestamp(FIELD_REGISTRATION_DATE).getTime();
// check if the password has been changed or not wrt the default one
boolean passwordChanged = userManager.isPasswordChanged(email);
toReturn.add(new VreUserBean(name, surname, institution, email, passwordChanged, registrationDate, false));
}
// now, make sure these users are still on portal
Iterator<VreUserBean> iterator = toReturn.iterator();
while (iterator.hasNext()) {
VreUserBean user = (VreUserBean) iterator.next();
if(!userManager.userExistsByEmail(user.getEmail())){
// remove from the table
deleteUserFromTable(user.getEmail(), con);
// remove from this collection
iterator.remove();
deleteUserFromTable(email, con);
return null;
} }
} }
else{
logger.debug("User NOT added in " + REGISTERED_USERS_TABLE);
return null;
}
}catch(Exception e){ }catch(Exception e){
logger.error("Unable to retrieve users list, sorry...", e); logger.error("Unable to add user, sorry..", e);
return null; return null;
}finally{ }finally{
try { try {
@ -352,9 +273,185 @@ public class CreateUsersImpl extends RemoteServiceServlet implements HandleUsers
logger.error("Unable to close connection to the DB"); logger.error("Unable to close connection to the DB");
} }
} }
return new VreUserBean(name, surname, institution, email, false, timestamp, isMale);
return toReturn;
} }
}
private boolean workspaceExists(String usernameToCheck) {
String previousToken = SecurityTokenProvider.instance.get();
String previousUMAToken = UmaJWTProvider.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<String> rolesString = new ArrayList<String>();
List<GCubeRole> 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
UserManagerClient client = AbstractPlugin.users().build();
toReturn = client.getUsers().contains(usernameToCheck);
logger.info("\nshub UserManagerClient#getUsers().contains(" + usernameToCheck + ") returns "+toReturn);
UmaJWTProvider.instance.set(previousUMAToken);
SecurityTokenProvider.instance.set(previousToken);
return toReturn;
} catch (Exception e) {
UmaJWTProvider.instance.set(previousUMAToken);
SecurityTokenProvider.instance.set(previousToken);
logger.error("Cannot check if worspace exists for " + usernameToCheck, e);
return false;
}
}
private User register(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(getThreadLocalRequest()));
serviceContext.setPortalURL(pContext.getGatewayURL(getThreadLocalRequest()));
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;
}
@Override
public List<VreUserBean> getAlreadyRegisterdUsers() {
List<VreUserBean> toReturn = new ArrayList<VreUserBean>();
LiferayUserManager userManager = new LiferayUserManager();
// evaluate current vre
PortalContext pContext = PortalContext.getConfiguration();
String vre = pContext.getCurrentScope(getThreadLocalRequest());
Connection con = null;
try{
con = DataAccess.getConnection();
Statement stmt = con.createStatement();
String sql = "SELECT * FROM " + REGISTERED_USERS_TABLE + " WHERE " + FIELD_VRE + "='" + vre + "';";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String name = rs.getString(FIELD_NAME);
String surname = rs.getString(FIELD_SURNAME);
String institution = rs.getString(FIELD_INSTITUTION);
String email = rs.getString(FIELD_EMAIL);
long registrationDate = rs.getTimestamp(FIELD_REGISTRATION_DATE).getTime();
// check if the password has been changed or not wrt the default one
boolean passwordChanged = userManager.isPasswordChanged(email);
toReturn.add(new VreUserBean(name, surname, institution, email, passwordChanged, registrationDate, false));
}
// now, make sure these users are still on portal
Iterator<VreUserBean> iterator = toReturn.iterator();
while (iterator.hasNext()) {
VreUserBean user = (VreUserBean) iterator.next();
if(!userManager.userExistsByEmail(user.getEmail())){
// remove from the table
deleteUserFromTable(user.getEmail(), con);
// remove from this collection
iterator.remove();
}
}
}catch(Exception e){
logger.error("Unable to retrieve users list, sorry...", e);
return null;
}finally{
try {
if(con != null)
con.close();
} catch (SQLException e) {
logger.error("Unable to close connection to the DB");
}
}
return toReturn;
} }
/** /**