How can I list all SPUser objects in a SPGroup? - sharepoint

I need to retrieve all SPUser's from a SPGroup. Unfortunately, the group may contain Active Directory groups, so a simple SPGroup.Users is not enough (I'd just get a single SPUser for the AD group, with the IsDomainGroup property set to true).
Does anyone have a good idea how can I obtain a list of all SPUser's, descending into any Active Directory groups contained in a SPGroup? Is there an alternative to SPGroup.ContainsCurrentUser that takes a SPUser parameter?

Based on a blog post I found, I have written the following code:
private static List<SPUser> ListUsers(SPWeb web, SPPrincipal group)
{
try
{
web.Site.CatchAccessDeniedException = false;
var users = new List<SPUser>();
foreach(SPUser user in web.SiteUsers)
{
using(var userContextSite = new SPSite(web.Site.ID, user.UserToken))
{
try
{
using (var userContextWeb = userContextSite.OpenWeb(web.ID))
{
try
{
if (userContextWeb.SiteGroups[group.Name]
.ContainsCurrentUser)
users.Add(user);
}
catch (SPException)
{
// group not found, continue
}
}
}
catch(UnauthorizedAccessException)
{
// user does not have right to open this web, continue
}
}
}
return users;
}
finally
{
web.Site.CatchAccessDeniedException = true;
}
}
I don't like the fact that I have to impersonate every single user, and this code will only find AD users that have already been imported into SharePoint (so an SPUser exists for them), but that's good enough for me.

Unfortunately, it may be the case that not every member of the AD group has a corresponding SPUser object in the site (yet).
In this scenario, I'd enumerate all the members of the active directory group, and force them into the site with the SPWeb's EnsureUser() method, which returns an SPUser, and creates a new one if it doesn't already exist in the site.
For guidance on enumerating active directory members, see Get List of Users From Active Directory In A Given AD Group.

Related

SPuser to find group membership

I have a code in which I have to check if a user is a part of a certain group (lets say "GroupA").
I have the user details stored in the Sharepoint variable SPUser. Now I need to check if this user is a part of GroupA and then take some action.
How can I achieve this?
Source : How to check if a user exists in a group
you can use following extension method, like this:
public static bool InGroup(this SPUser User, string GroupName)
{
return User.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == GroupName.ToLower());
}
Then call it like this:
bool inGroup = spuser.InGroup("GroupName");
If you want to check the current user then another approach can be like this:
From: Check user already exist in specified SharePoint Group
SPWeb web = SPContext.Current.Web;
SPGroupCollection webGroups = web.Groups;
foreach (SPGroup group in webGroups)
{
//Checking the group
if (group.ContainsCurrentUser)
{
// perform action
}
else
{
//perform action
}
}
For More Reference:
Tell if user exists in SharePoint Group through web service

Control Report Permission Based on Parameters in Reporting Services

Assume we have a report called SalesSummary for a large department. This department has many smaller teams for each product. People should be able to see information about their own product, not other teams' products. We also have one domain group for each of these teams.
Copying SalesSummary report for each team and setting the permission is not the best option since we have many products. I was thinking to use a code similar to below on RS, but it doesn't work. Apparently, System.Security.Principal.WindowsPrincipal is disabled by default on RS.
Public Function isPermitted() As Boolean
Dim Principal As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
If (Principal.IsInRole("group_prod")) Then
Return true
Else
Return false
End If
End Function
I also thought I can send the userID from RS to SQL server, and inside my SP I can use a code similar to below to query active directory. This also doesn't work due to security restriction.
SELECT
*
FROM OPENQUERY(ADSI,'SELECT cn, ADsPath FROM ''LDAP://DC=Fabricam,DC=com'' WHERE objectCategory=''group''')
Is there any easier way to achieve this goal?
Thanks for the help!
The first option you suggested (using embedded code to identify the executing user) will not be reliable. SSRS code is not necessarily executed as the user accessing the report, and may not have access to that users credentials, such as when running a subscription.
Your second approach will work, but requires the appropriate permissions for your SQL server service account to query Active Directory.
Another approach is to maintain a copy of the group membership or user permissions in a SQL table. This table can be updated by hand or with an automated process. Then you can easily incorporate this into both available parameters and core data queries.
So I ended up with this code:
PrincipalContext domain = new PrincipalContext(ContextType.Domain, "AD");
UserPrincipal user = UserPrincipal.FindByIdentity(domain, identityName);
//// if found - grab its groups
if (user != null)
{
PrincipalSearchResult<Principal> _groups = null;
int tries = 0;
//We have this while because GetGroups sometimes fails! Specially if you don't
// mention the domain in PrincipalContext
while (true)
{
try
{
_groups = user.GetGroups();
break;
}
catch (Exception ex)
{
logger.Debug("get groups failed", ex);
if (tries > 5) throw;
tries++;
}
}
// iterate over all groups, just gets groups related to this app
foreach (Principal p in _groups)
{
// make sure to add only group principals
if (p is GroupPrincipal)
{
if (p.Name.StartsWith(GROUP_IDENTIFIER))
{
this.groups.Add((GroupPrincipal)p);
this.groupNames.Add(p.Name);
}
}
}
}
Now, that you have a list of related group you can check the list to authorize the user!

Check the Sharepoint user exists in AD

