views:

1504

answers:

1

I have built custom Membership and Role providers. Users are some clients that belong to the company and I am using Company as a Role.

I would like to create SharePoint Group and add more companies to it (for example type of industry) and then do redirecting and security by the SPGroup.

How do I retrieve SPGroup for the current logged in user ?
I would like to this in my custom Login page so another problem is how do I retrieve SPUser or SPGroup knowing login name ?

This is what I have now:


private List GetGroupsForUser(List roleAccounts)
{
    List groups = new List();
    SPSecurity.RunWithElevatedPrivileges(
     delegate()
     {
         using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
         {
             SPUserCollection users = site.RootWeb.SiteUsers;
             foreach (string account in roleAccounts)
             {
                 SPGroupCollection accGroups = users[account].Groups;
                 foreach (SPGroup spg in groups)
                 {
                     groups.Add(spg);
                 }
             }
         }
     }
     );

    return groups;

}

private string GetRoleManagerName()
{
    foreach (KeyValuePair setting in SPContext.Current.Site.WebApplication.IisSettings)
    {
        if (string.IsNullOrEmpty(setting.Value.RoleManager) == false)
            return setting.Value.RoleManager.ToLower();
    }
    return null;
}

private List GetSpAccounts()
{
    List roleAccounts = new List();
    string roleProviderName = GetRoleManagerName();
    foreach (string role in Roles.GetRolesForUser(login.UserName))
    {
        roleAccounts.Add(roleProviderName + ":" + role.ToLower());
    }

    return roleAccounts;
}


// and now I can use it
List roleAccounts = GetSpAccounts();
List groups = GetGroupsForUser(roleAccounts);

But I have a felling that I should not have to do this manually like this. How will Target Audience work if only role is added to the group ?

+1  A: 
Robert MacLean
Thanks for answering but SPContext.Current.Web.CurrentUser.Roles thows exeption. One more not I am doing all this on the login page in the OnLoggedIn event.
Robert Vuković