Blog Post

...

Liferay: execute java code as administrator user

During Liferay java code development you may need to run your code as administrator user. This can happen when some user logged in with a restricted role, but it is required to execute an user action with higher privileges (admin or others). The examples of these user actions: grant permissions to some folder or file, search for content in spaces which the user does not belong to, perform system actions (create new role in portal etc.) and many others. In this blog post I’ll show how to make it possible.

The main approach will have the following steps:  

  1. Save com.liferay.portal.security.permission.PermissionChecker for current user.
  2. Get admin user in portal.
  3. Create a new PermissionChecker for retrieved admin user.
  4. Substitute current PermissionChecker with the just created PermissionChecker. 
  5. Execute required user action.
  6. Revert current admin PermissionChecker to the one of step 1. 

In previous article I presented how to get Liferay administrator user. Having this retrieved user we can perform step 2.

As the result we’ll have this function:

 

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;

private void asAdmin() {
    try {
        PermissionChecker currentPermisionChecker = PermissionThreadLocal.getPermissionChecker();
        User admin = Utils.getAdmin();
        PrincipalThreadLocal.setName(admin.getUserId());
        // Create and set permission checker
        PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(admin);
        PermissionThreadLocal.setPermissionChecker(permissionChecker);
        
        /* ... 
            user action that requires admin privileges */
        
        // Set original checker
        PermissionThreadLocal.setPermissionChecker(currentPermisionChecker);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

Surely, user action in this function can be passed as a parameter that will enable to reuse this method many times. Thank you for interest.

Comments (0)

Tags: liferay


0 comments

Leave a Comment