Friday, July 30, 2010

Sharepoint 2010 - Create an Audience based ACL

I have been asked to manage the security of an application according to the user profile organization's property.... Well obviously, sharepoint is not designed like that. So, how to ?

My solution is the following :
  • Fill the organization property on each of the profile
  • Create one audience per organization based on this property
  • Synchronize the audiences with Sharepoint groups using a timer job (that's the main part of the article)
I won't explain the two first points, I guess you already know how to create and compile audiences, else go back to the root first !

The principle of my timer job is simple. It is activated using a feature that is scoped webapplication. The execute method parses all the sites of the applications, and the audiences of the platform. It thus verify that a group with the same name exists on the site. If not, it creates the groups, If it does exist, it just adds the users in the group.
So at the end I have on all my sites, the same groups with the same users and everything is based on the audiences that are based on the user profile properties ... Quod Erat Demonstratum.

Below the execute Method of the Timer job:

try
{
SPWebApplication webApplication = this.Parent as SPWebApplication;
AudienceManager audManager = new AudienceManager(SPServiceContext.GetContext(webApplication.Sites[0]));
foreach (SPSite site in webApplication.Sites)
{
foreach (Audience au in audManager.Audiences)
{
try
{
if (site.RootWeb.SiteGroups[au.AudienceName] == null)
{
}
}
catch (Exception exx)
{
SPUser oUser = site.RootWeb.Users.GetByEmail("alexandre.joly@toto.com");
SPMember oMember = site.RootWeb.Users.GetByEmail("alexandre.joly@toto.com");
site.RootWeb.SiteGroups.Add(au.AudienceName, oMember, oUser, "Group synchronized on existing audience");

}
SPGroup group = site.RootWeb.SiteGroups[au.AudienceName];
ArrayList members = au.GetMembership();
if (members != null)
{
foreach (UserInfo userInfo in members)
{
group.Users.Add(userInfo.NTName, userInfo.Email, userInfo.PreferredName, "");
}
}
}
}

}
catch (Exception exc)
{

}