I am using the following code to set permission for groups when I create a site:
// Assign Site Owner role to the selected users
string siteOwnerGroup = null;
string siteOwnerRole = null;
foreach (ListItem item in lbSiteOwner.Items)
{
siteOwnerGroup = item.Text.ToString();
siteOwnerRole = "Full Control";
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteGroups[siteOwnerGroup]);
SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
roleDefinition.Add(web.RoleDefinitions[siteOwnerRole]);
web.RoleAssignments.Add(roleAssignment);
web.Properties[siteOwnerGroup] = siteOwnerRole;
web.Properties.Update();
}
Shouldn't it be easy to change this to set permission for users in the lbSiteOwner listbox instead?
I tried
SPRoleAssignment roleAssignment = new SPRoleAssignment(web.SiteUsers[siteOwnerGroup]);
But it doesn't work, any ideas?
Thanks in advance.
following solution will hold true in your case as well in place of list use web
Programatically add user permission to a list in Sharepoint
Related
I'm creating a new list in CSOM for SharePoint Online, but I'm very new to this so I'm stuck on changing the permissions.
There are 3 user groups, owners, visitors and members. I'd like to give the visitors editing rights on this list.
I've managed to break inheritance and get all the visitors with the following code, but I'm stuck on how to give them new permissions
newList.BreakRoleInheritance(false, true);
var visitors = ctx.Web.SiteGroups;
ctx.Load(visitors, groupitems => groupitems.Include(groupitem => groupitem.Title,
groupitem => groupitem.LoginName).Where(groupitem=> groupitem.Title == visitorsGroupName));
You can do something similar to this one:
foreach(var grpUser in grpUsers)
{
Principal user = ctx.Web.SiteUsers.GetByLoginName(grpUser);
RoleDefinition writeDefinition = ctx.Web.RoleDefinitions.GetByName("Edit");
RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(ctx);
roleDefCollection.Add(writeDefinition);
RoleAssignment newRoleAssignment = ctx.Web.RoleAssignments.Add(grpUser, roleDefCollection);
}
ctx.ExecuteQuery();
This assumes that there is an "Edit" permission level which is available by default in SharePoint. Let me know if it works.
You could try this
var EditRole= new RoleDefinitionBindingCollection(ctx);
EditRole.Add(ctx.Web.RoleDefinitions.GetByType(RoleType.Editor));
Microsoft.SharePoint.Client.Group visitors= ctx.Web.SiteGroups.GetByName("visitors");
ctx.Load(visitors);
newList.RoleAssignments.Add(visitors, EditRole);
ctx.ExecuteQuery()
I have a list contained in an SPWeb and when the web is provisioned an event receiver change the list permissions by using this code:
[...]
SPList theList = web.Lists[listName];
theList.BreakRoleInheritance(false);
SPGroup group = web.Groups["MyGroup"];
SPRoleAssignment ra = new SPRoleAssignment(group);
SPRoleDefinition roleDef = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
ra.RoleDefinitionBindings.Add(roleDef);
list.RoleAssignments.Add(ra);
list.Update();
Later in the workflow I need to change the permission for the group to be Reader instead of Contributor. I have used the following code
SPList theList = web.Lists[listName];
foreach (SPRoleAssignment assignment in theList.RoleAssignments) {
if (assignment.Member.Name == "MyGroup") {
assignment.RoleDefinitionBindings.RemoveAll();
SPRoleDefinition rda = web.RoleDefinitions.GetByType(SPRoleType.Reader);
assignment.RoleDefinitionBindings.Add(rda);
}
}
However this code is not working and does not change the permission on the list.
Could anybody help on understanding which is the right method to change permission for an existing principal?
Thanks
You need to do a theList.Update() after your foreach statement.
I have LDAP imported user groups which I have mapped to site roles (as mapping them to organization roles was not possible for Liferay 6.1).
So for example I have mapped the user group 'my_site administrators' to the site role 'Site Administrators' of the site 'my_site'.
How can I get all the users that are members of a site role taking into account the user group memberships too?
I have tried the following code but did not work.
Set<User> siteMembers = new HashSet<User>();
Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());
Integer[] types = new Integer[]{Integer.valueOf(2)}; //site roles
List<Role> siteRoles = RoleLocalServiceUtil.search(group.getCompanyId(), null, types, 0, 10, null);
Set<UserGroupRole> siteUserGroupRoles = new HashSet<UserGroupRole>();
for (Iterator<Role> iterator = siteRoles.iterator(); iterator.hasNext();) {
Role siteRole = (Role) iterator.next();
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(group.getGroupId(), siteRole.getRoleId());
siteUserGroupRoles.addAll(userGroupRoles);
}
for (Iterator<UserGroupRole> it1 = siteUserGroupRoles.iterator(); it1.hasNext();) {
UserGroupRole userGroupRole = (UserGroupRole) it1.next();
User userGroupUser = userGroupRole.getUser();
siteMembers.add(userGroupUser);
}
Finally found the following solution:
Set<User> siteMembers = new HashSet<User>();
Group group = GroupLocalServiceUtil.getGroup(layout.getGroupId());
long groupId = group.getGroupId();
Integer[] types = new Integer[]{Integer.valueOf(2)}; //site roles
List<Role> siteRoles = RoleLocalServiceUtil.search(group.getCompanyId(), null, types, 0, 10, null);
Set<UserGroupGroupRole> siteUserGroupGroupRoles = new HashSet<UserGroupGroupRole>();
for (Iterator<Role> iterator = siteRoles.iterator(); iterator.hasNext();) {
Role siteRole = (Role) iterator.next();
List<UserGroupGroupRole> userGroupGroupRoles = UserGroupGroupRoleLocalServiceUtil.getUserGroupGroupRolesByGroupAndRole(groupId, siteRole.getRoleId());
siteUserGroupGroupRoles.addAll(userGroupGroupRoles);
}
for (Iterator<UserGroupGroupRole> it1 = siteUserGroupGroupRoles.iterator(); it1.hasNext();) {
UserGroupGroupRole userGroupGroupRole = (UserGroupGroupRole) it1.next();
long userGroupId = userGroupGroupRole.getUserGroupId();
List<User> userGroupUsers = UserLocalServiceUtil.getUserGroupUsers(userGroupId);
siteMembers.addAll(userGroupUsers);
}
siteMembers.addAll(UserLocalServiceUtil.getGroupUsers(groupId));
It does not seem straight-forward. I would expect a method fetching all site members, even the indirect ones through site role-user group-user mapping.
I had to fetch separately all users belonging to all user groups having a site role association with the site and on top of that fetch all users with direct membership to the site.
Any other more straight-forward solution would be welcome.
When we associate any site roles to user then association will be stored in UserGroupRole table.When ever we want get site roles then we have to use respective service class to access those roles like we need use UserGroupRoleLocalService.java class there we can find many service methods.
UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(themeDisplay.getScopeGroupId(),supervisorRole.getRoleId());
And then you can get userId from UserGroupRole object.
I'm trying to establish whether a specific group has Read access to a particular site collection.
I have been trying for a day and a half but feel as if I have found three halves of different solutions!
The code fragments I have so far are:
using (SPSite site = new SPSite(this.GenerateAbsoluteUri(moduleCode, academicYear)))
{
using (SPWeb web = site.OpenWeb())
{
for (int i = web.SiteGroups.Count - 1; i >= 0; i--)
{
SPGroup group = web.SiteGroups[i];
if (Regex.IsMatch(group.Name, theGroupImLookingFor))
{
but then what?!
Most of my Google results tell me about roles but I don't know how to tie a role to a group.
Please help!
To assign permission to a user (account) or a SharePoint group there are some objects that we need to look at in a certain order. The first thing we need to do is get the the security principal that we want to assign the role to (SPUser or SPGroup). The next thing we need to do it get the actual permission (role) that we want to assign (ex: Read, Full Control etc…). Then we need to create a SPRoleAssignment object and on the constructor pass it in the SPUser or SPGroup (security principal) that we want to assign the permissions to. Now we need to add the role definition to the RoleDefinitionBindings collection of the role assignment object. Then we need to add the actual role assignment to the web (site) and update the web. Below is the full code lisitng.
// Create the site that contains our list
using(SPSite oSite = new SPSite("<<my site url>>"))
{
// Open the web object
using(SPWeb oWeb = oSite.OpenWeb())
{
// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<<group name>>"];
// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];
// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);
// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);
// Now update the web
oWeb.Update();
}
}
Heres snippets from my own code (Sharepoint 2010).
Creating a role:
SPRoleDefinition network_role = new SPRoleDefinition();
network_role.BasePermissions = SPBasePermissions.AddListItems |
SPBasePermissions.BrowseDirectories |
SPBasePermissions.EditListItems |
SPBasePermissions.DeleteListItems;
network_role.Name = "Network - Project Member";
network_role.Description = "Provides permissions required for a member of a project.";
web.RoleDefinitions.Add(network_role);
Adding a role to a group:
var assign = new SPRoleAssignment(oweb.SiteGroups["Network Project - " + item.Code]);
assign.RoleDefinitionBindings.Add(network_role);
on the project i'm working we have a site (the front office) which is accessible by anonymous users, and a subsite (the back office) which access is restricted. In the back office, i want to restrict the access of one specific page (e.g, /Pages/specificpage.aspx) to only users who are members of a certain group.
How can i do that programmatically?
Thanks.
First you create a group for this permission type. You do that from the "People and Groups" page.
Then you go to your Pages list by browsing to the http:/Pages.
Click on the drop down menu on the page/item in question and select "manage permissions".
On the Actions menu, select "Edit permissions" and click Ok to break inheritance.
Remove the default (inherited) permissions (user/groups) by put a check mark in them and select Action-s>Remove User Permissions.
On the New menu, select "Add users", enter the name of your group , select the desired permissions and click Ok.
And here's how to do it programmatically:
using (SPSite site = new SPSite("<YOUR URL>"))
{
using (SPWeb web = site.OpenWeb())
{
// Get the group you want to assign to the item
SPGroup group = web.Groups["<YOUR GROUP NAME>"];
SPPrincipal principal = group as SPPrincipal;
// Define the role definitions
SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
SPRoleDefinition[] rolesToApply = new SPRoleDefinition[1] { roleDefinitions["Contribute"] };
// Or whatever role definition you want to assign
SPRoleAssignment newRoleAssignmentToAdd = new SPRoleAssignment(principal);
foreach (SPRoleDefinition roleDefinition in rolesToApply)
{
if (roleDefinition != null)
{
newRoleAssignmentToAdd.RoleDefinitionBindings.Add(roleDefinition);
}
}
// Choose your list
SPList list = web.Lists["Pages"];
// Query for the item/file/page
SPQuery query = new SPQuery();
query.RowLimit = 2000;
query.ViewFields = "<FieldRef Name='Title' />";
query.Query = string.Format(#"<OrderBy><FieldRef Name='ID'/></OrderBy>
<Where>
<Eq>
<FieldRef Name='FileLeafRef'/>
<Value Type='Text'>{0}</Value>
</Eq>
</Where>", "<YOUR PAGE NAME>");
// Get the list item
SPListItemCollection items = list.GetItems(query);
if (items.Count > 0)
{
SPListItem item = items[0];
// If the item doesn't have unique permissions, set it to have that
if (!item.HasUniqueRoleAssignments)
{
item.BreakRoleInheritance(false);
}
// Add your role definition
item.RoleAssignments.Add(newRoleAssignmentToAdd);
}
}
}
To set the permissions pragmatically you need to do the following.
1) Break Role Inheritance of the item
2) Add the new role assignment
To break the Break Role Inheritance of an item you call the BreakRoleInheritance method on the item, passing true will copy the current permissions for the list to the item.
item.BreakRoleInheritance(false);
You then need to get the items Role Assignments collection and add a new role assignment to it. The role assignment is created for a SPPrincipal and has a SPRoleDefinition bound to it.
SPRoleAssignmentCollection rolesAssignments = item.RoleAssignments;
SPRoleAssignment userRoleAssignment = new SPRoleAssignment(principal);
userRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
rolesAssignments.Add(userRoleAssignment);
To fetch a Role Definition you can go to the current SPWeb’s FirstUniqueRoleDefinitionWeb property so you keep any customisations that have been made to your sites permissions and then use the SPWeb’s Role Definitions Collection. (I am not too sure of the disposal pattern for the FirstUniqueRoleDefinitionWeb property, if you are using SPContext Dont dispose it)
if (web.FirstUniqueRoleDefinitionWeb != null)
{
using (SPWeb firstUniqueRoleDefinitionWeb = web.FirstUniqueRoleDefinitionWeb)
{
return firstUniqueRoleDefinitionWeb.RoleDefinitions[roleName];
}
}
return web.RoleDefinitions[roleName];
Hope this helps you in the right direction