Recently I’ve got into a situation where I have to identify programmatically whether given user is having read or write access on specific Sitecore item. I’ve thought of sharing my solution via blog post. It might come in handy for someone else. Below function CheckReadAccess(string itemId, string UserName) accepts User Name and Item Id of Sitecore item as input parameter and returns true or false after assessing access rights.
public bool CheckReadAccess(string itemId, string UserName) { bool ReadAccess = false; if (Sitecore.Data.ID.IsID(itemId)) { Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId)); if (item != null) { Sitecore.Security.Domains.Domain domain = Sitecore.Context.Domain; string domainUser = domain.Name + @"\" + UserName; if (Sitecore.Security.Accounts.User.Exists(domainUser)) { Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(domainUser, false); // UserSwitcher allows below code to run under a specific user using (new Sitecore.Security.Accounts.UserSwitcher(user)) { ReadAccess = item.Access.CanRead(); } } } } return ReadAccess; }Explanation: I’ve used the Sitecore.Security.Accounts.UserSwitcher class to cause a block of code to run in the context of a specific user, regardless of the context user. The Sitecore.Security.Accounts.UserSwitcher constructor sets the context user to the specified user. The code within the using statement block has the effective rights of the user specified by the first parameter passed to constructor of the the Sitecore.Security.Accounts.UserSwitcher class. Sitecore.Security.AccessControl.ItemAccess class is responsible to check various access rights on given item. In my code, I am checking read access rights on Sitecore item by calling item.Access.CanRead(). ItemAccess class is having below inbuilt functions:
namespace Sitecore.Security.AccessControl { public class ItemAccess { public ItemAccess(Item item); public virtual bool CanAdd(BranchId branchId); public virtual bool CanAdd(TemplateID templateID); public virtual bool CanAdmin(); public virtual bool CanCopyTo(Item destination); public virtual bool CanCreate(); public virtual bool CanDelete(); public virtual bool CanDuplicate(); public virtual bool CanMoveTo(Item destination); public virtual bool CanRead(); public virtual bool CanReadLanguage(); public virtual bool CanRemoveVersion(); public virtual bool CanRename(); public virtual bool CanWrite(); public virtual bool CanWriteLanguage(); } }Write a comment if you are aware of some other ways of checking access rights on Sitecore item programmatically. Comments and suggestions are most welcome. Happy coding!
Godd bless
ReplyDelete