Sometimes security may be one of the major issues while writing codes. A user who has only read permission can’t add a new list item, can’t edit a list item, can’t delete a list item – In this case if we try to perform any of these operation, it will throw an exception. There may be items that the user can access but the user still doesn’t have access to perform a specific task hence, there is a great reason to check for permissions before attempting any of these operations. One of the great things about the object model is that it is security trimmed, so it will be a best practice while writing code to just check whether the current user has permissions before performing any item operations.
The following sample shows how to check adding list item permissions for the current user.
using (SPSite spSite = new SPSite("http://MySiteUrl")) { using (SPWeb spWeb = spSite.OpenWeb()) { // Get the current user. SPUser currentUser = spWeb .SiteUsers[HttpContext.Current.User.Identity.Name.ToString()]; // Get the list. SPList spList = spWeb.Lists["MyList"]; // Variable to determine permission. bool userPermission = spList.DoesUserHavePermissions(currentUser, SPBasePermissions.AddListItems); if ( userPermission ) { // Perform operation here. } } }
The local variable “userPermission” will set to True if the user can add items in list otherwise it will set to false.
Similarly,
For viewing list item
bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.ViewListItems); For editing list item bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.EditListItems); For deleting list item bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.DeleteListItems);