Monday, April 21, 2008

Checking the current user's permission on a web site or a list by code

in answer to a question in the forums:

SPWeb has a "CurrentUser" attribute which gives you a SPUser object. the GetAssignmentByPrincipal function of the RoleAssignments collection of the SPWeb object will get you what roles the current user has.

 

here is an example:

SPWeb web = SPControl.GetContextWeb(this.Context);

SPRoleAssignment assignment = web.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal) web.CurrentUser);

StringBuilder sb = new StringBuilder("");

foreach (SPRoleDefinition role in assignment.RoleDefinitionBindings)

{

sb.AppendLine(role.Name);

sb.AppendLine(role.BasePermissions);

sb.AppendLine("--------------------------------------");

}

 

 

This sample will give you a string with all the information. if you want to check if a use is allowed to add list items

 

note - don't dispose of the SPWeb object in the example above, since it comes from the context.

 

another note - this checks the web site permissions - not the permissions for a specific list. if you want to check a list you will have to get the roles from an SPList object. in the following example I am doing the same for the announements list in the current site:

 

SPList list = SPControl.GetContextWeb(this.Context).Lists["Announcements"];

SPRoleAssignment assignment = list.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal) web.CurrentUser);

StringBuilder sb = new StringBuilder("");

foreach (SPRoleDefinition role in assignment.RoleDefinitionBindings)

{

sb.AppendLine(role.Name);

sb.AppendLine(role.BasePermissions);

sb.AppendLine("--------------------------------------");

}

 

1 comment:

Ajay Yadav said...

It's giving an error.
"Can not find the principal with id: 1073741823."