Enumerate user's permissions

To manage authorization in SharePoint you define a set of roles with permissions that is assigned to groups and users. It is a versatile model with many possibilities.

But because of its complexity it is a not as easy as one might think to get a list of what each user can do with a SP object. This little snippet will help a long way to provide that overview.

class UserPermission  
    public SPUser User { get; private set; }
    public SPBasePermissions Permissions { get; private set; }
    public UserPermission(
        SPUser user, 
        SPBasePermissions permissions)
        User = user;
        Permissions = permissions;
    public static IEnumerable<UserPermission>
        FromRoleAssignments(SPRoleAssignmentCollection roles)
        var allGranted // all assignments
            = from r in roles.Cast<SPRoleAssignment>()
            let asGroup = r.Member as SPGroup
            let users = asGroup != null
                ? asGroup.Users.Cast<SPUser>()
                : new[] { (SPUser)r.Member }
            from u in users
            select new UserPermission(
                        (acc, x) => acc |= x.BasePermissions)
        var byUser // aggregate per user
            = allGranted.GroupBy(
            x => x.User,
            x => x.Permissions,
            (u, p) => new UserPermission(
                    (acc, x) => acc |= x)
            new UserComparer());
        return byUser;
    sealed class UserComparer : IEqualityComparer<SPUser>
        public bool Equals(SPUser x, SPUser y)
        { return x.ID == y.ID; }
        public int GetHashCode(SPUser obj) 
        { return obj.ID.GetHashCode(); }
m@kli.dk @klinkby RSS feed  GitHub