Notify sitecore user on account enable

Often when a new user is created (especially if created from the sitecore site – as an extranet user), we might find the need to have an approval process in place to ensure access to credible users only.

You can see more details on creating extranet users for your site at Creating an extended Sitecore user for your site

When the user is being created, you can automatically disable the user initially by adding this before user save:

user.IsApproved = false;

This would disable the user id:
2014-06-15_030924

Now when a user admin of your site, goes and enables the user after review, you might want to intimate the user that their account has been enabled and they now have the privileges that it comes with!

The enable user command which is executed when a user is enabled resides in the App_Config\Commands.config file:

  <command name="usermanager:enable" type="Sitecore.Shell.Framework.Commands.UserManager.Enable,Sitecore.Kernel"/>

You can override this command and add your own functionality to the existing needed functionality for enable which you can bring over from the reflected code of Sitecore.Kernel.dll.

Here’s a sample of getting this done:
Config:

  <command name="usermanager:enable" type="Sitecore72.Classes.EnableUserNotify, Sitecore72"/>

Code (This is reflected code from sitecore.kernel.dll with an additional method call for the notification. You could sure choose to write the code yourself for enable – after all you only need to toggle a user property at the end of the day, but this code will also handle the confirm messages and all error handling for you)

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.Web.Security;
using Sitecore.ApplicationCenter.Applications;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Shell.Framework.Commands.UserManager;
using Sitecore.Text;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.WebControls;
using Sitecore.Web.UI.XamlSharp.Continuations;

namespace Sitecore72.Classes
{
    [Serializable]
    public class EnableUserNotify : Command, ISupportsContinuation
    {
        /// <summary>
        /// Executes the command in the specified context.
        /// 
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Execute(CommandContext context)
        {
            Assert.ArgumentNotNull((object)context, "context");
            var userName = context.Parameters["username"];
            if (!ValidationHelper.ValidateUserWithMessage(userName))
                return;
            var parameters = new NameValueCollection();
            parameters["username"] = userName;
            ContinuationManager.Current.Start((ISupportsContinuation)this, "Run", new ClientPipelineArgs(parameters));
        }

        /// <summary>
        /// Runs the pipeline.
        /// 
        /// </summary>
        /// <param name="args">The args.</param>
        protected void Run(ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull((object)args, "args");
            ListString listString = new ListString(args.Parameters["username"]);
            if (args.IsPostBack)
            {
                if (!(args.Result == "yes"))
                    return;
                List<string> list = new List<string>();
                string key = string.Empty;
                foreach (string username in listString)
                {
                    MembershipUser user = Membership.GetUser(username);
                    Assert.IsNotNull((object)user, typeof(MembershipUser));
                    try
                    {
                        user.IsApproved = true;
                        Membership.UpdateUser(user);

                        NotifyUser(user);

                        Log.Audit((object)this, "Enable user: {0}", new string[1]
                        {
                          username
                        });
                    }
                    catch (NotImplementedException ex)
                    {
                        key = "Sorry, this feature is not supported by the underlying provider implementation. Please contact the system administration for more details";
                    }
                    catch (NotSupportedException ex)
                    {
                        key = "Sorry, this feature is not supported by the underlying provider implementation. Please contact the system administration for more details";
                    }
                    catch (Exception ex)
                    {
                        list.Add(username);
                        key = ex.Message;
                        Log.Error("User can not be enabled", ex, (object)this);
                    }
                }
                if (list.Count > 0)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (string str in list)
                    {
                        stringBuilder.Append('\n');
                        stringBuilder.Append(str);
                    }
                    SheerResponse.Alert(Translate.Text("The following users could not be enabled:\n{0}\nException:\n{1}", (object)((object)stringBuilder).ToString(), (object)Translate.Text(key)), new string[0]);
                }
                AjaxScriptManager.Current.Dispatch("usermanager:refresh");
            }
            else
            {
                if (listString.Count == 1)
                    SheerResponse.Confirm(Translate.Text("Are you sure you want to enable {0}?", new object[1]
          {
            (object) listString[0]
          }));
                else
                    SheerResponse.Confirm(Translate.Text("Are you sure you want to enable these {0} users?", new object[1]
          {
            (object) listString.Count
          }));
                args.WaitForPostBack();
            }
        }

        private void NotifyUser(User user)
        {
            var emailMessage = new MailMessage
            {
                From = new MailAddress(ConfigurationSettings.AppSettings["CompanyFromAddress"]),
                Subject = "You are a privileged member!",
                Body = user.FullName + ", you are now a privileged member of our club!"
            };

            emailMessage.To.Add(user.Email);

            using (var client = new SmtpClient())
            {
                client.Send(emailMessage);
            }
        }
    }
}

The corresponding smtp settings can be as usual found in the config:

  <system.net>
    <mailSettings>
      <smtp>
        <network host="yoursmtphost.com" port="25" userName="" password="" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>
Advertisements

, , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: