« Back to Wiki - Pending...

Permissioning in Plugin Environment

DEFINING PERMISSION FOR A PORTLET RESOURCE IN PLUGIN ENVIRONMENT #

Step 1 #

Create one portlet named addressbook with crud operations.

Here i have already created addressbook portlet from there i am explaining how to create permissions.

Step 2 #

Create "addressbook.xml" under "src/resource-actions"

copy the below contents:

<?xml version="1.0"?>
<resource-action-mapping>
	<portlet-resource>
		<portlet-name>addressbook</portlet-name>
                <permissions>
		<supports>
			<action-key>VIEW</action-key>
			<action-key>CONFIGURATION</action-key>
			<action-key>ADD_ENTRY</action-key>
			<action-key>DELETE</action-key>
			<action-key>SEARCH</action-key>
			<action-key>FILTER</action-key>
		</supports>
		<community-defaults>
			<action-key>VIEW</action-key>
			<action-key>SEARCH</action-key>
		</community-defaults>
		<guest-defaults>
			<action-key>VIEW</action-key>
			<action-key>FILTER</action-key>
		</guest-defaults>
		<guest-unsupported>
			<action-key>DELETE</action-key>
			<action-key>CONFIGURATION</action-key>
		</guest-unsupported>
         </permissions>
	</portlet-resource>
</resource-action-mapping>

create "default.xml" inside the same folder and insert the below contents.

<?xml version="1.0"?>
<resource-action-mapping>
	<resource file="resource-actions/addressbook.xml" />
</resource-action-mapping>

Step 3 #

Insert the below tag just before "</portlet>" in the file "liferay-portlet.xml"

<add-default-resource>true</add-default-resource>

Step 4 #

Update Language.properties.

Add the following 3 entries,

action.FILTER=Filter action.COPY=Copy action.SEARCH=Search

