Code Project

Link Unit

Monday, March 22, 2010

DoesUserHavePermissions in WebPart

I wrote a search webpart and it need check if the current user has the right to some lists so I can highlight those lists in different color , but Whenever SPList.DoesUserHavePermissions is called on the object[List/Library], for the user who does not have the permission, it should return false, but it gives an exception. An IE browser pops up asking for user to type in username and password. This dialog box should not appear as my code catches the exception.
Solution: After googling around for some solution on the same line , found points which may help fellow visitors.
#1 DoesUserHavePermissions only works in WSS, not SPS
#2 Suppress Popup for Unauthorized Access:The problem happens with your SPSite object from which you get the web, then the list, there is a property called CatchAccessDeniedException, you should set it to false, then make your call, end the popup will not show up. This is a standard WSS feature, and will happen every time you try to access a resource to which the current user does not have access.
WorkAround : Use the following in your webpart

=====
using(SPWeb oWeb=SPContext.Current.Web)
{
oSite.CatchAccessDeniedException = false; // Suppress the popup
SPListCollection oList = oWeb.Lists;
oList.ListsForCurrentUser = true;
int iCount = oList.Count;
for(int i=0;i{
try
{
if(oList[i].Permissions.DoesUserHavePermissions(SPRights.ViewListItems)) // Check for view Rights
{
// Do something
}
}
catch(System.UnauthorizedAccessException ex)
{
//Do Nothing, or as you please
}
}
}
=====


Hope this helps