Forum Discussion
Right User Permissions to use ListItem.GetUserEffectivePermissions method
I'm currently using a SharePoint account as a Service account to get files and share them in an application I'm working on using CSOM. I filter the files according to the logged-in user to check if the user has no access to the file, then I hide it, to prevent him from trying to access it and get "Permission Denied" error.
So, I used ListItem.GetUserEffectivePermissions for this issue, but I need to grant the user only the permissions he needs to access and make that check.
I checked the official documentation of ListItem.GetUserEffectivePermissions here but unfortunately, I found no direct clue which permission does the job.
So to recap what this service account needs to do is :
- Execute Search across all sharepoint files [SearchExecutor].
- Get Login Name by Email using Utility.ResolvePrincipal (to be used in GetUserEffectivePermissions function).
- Use GetUserEffectivePermissions to check if the logged-in User has permission to view the file.
I'd really appreciate your help as I'm kind of new to SharePoint and I searched a lot but found no clue about what I need.
- G_Vijai_KumarCopper ContributorHere is the response for your questions
- SharePoint Farm Administrator account can be used to perform search across all SharePoint files
- You can use the Utility.ResolvePrincipal method in SharePoint to get the login name
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
string email = "email address removed for privacy reasons";
string loginName = string.Empty;
using (SPSite site = new SPSite("http://your-sharepoint-site-url-goes-here....."))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPUser user = web.EnsureUser(email);
loginName = user.LoginName;
}
catch (SPException ex)
{
SPPrincipalInfo principalInfo = Utility.ResolvePrincipal(web, email, SPPrincipalType.User, SPPrincipalSource.Windows, true);
if (principalInfo != null)
{
loginName = principalInfo.LoginName;
}
}
}
}
Console.WriteLine("The login name for the email address {0} is {1}", email, loginName);
- Here is the source for GetUserEffectivePermissions method in SharePoint to check if the logged-in user has permission to view file.
string fileUrl = "http://document-library-filename-url";
SPUser currentUser = SPContext.Current.Web.CurrentUser;
using (SPSite site = new SPSite("http://your-sharepoint-site-url"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile(fileUrl);
if (file.Exists)
{
SPRoleDefinitionBindingCollection permissionCollection = file.Item.RoleAssignments.GetEffectivePermissions(currentUser);
if (permissionCollection.Web.AllowAnonymousAccess && permissionCollection.Contains(SPBasePermissions.ViewListItems))
{
}
else if (permissionCollection.Contains(SPBasePermissions.ViewListItems))
{
}
else
{
}
}
else
{
// The file does not exist
}
}
}