Liferay: execute java code as administrator user
by Stanislav on Wednesday Jul 01, 2015
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:
- Save com.liferay.portal.security.permission.PermissionChecker for current user.
- Get admin user in portal.
- Create a new PermissionChecker for retrieved admin user.
- Substitute current PermissionChecker with the just created PermissionChecker.
- Execute required user action.
- 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.
Tags: liferay