How to get user belongs to which group in sharepoint? - sharepoint

I have 350 groups in in my sites collection. I need to find a user by passing login name get his groups belongs to? How to get programmatically?

Use SPWeb.AllUsers collection to get the SPUser by login name (alternatively use SPWeb.EnsureUser if you don't know if they have been added yet)
Use SPUser.Groups to get the groups the user is a member of

Checkout this excellent post on ASP.NET forums:
C# Example: How to get all groups, users and roles from SharePoint using SPGroup, SPUser, SPRole ...

CheckOut this one
SPFieldUserValue usersField = new SPFieldUserValue(SPContext.Current.Web);
bool isUser = SPUtility.IsLoginValid(SPContext.Current.Site, usersField.User.LoginName);
SPGroup group = SPContext.Current.Web.Groups.GetByID(usersField.LookupId);

Related

User is part of an AD Group that is nested in the SharePoint group how to relate ad user with SharePoint group

We have added a AD group to SharePoint users group. Now when we login with user, we want to check permission for the logged in AD user.
I have added Ad group (example) managers in SharePoint.
Now I want show some URL links to only the group(managers).
When user logged in, how can I check whether user is manager or not? (Using
CSOM or JSOM)
Unfortunately, the SPGroup.ContainsCurrentUser property that you would use for this in server-side code is not accessible through the JavaScript client object model (at least not in SP2010 and 2013).
Option 1: Use group membership visibility as a workaround
One potential workaround is to exploit a combination of two properties that you can access on groups via the JavaScript client object model: OnlyAllowMembersViewMemberhip and CanCurrentUserViewMembership.
If the current user can view group membership for a group that is only set to allow group members to do so, we can assume the user is a group member.
var clientContext = new SP.ClientContext();
var groupId = 5; // the group membership ID for the group you want to check
var group = clientContext.get_web().get_siteGroups().getById(groupId);
clientContext.load(group,"CanCurrentUserViewMembership");
clientContext.load(group,"OnlyAllowMembersViewMembership");
clientContext.executeQueryAsync(
function(sender,args){
var isMemberOfGroup = group.get_canCurrentUserViewMembership() && group.get_onlyAllowMembersViewMembership();
if(isMemberOfGroup){
doSomething();
}
},
function(sender,args){alert("Whoops! "+args.get_message());}
);
This approach will only work if you've set the groups to only be visible to members, and it'll always return a false positive if you have elevated access, such as if you're a site collection administrator or the group owner.
How to Iterate Through All Site Groups
If you want to apply the above logic to check the current user's membership in all groups on the site (instead of specifying a group by its ID), you can use the modified JavaScript code below.
var clientContext = new SP.ClientContext();
var groups = clientContext.get_web().get_siteGroups()
clientContext.load(groups,"Include(CanCurrentUserViewMembership,OnlyAllowMembersViewMembership,Title)");
clientContext.executeQueryAsync(
function(sender,args){
var groupIterator = groups.getEnumerator();
var myGroups = [];
while(groupIterator.moveNext()){
var current = groupIterator.get_current();
var isMemberOfGroup = current.get_canCurrentUserViewMembership() && current.get_onlyAllowMembersViewMembership();
if(isMemberOfGroup){
myGroups.push(current.get_title()); // this example adds group titles to an array
}
}
alert(myGroups); // show the array
},function(sender,args){"Whoops! "+alert(args.get_message());});
Option 2: Use Audience Targeting as a workaround
For your requirements you may not even need programmatic access to the group membership. You could just set audience targeting on the web parts that you want to be visible only to certain groups; audience targeting should respect AD group membership.

Get SPUser object

I am trying this code to get SPUser object but it keeps throwing exception of user not found even when it returns true for DoesUserHavePermissions(..., does anyone know any fix or way around ?
if (web.Site.RootWeb.DoesUserHavePermissions("UserLoginName", SPBasePermissions.Open))
{
SPUser user = web.Site.RootWeb.Users["UserLoginName"];
}
Can't use web.Ensure
According to MSDN:
SPWeb.Users contains user objects that are explicitly assigned permissions in the website.
SPWeb.AllUsers contains user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.
So use AllUsers collection
SPUser user = web.Site.RootWeb.AllUsers["UserLoginName"];

Is it possible to grant permission for groups (in SharePoint) to a site programmatically?

I am using the SharePoint Object Model to create new sites programmatically (with a custom web part). It works fine but I am wondering if it is possible to grant permission for groups as well?
When I create the site I have set it to not inherit permission
newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(siteUrl, siteName, siteDescription, (uint)1033, siteTemplate, true, false);
In the GUI I can then go to Site Actions (on the newly created site) -> Grant Permission -> search for groups in the parent site and then grant permission for this group. So, in the parent site myGroup can have Full Access permissions but in this site I can set it to Contribution or whatever. Is it possible to do this when I create the site or just after (programmatically)?
Thanks in advance.
You must assign a role definition to your group.
Here's a code snippet I wrote to assign a group one of the predefined sharepoint role definitions.
public bool AssignExistingGroupToWeb(SPWeb siteWeb, string GroupName, SPRoleDefinition roleDefinition)
{
//retrieve a group
SPGroup siteGroup = siteWeb.SiteGroups.FindGroupByName(GroupName);
//create a role assignment for the group using the specified SPRoleDefinition
//examples of roles as "Full Control", "Design", etc...
SPRoleAssignment roleAssignment = new SPRoleAssignment(siteGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
siteWeb.RoleAssignments.Add(roleAssignment);
siteWeb.Update();
}
You can retrieve a SPRoleDefinition by accessing the RoleDefinitions collection, like so...
siteWeb.RoleDefinitions["Contribute"]

Cannot access site groups with user with manage hierarchy permissions

I have a custom form that lists the site groups and the users in each group.
the form has twi drop down lists: one to display the site's group and the other to display the users in that group.
when I log to the form with the administrator user it works fine.
But if I log in with a user with manage hierarchy permission level, it omly displays the info of the domain groups and if I try to access a sharepoint group I get an access denied error.
I use run with elevated permissions in my code
I really don't know what to do in this
thanks.
Two common mistakes when using RunWithElevatedPrivileges is:
Using the SPContext.Current.Web (or Site etc) won't change the identity of the web object, it is already in memory.
Declaring the SPWeb outside the delegate, with similar results of mistake 1
That said, try something like:
Guid siteId = SPContext.Current.Site.Id;
SPSecurity.RunWithElevatedPrivileges(() =>
using (SPSite elevatedSite = new SPSite(siteId))
using (SPWeb elevatedWeb = elevatedSite.RootWeb)
{
//impl
});

SharePoint WebPart Permissions

Hi I am using the SharePoint namespace for a webpart and I encounter some permission errors when I try to use the System account. Is there a way I can use a defined user instead of the system account?
Right now I have:
SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite site = new SPSite(_SPSite, sysToken))
I want to be able to use an account on the domain instead of the System account, thanks for any advice.
You may need to use RunWithElevatedPermissions to get access to the System account to work, as per the following blog post:
http://solutionizing.net/2009/01/06/elegant-spsite-elevation/
You can use the SPUserCollection
SPContext.Current.Site.RootWeb.AllUsers
to get all of the users on the site, and get the SPUser from there. Once you have the SPUser you can get the UserToken.
What are you trying to do? If you don't use a token, the web will be opened with the same permissions as the current user
/* runs as user requesting the web part */
SPSite site = SPContext.Current.Web.site
or you can wrap it in the RunWithElevatedPrivileges delegate
/* runs with admin privileges */
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Web.Site.Url))
{
//do stuff
}
}
);

Resources