(Copy action we'll use in model resource)

Step 5 #

Append the following lines to portlet.properties (see "Add a Properties File to a Portlet")

##
## Resource
##
resource.actions.configs=resource-actions/default.xml

Step 6 #

Run "ant deploy" to deploy the portlet to the server

You can check the permissions now in two ways:

  • a. in the UI
  • b. in the database (table Permission_)

CHECKING THE PERMISSIONS - IN JSP #

1. open the jsp file responsible for rendering the list page. list_normal_address.jsp. (To test this you can directly modify the file inside tomcat/webapps. )

2. replace the below line

<c:if test="<%= addButton == 1%>">

with,

<c:if test="<%= PortletPermissionUtil.contains(permissionChecker,plid.longValue(), "addressbook_WAR_addressbook5121",ActionKeys.ADD_ENTRY) %>">

Note:

In the EXT envt you'll give the portlet name as "addressbook"

3. Refresh the page and you will not see the "Add" Button

4. Now login as admin and give permission for guest to do this "action"

5. Logout and see the button appearing now.

6. Create a new user account. Once the account is created reset the password to "test"

7. Login as this new user. You'll find the "Add" action available to this use as he belongs to the "Guest" community

CHECKING THE PERMISSIONS - IN JAVA #

1. add this method in AddressActionUtil.java

public static void authorize(PortletRequest req, String action) 
		throws PrincipalException, PortalException, SystemException {	
	// permission checker code
	ThemeDisplay themeDisplay = (ThemeDisplay)req.getAttribute(

		WebKeys.THEME_DISPLAY);

	Layout layout = themeDisplay.getLayout();
	long plid = layout.getPlid();

	PermissionChecker permissionChecker =

		PermissionThreadLocal.getPermissionChecker();

	try {
		PortletPermissionUtil.check(permissionChecker,plid,"addressbook_WAR_addressbook5121",action);
	} catch (PrincipalException pe) {
		System.out.println("the use is not authorized to perform this action. ");		
		throw new PrincipalException(pe);		
	}
}

2. Make necessary imports,

import com.liferay.portal.util.WebKeys;
import com.liferay.portal.model.Layout;
import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.service.permission.PortletPermissionUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;

3. call this method from ViewAddressAction.java

insert this line as the first line of the loadAddPage method.

AddressActionUtil.authorize(req, ActionKeys.ADD_ENTRY);

4. ant compile to confirm all your changes are proper.

5. ant deploy to deploy the new war file to the server

6. verify your changes. Now guest will not see the page to add an entry.

DEFINING PERMISSION FOR A MODEL RESOURCE #

Step 1 #

-->Create the folder resource-actions and place under ext-impl/src -->Create the "addressbook.xml" file and place under resource-actions

addressbook.xml:

<?xml version="1.0"?>
<resource-action-mapping>
<model-resource>
        <model-name>com.mpower.addressbook.model.Address</model-name>
        <portlet-ref>
            <portlet-name>addressbook</portlet-name>
        </portlet-ref>
        <supports>
            <action-key>PERMISSIONS</action-key>
            <action-key>LIST</action-key>
	    <action-key>UPDATE</action-key>
            <action-key>COPY</action-key>
	    <action-key>DELETE</action-key>
	    <action-key>VIEW</action-key>
        </supports>
        <community-defaults>
		<action-key>VIEW</action-key>
		<action-key>LIST</action-key>
		<action-key>UPDATE</action-key>
	</community-defaults>
	<guest-defaults>
		<action-key>VIEW</action-key>
		<action-key>COPY</action-key>
	</guest-defaults>
	<guest-unsupported>
		<action-key>UPDATE</action-key>
	</guest-unsupported>		
</model-resource>
</resource-action-mapping>

Note: Add the Following entries in "language.properties"

add.LIST=List add.COPY=copy

Step 2 #

Create "default-ext.xml" file and place inside the same folder where the "addressbook.xml" file resides

default-ext.xml

<?xml version="1.0"?>

<resource-action-mapping>
	<resource file="resource-actions/addressbook.xml" />
</resource-action-mapping>

Step 3 #

Now add the following line in the --"portal-ext.properties"--

resource.actions.configs=resource-actions/default.xml

Step 4 #

Now we want to mention this in --"liferay-portlet-ext.xml"-- Note:This is main thing .We want to mention . <portlet> <add-default-resource>true</add-default-resource> </portlet>

Step 5 #

Place the following code inside the "address_action_tab.jsp" before closing the

</liferay-ui:icon-menu> tag.
			<liferay-security:permissionsURL
				modelResource="<%= Address.class.getName() %>"
				modelResourceDescription="<%= "mPowerPermission" %>"
				resourcePrimKey="<%= Long.toString(address.getAddressId()) %>"
				var="permissionsEntryURL"
			/>
			<liferay-ui:icon image="permissions" url="<%= permissionsEntryURL %>" />

Step 6 #

Now give ant deploy from ext to the server.Run the server and click the action tab and select permisson it will shows the permissions what ever you have mentioned.

--Now you will able to see those effects which effected in your permission tag which we mentioned in action tag.

Step 7 #

Create the folder permission and place inside ext-impl/src/com/mpower/addressbook/service folder. Now create "AddressPermission.java" program and place inside permission folder.

"AddressPermission.java"

package com.mpower.addressbook.service.permission;

import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.service.AddressLocalServiceUtil;
import com.mpower.addressbook.model.Address;

public class AddressPermission {

	public static void check(
			PermissionChecker permissionChecker, long addressId, String actionId)
		throws PortalException, SystemException {

		if (!contains(permissionChecker, addressId, actionId)) {
			throw new PrincipalException();
		}
	}

	public static void check(
			PermissionChecker permissionChecker, Address address,
			String actionId)
		throws PortalException {

		if (!contains(permissionChecker, address, actionId)) {
			throw new PrincipalException();
		}
	}

	public static boolean contains(
			PermissionChecker permissionChecker, long addressId, String actionId)
		throws PortalException, SystemException {

		Address address = (Address)AddressLocalServiceUtil.getAddress(addressId);

		return contains(permissionChecker, address, actionId);
	}

	public static boolean contains(
		PermissionChecker permissionChecker, Address address,
		String actionId) {

		return permissionChecker.hasPermission(
			0l, Address.class.getName(), address.getAddressId(),
			actionId);
	}
}

Step 7 #

Now we want to add the Resources when we trying to add the record inside the database,as well as we want to delete the allocated permission for that particular when we trying to delete the record. So do the changes in the following files

1.ProcessAddressAction.java 2.AddressLocalServiceImpl.java 3.AddressServiceImpl.java

These files are Regarding to addressbook portlet.

In "ProcessAddressAction.java":

--First change: address = (AddressImpl) AddressServiceUtil.create((Address) address); --The Above line i altered to following address = (AddressImpl) AddressServiceUtil.create((Address) address, userId);

--Second Change: AddressServiceUtil.delete(p_keys); --The Above line i altered to following Long userId = CommonUtil.getUserId(req); AddressServiceUtil.delete(p_keys,userId);

Only two changes in this file.

In AddressServiceImpl.java:

In the following changes we just adding the userid other than that no changes:

--First Change:
public Address create(Address address,long userId)
        throws PortalException, SystemException {
        return AddressLocalServiceUtil.create(address,userId);
    }
--Second Chnage:
 public Address delete(String primaryKey,long userId)
        throws PortalException, SystemException {
        return AddressLocalServiceUtil.delete(primaryKey,userId);
    }

    public void delete(String[] p_keys,long userId) throws PortalException, SystemException {
        AddressLocalServiceUtil.delete(p_keys,userId);
    }

In AddressLocalServiceImpl.java

In this File we going to do Many changes . So I am placing the whole code here.

package com.mpower.addressbook.service.impl;

import com.liferay.counter.service.CounterLocalServiceUtil;

import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.util.Validator;

import com.mpower.addressbook.model.Address;
import com.mpower.addressbook.service.base.AddressLocalServiceBaseImpl;
import com.mpower.addressbook.service.persistence.AddressUtil;

import com.mpower.service.DBUtil;

import java.util.ArrayList;
import java.util.List;

---Imported for Model-permission(Changes Here)
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.service.persistence.UserUtil;
import com.liferay.portal.service.ResourceLocalServiceUtil;
---End.



public class AddressLocalServiceImpl extends AddressLocalServiceBaseImpl {
    public Address create(Address address,long userId)-->Note I added UserId here
        throws PortalException, SystemException {
        long id = CounterLocalServiceUtil.increment(Address.class.getName());
        address.setPrimaryKey(id);

        address.setNew(true);

	--Imported for Model-permission
	User user = UserUtil . findByPrimaryKey(userId);
	addAddressResources(user.getCompanyId(), user.getGroup().getGroupId(), userId,address, true, true);
	--End.

        return AddressUtil.update(address, false);
    }

    --Imported for Adding the Model-permission in the database

    public void addAddressResources(long companyId, long groupId, long userId,Address address,
			boolean addCommunityPermissions, boolean addGuestPermissions)
			throws PortalException, SystemException {
		  ResourceLocalServiceUtil.addResources(companyId, groupId, userId,
				Address.class.getName(), address.getAddressId(), false,
				addCommunityPermissions, addGuestPermissions);
	}
    --End.

    public Address update(Address address)
        throws PortalException, SystemException {
        return AddressUtil.update(address, true);
    }

    public Address delete(String addressId,long userId)-->Note I added UserId here
        throws PortalException, SystemException {
        if (Validator.isNotNull(addressId)) {

	    --Imported for Deleting the Model-permission from the database
	    User user = UserUtil . findByPrimaryKey(userId);
	    ResourceLocalServiceUtil.deleteResource(user.getCompanyId(),
					Address.class.getName(),ResourceConstants.SCOPE_INDIVIDUAL,addressId);
	    
	    --End.

            return AddressUtil.remove(Long.parseLong(addressId));
        }

        return null;
    }

    public void delete(String[] addressIds,long userId)-->Note I added UserId here
        throws PortalException, SystemException {
	 --Declaration for the Model-permission
	       User user=null;
	    --End.
        if (addressIds != null) {
           for (int i = 0; i < addressIds.length; i++) {
                if (Validator.isNotNull(addressIds[i])) {
		    --Imported for Removing the Model-permission from the database
		    user = UserUtil.findByPrimaryKey(userId);
		    ResourceLocalServiceUtil.deleteResource(user.getCompanyId(),
		    Address.class.getName(),ResourceConstants.SCOPE_INDIVIDUAL,addressIds[i]);
		    --End.

                    AddressUtil.remove(Long.parseLong(addressIds[i]));
                }
            }
        }
    }

    public List getByUserId(Long userId)
        throws PortalException, SystemException {
        return AddressUtil.findByUserId(userId);
    }

    public List getAll() throws PortalException, SystemException {
        return AddressUtil.findAll();
    }

    public List findWithDynamicQuery(
        com.liferay.portal.kernel.dao.orm.DynamicQuery queryInitializer)
        throws PortalException, SystemException {
        return AddressUtil.findWithDynamicQuery(queryInitializer);
    }

    public List find(List criteria, boolean _and, List orderBy)
        throws PortalException, SystemException {
        DynamicQuery dqi = DBUtil.getCriteria(Address.class, criteria, _and,
                orderBy);

        return findWithDynamicQuery(dqi);
    }

    public List find(List criteria, boolean _and)
        throws PortalException, SystemException {
        return find(criteria, _and, null);
    }

    public List find(Object criterion, Object orderBy)
        throws PortalException, SystemException {
        List criteria = new ArrayList();
        criteria.add(criterion);

        List orderByList = new ArrayList();
        orderByList.add(orderBy);

        return find(criteria, false, orderByList);
    }

    public Address getByPrimaryKey(String addressId)
        throws PortalException, SystemException {
        return AddressUtil.findByPrimaryKey(Long.parseLong(addressId));
    }
}

--Now we Made all the changes in the java files.

Step 8 #

In "AddressActionUtil.java"

Note: For this portlet we want to make -->This chnange is only for this portlet only.For others No need.

userFilter = false--In two places

Then only every one can view the entries otherwise user will permitted to see user entry,guest will permitted to see guest entry only.

Step 9 #

Now give ant build-service and ant compile to make sure that there is any errors are there. Now we finished successfully altering the java pages.

Step 10 #

Now we want to place the condition for checking whether all the permissions working properly or not.

Apppling Conditions In Jsp Pages

Import the following two import statements where ever you are placing the conditions in Jsp.

Imports In Jsp Page

    <%@ page import="com.liferay.portal.security.permission.PermissionChecker"%>
    <%@ page import="com.mpower.addressbook.service.permission.AddressPermission"%>

Conditions we can give before the buttons

 <c:if test="<%= AddressPermission.contains(permissionChecker, address, "VIEW") %>">
	Here may be any buttons will be available
	Example:list button,view button
  </c:if>

Step 11 #

Now do ant deploy and check the conditions it will work successfully

0 Attachments
42671 Views
Average (2 Votes)
The average rating is 2.0 stars out of 5.
Comments
Threaded Replies Author Date
I tried it for V4 but no luck, please guide me.... Pavan Agrawal October 9, 2009 3:56 AM
Is it possible to add custom permissions for... Hans-Joachim Matheus November 24, 2009 10:20 AM
Hi .. For clarity sake. Can you also include... Mohd Rossi Mam Yudi March 18, 2010 12:49 AM
Adding custom resource-actions to my portlet - ... Mark Stein February 27, 2012 2:26 AM

I tried it for V4 but no luck, please guide me.

Pavan
Posted on 10/9/09 3:56 AM.
Is it possible to add custom permissions for web plugins too?
Or is it possible to import permissions/actions and model-resources via script to the LR database?
Means: Is it possible to use liferay to administrate permissions, roles for (web) applications running out of the portal scope?
Posted on 11/24/09 10:20 AM.
Hi .. For clarity sake. Can you also include the address book portlet as an attachment to this Wiki ? This would clearly help. Thanks!
Posted on 3/18/10 12:49 AM.
Adding custom resource-actions to my portlet - not work for me: Liferay 6.1 emoticon
Posted on 2/27/12 2:26 AM in reply to Mohd Rossi Mam Yudi.