If a user is removed from AD, the user still exists in sharepoint. Now i want to check if a user exists in AD, so is there any sharepoint object model can do this?
Thanks in advance.
If the user is in the domain user Group, it collects all users under that user group and loops the list to that try to find the current user. If a user is found, it returns true, otherwise returns false.
Check this article Check Whether User Exists in Active Directory that include some security related issues to achieve the requirement.
// Get ad users in the groups. Since MOSS does
// not support nested groups
// this will always be a collection of AD users
// and groups
foreach (SPUser user in group.Users)
{
// Check if this is a Group
if (!user.IsDomainGroup)
{
// Verify if the user name matches the user name in group
if (user.LoginName.ToUpper().Equals(upperCaseUserName))
{
// if a match is confirmed, return from the method.
// There is no need to continue
userIsInGroup = true;
return;
}
}
else {
// If the AD entity is a User Group,
// then check for users in that group
if (IsUserInADGroup(web, user.LoginName,
username, out reachedMax))
{
userIsInGroup = true;
return;
}
}
Hope this help..

In SharePoint, is it possible to programmatically get the current list of users associated with the "nt authority/authenticated users" group?

In SharePoint, I'd like to find out all of the users who have been given access to a site.
If the user is directly granted permissions, granted permissions via a SharePoint group, or granted permissions via a domain group; then I'm able to get the necessary information.
However, if the user is granted permissions via the "authenticated users" group, I am not sure how to find the list of users associated with that group.
Is this possible?
This is more of a .Net question than a Sharepoint question. Yes, you can do this - use the AD APIs to query your domain controller for a list of all users. Here is some code to get you started on programmatic AD access:
http://www.codeproject.com/KB/system/everythingInAD.aspx
You could try to do a query for all objects in AD that are Users.
Please note that this will not list any users outside of AD that might have access to the Sharepoint content. Also, if you have multiple domains, be sure to query all of the AD domains that might have access to the Sharepoint server.
Kyle, thanks for the response.
Using that information, I came up with the following to get all of the users in all of the domains:
private List<Principal> GetAllAuthenticatedUsers()
{
List<Principal> users = new List<string>();
foreach (string domain in GetAllDomains())
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, domain);
// Create search condition for all enabled users
PrincipalSearcher searcher = new PrincipalSearcher();
UserPrincipal user = new UserPrincipal(context);
user.Enabled = true;
user.Name = "*";
searcher.QueryFilter = user;
// Get the users
System.DirectoryServices.AccountManagement.PrincipalSearchResult<Principal> results = searcher.FindAll();
foreach (Principal principal in results)
{
users.Add(principal);
}
}
catch
{
}
}
return users;
}
private static List<string> GetAllDomains()
{
List<string> domains = new List<string>();
using (Forest forest = Forest.GetCurrentForest())
{
foreach (Domain domain in forest.Domains)
{
domains.Add(domain.Name);
}
}
return domains;
}

Creating a custom Document Library in SharePoint

I have a document library in my SharePoint page and there are 10 documents in it.
If User A is logged in I want him to only see 5 of those documents in that document library.
How can I create some custom document library for this to work?
I have MOSS installed.
Thanks in advance!
You could configure different permissions on each document in the document library. Just select the "Manage Permissions" option on each item and break the permission inheritance from the document library level. Just note that having too many documents with item level permissions can create a maintenance nightmare for you. Another option could be to create two document libraries with different permissions.
Write an ItemEventReceiver that breaks the permissions based on a field in the library, i.e. a column that holds the different roles .
We have done this by creating a list that holds all roles coupled to sharepoint groups.
i.e.
Administrator -> Owners of website (SPGroup), Company Administrators (SPGroup)
Managers -> Managers (SPGroup)
then in our content type we have a lookup column to this list.
Here's the code for the ItemEventReceiver:
public override void ItemUpdated(SPItemEventProperties properties)
{
lock (_lock)
{
try
{
using (SPSite site = new SPSite(properties.SiteId,
properties.ListItem.ParentList.ParentWeb.Site.SystemAccount.UserToken))
using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
{
web.AllowUnsafeUpdates = true;
var item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);
var roles = item["Roles"] as SPFieldLookupValueCollection;
var rolesList = web.Site.RootWeb.Lists["Company Roles"];
var groupsToAdd = new List<SPFieldUserValue>();
if (item.HasUniqueRoleAssignments)
{
item.ResetRoleInheritance();
item = item.ParentList.GetItemById(item.ID);
}
if (roles != null && roles.Count > 0)
{
// Iterate over the roles and see if there is a group associated
foreach (var role in roles)
{
var roleItem = rolesList.GetItemById(rol.LookupId);
if (roleItem != null)
{
// This is the SPgroup field in the rolesList
var groups = roleItem["Groups"] as SPFieldUserValueCollection;
if (groups != null)
{
groupsToAdd.AddRange(from g in groups
where g.User == null
select g);
}
}
}
if (groupsToAdd.Count > 0)
{
item.BreakRoleInheritance(false);
foreach (var value in groupsToAdd)
{
var group = web.Groups[value.LookupValue];
var assignment = web.RoleAssignments.GetAssignmentByPrincipal(group);
item.RoleAssignments.Add(assignment);
}
}
}
DisableEventFiring();
item.SystemUpdate(false);
EnableEventFiring();
}
}
catch (Exception ex)
{
//LOG ERROR
}
}
}
If the coding doesn't work for you, and you'd rather not set permissions on each file, then there is a third option. We use folders with permissions set on them.
e.g.
Create a folder called "Managers", break permissions, and set rights to only the managers.
Create another folder called "Employee 1", break permissions, and set Contribute rights to the Employee and the Employe's manager.
Place the files in the appropriate folders and it will inherit rights from the folder.
This way, managers can see the manager files, and all files of their employees. Users can only see their own files.
Similar logic can be done for Headquarters, Region 1, Region 2, etc ... and creating different Groups for each region and then assigning the group to the folder's permissions.
Note, there's always concern in using this design on maintaining all the permissions and on performance, but we've been doing similar things for 750+ user populations and thousand of docs and it's been working fine for us so far.

Resources