.Net & SharePoint '07

Technical blog for .Net and all SharePoint 2007 related Information

About the author

Me(Prince) and my wife are B.E in I.T & C.S.E respectively.  I a certified MCPD: Web from 2007 Dec. I am Intrestes in Web Application, MOSS, EPM, etc.
Now working with Deira International School, as IT Application & Help Manager. I have started my career as "Software Developer" @  REACH Sewn Technologies and Consulting Pvt. Ltd, Bangalore India from Oct 2004 to Feb 2006, then as "Web & Intranet Developer" @ Fosroc International Ltd, Dubai from April 2006 to Sep 2009.
You can catch me on mail@jpy-tech.com or mail@princepy.com. Or on 00971 - 50 - 4284530 

Google Translate

Tag cloud

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

RecentComments

Comment RSS

Google Your Location


Checking to see if a user is in a role

Code to check to see if a user was a member of a role and it was working properly until that user was placed in a group that had that role instead of the using having the role. 

The problem was caused by the GetAssignmentByPrincipal method only returning the assignments to the actual user and not any of the groups that the user was in. 

The property AllRolesForCurrentUser in the web returns roles that are assigned to a group that the user is part of as well, but this will only work if you are logged in as that user.  To get around this I made a quick method that takes in a SPUser and a role name for a role that is on the root web:

public bool DoesUserHaveRole(SPUser user, string strRole)
{
    bool retValue = false;
    if (user != null)
    {
        // Open the site as the current user
        using (SPSite site = new SPSite(SPContext.Current.Site.Url, user.UserToken))
        {
            // Get the root web
            using (SPWeb rootWeb = site.RootWeb)
            {
                SPRoleDefinition role = null;
                // Try to get the role by it's name,
                // since we can't simply check against null
                try
                {
                    role = rootWeb.RoleDefinitions[strRole];
                }
                catch { }
 
                if (role != null)
                {
                    // Check to see if the user has that role
                    retValue = rootWeb.AllRolesForCurrentUser.Contains(role);
                }
            }
        }
    }
    return retValue;
}

Source : http://www.thesug.org/blogs/MOSSMania/Lists/Posts/Post.aspx?List=3f7d7b8a%2Da822%2D409c%2D97ed%2Dd4367160f6d7&ID=34


Categories: MOSS | WSS
Posted by admin on Tuesday, September 16, 2008 11:15 AM
Permalink | Comments (0) | Post RSSRSS comment feed