Liferay – Run as Administrator

Following method allows to set admin privileges to the current thread, executes the work and returns the thread control to the current user.

AuthenticationUtil.java

import java.util.List;

import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.CompanyThreadLocal;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;

public class AuthenticationUtil {
	
    public interface RunAsWork<Result> {
        Result doWork() throws Exception;
    }
	
    public static <R> R runAsSystem(RunAsWork<R> runAsWork) {
		PermissionChecker currentPermisionChecker = PermissionThreadLocal.getPermissionChecker();
        final R result;
        
        try {
        	
    		Role adminRole = RoleLocalServiceUtil.getRole(CompanyThreadLocal.getCompanyId(), RoleConstants.ADMINISTRATOR);
    		List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
    		PrincipalThreadLocal.setName(adminUsers.iterator().next().getUserId());
    		PermissionChecker permissionChecker =PermissionCheckerFactoryUtil.create(adminUsers.iterator().next(), false);
    		PermissionThreadLocal.setPermissionChecker(permissionChecker);
            
            result = runAsWork.doWork();
            return result;
            
        } catch (Throwable exception) {
            if (exception instanceof RuntimeException) {
                throw (RuntimeException) exception;
            } else {
                throw new RuntimeException("Error during run as.", exception);
            }
        }
        finally {
    		PermissionThreadLocal.setPermissionChecker(currentPermisionChecker);
        }
    }

}

Sample invocation

public static Organization addOrganization(final long parentOrganizationId, 
    final String name) throws Exception {
	
	Organization organization = AuthenticationUtil.runAsSystem(new AuthenticationUtil.RunAsWork<Organization>() {
		
	    @Override
		public Organization doWork() throws Exception {
	
			Organization organization = OrganizationServiceUtil.addOrganization(
				parentOrganizationId,
				name,
				"regular-organization", true, 0, 0, 
				ListTypeConstants.ORGANIZATION_STATUS_DEFAULT, "", new ServiceContext());
	
			return organization;
	
	    }
	    
	});
	
	return organization;
	
}

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s