Tuesday 9 November 2010

Programmatically Add/Edit Users

I always find it frustrating when looking at code samples that the references are not included :-). I have included the whole class on how to create, edit and delete users.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;

using Sitecore.Configuration;
using Sitecore.Security.Accounts;

namespace Client.Project.Security
{
    /// <summary>
    /// This class will be responsible for:
    /// 1. Adding new users
    /// 2. Editing existing users
    /// 3. Deleting users
    /// 4. Assigning roles
    /// </summary>
    public class UserMaintenance
    {
        /// <summary>
        /// Creates a new user and edits the profile custom fields
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <param name="telephoneNumber"></param>
        /// <param name="jobTitle"></param>
        public void AddUser(string domain, string firstName, string lastName, string email, 
            string comment, string telephoneNumber, string jobTitle)
        {
            string userName = string.Concat(firstName, lastName);
            userName = string.Format(@"{0}\{1}", domain, userName);
            string newPassword = Membership.GeneratePassword(10, 3);
            try
            {
                if (!User.Exists(userName))
                {
                    Membership.CreateUser(userName, newPassword, email);

                    // Edit the profile information
                    Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
                    Sitecore.Security.UserProfile userProfile = user.Profile;
                    userProfile.FullName = string.Format("{0} {1}", firstName, lastName);
                    userProfile.Comment = comment;

                    // Assigning the user profile template
                    userProfile.SetPropertyValue("ProfileItemId", "{AE4C4969-5B7E-4B4E-9042-B2D8701CE214}");

                    // Have modified the user template to also contain telephone number and job title.
                    userProfile.SetCustomProperty("TelephoneNumber", telephoneNumber);
                    userProfile.SetCustomProperty("JobTitle", jobTitle);
                    userProfile.Save();
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(string.Format("Error in Client.Project.Security.UserMaintenance (AddUser): Message: {0}; Source:{1}", ex.Message, ex.Source), this);
            }
        }

        /// <summary>
        /// Edits the user profile and custom fields
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="email"></param>
        /// <param name="comment"></param>
        /// <param name="telephoneNumber"></param>
        /// <param name="jobTitle"></param>
        public void EditUser(string domain, string firstName, string lastName, string email,
            string comment, string telephoneNumber, string jobTitle)
        {
            string userName = string.Concat(firstName, lastName);
            userName = string.Format(@"{0}\{1}", domain, userName);
            try
            {
                Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
                Sitecore.Security.UserProfile userProfile = user.Profile;
                if (!string.IsNullOrEmpty(email))
                {
                    userProfile.Email = email;
                }
                if (!string.IsNullOrEmpty(comment))
                {
                    userProfile.Comment = comment;
                }

                // Have modified the user template to also contain telephone number and job title.
                if (!string.IsNullOrEmpty(telephoneNumber))
                {
                    userProfile.SetCustomProperty("TelephoneNumber", telephoneNumber);
                }
                if (!string.IsNullOrEmpty(jobTitle))
                {
                    userProfile.SetCustomProperty("JobTitle", jobTitle);
                }
                userProfile.Save();
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(string.Format("Error in Client.Project.Security.UserMaintenance (EditUser): Message: {0}; Source:{1}", ex.Message, ex.Source), this);
            }
        }

        /// <summary>
        /// Deletes a user for a particular domain
        /// </summary>
        /// <param name="userName"></param>
        public void DeleteUser(string userName)
        {
            try
            {
                Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(userName, true);
                user.Delete();
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(string.Format("Error in Client.Project.Security.UserMaintenance (DeleteUser): Message: {0}; Source:{1}", ex.Message, ex.Source), this);
            }            
        }

        /// <summary>
        /// Assigns a user to either the User or Superuser role of that particular domain
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="isSuperUser"></param>
        public void AssignUserToRole(string domain, string firstName, string lastName, bool isSuperUser)
        {
            try
            {
                ConfigStore userRolesConfig = Sitecore.Configuration.ConfigStore.Load("config");
                List<ConfigRecord> userRoles = userRolesConfig.RootRecord.GetChildRecords();

                string userName = string.Concat(firstName, lastName);
                userName = string.Format(@"{0}\{1}", domain, userName);
                string domainRole = string.Empty;
                if (isSuperUser)
                {
                    domainRole = string.Format("{0}\\{1}",
                        domain,
                        userRoles.SingleOrDefault(role => role.Attributes["IsSuperUser"] == "1").Attributes["name"]);
                }
                else
                {
                    domainRole = string.Format("{0}\\{1}",
                        domain,
                        userRoles.SingleOrDefault(role => role.Attributes["IsSuperUser"] == "0" && role.Attributes["Access"] == "Allow").Attributes["name"]);
                }
                UserRoles.FromUser(User.FromName(userName, true)).Add(Role.FromName(domainRole));
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(string.Format("Error in Client.Project.Security.UserMaintenance (AssignUserToRole): Message: {0}; Source:{1}", ex.Message, ex.Source), this);
            }
        }
    }
}

No comments:

Post a Comment