Get SPUser object - sharepoint

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"];

Related

Sitecore 6 Is it possible to change roles for virtual user when already logged in?

In Sitecore 6 is it possible to change roles for virtual user when already logged in?
I would like to change roles for virtual users that are already logged in to system, but it looks like Sitecore ignores it. I can clear roles and add a new one but all the old roles are still attached to the user.
I think I should to re-login the user but it is not the case for me.
virtualUser.RuntimeSettings.AddedRoles.Clear();
virtualUser.Roles.RemoveAll();
if (permissions != null && permissions.Any())
{
foreach (var role in permissions.Where(d=>!string.IsNullOrEmpty(d.Type)))
{
string domainRole = string.Format("{0}\\{1}", "extranet", role.Type);
if (SC.Security.Accounts.Role.Exists(domainRole))
{
virtualUser.RuntimeSettings.AddedRoles.Add(domainRole);
}
}
}
You can try to use
Sitecore.Caching.CacheManager.ClearSecurityCache(userName);
This method calls another methods:
CacheManager.ClearUserProfileCache(userName);
CacheManager.ClearIsInRoleCache(userName);
CacheManager.ClearAccessResultCache(userName);
So in theory it should do what you need but I haven't confirmed it in practice.
It seems to be that login-out and re-login will set the correct roles because during login the AuthenticationManager will clear the SecurityCache which holds the UserProfile and the Roles.
I don't see a method to add new Roles to the current authenticated user.

SharePoint 2010 Access Denied - Logged in user doesn't have permission to view the mebership of this sharepoint group

I have a scenario in my custom visual web part where I need to check for logged in User is a member of sharepoint group(sharepoint groups or users are stored in a sharepoint list). Actually if logged in users exists in the list, he will be given Edit access in my custom web part.
Since I have created a group name "SharePoint_Owners" with group settings as 'Who can View Membership of this group' to 'Group Members', Site is throwing error as 'Access denied' as logged in user doesn't have permission to view. I get error when my code executes this,
SPGroup oGroup = oWebsite.SiteGroups[strgroup];///strgroup is a group name
foreach (SPUser oUser in oGroup.Users) { }
Site throws this error when I try to open page which consists my webpart.
Can any one suggest me how do i proceed? is there a way to resolve this programmatically without actually giving View permission to "Everyone" for each group??
I thought RunWithElevatedPrivileges does my work but have no luck!
please help
Try this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string siteURL = SPContext.Current.Site.Url;
using (SPSite safeSite = new SPSite(siteURL))
{
using (SPWeb safeWeb = safeSite.OpenWeb())
{
SPGroup group = safeWeb.Groups["SharePoint_Owners"];
bool isMember = safeWeb.IsCurrentUserMemberOfGroup(group.ID);
}
}
});

How to get user belongs to which group in 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);

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
});

Resources