Redirect to login page if user is not logged in using Sitecore forms Authenctication Manager

 The scenario is as follows which covers all the cases in the code:

  1. When the user visits the page, check if user is at the /login page then keep him on login page if he is not logged in.
  2. When the user visits the page, and the user is trying to access the page other than /login and user is not logged in,  then redirect him to /login page.
  3. When user tries to login with credential and user doesn't exist then show error. And user can click on the Register button to redirect to register page.
  4. When user enters the correct credentials then redirect him to its specific country page (https://domain/countries/<country>) that user would have selected in the dropdown at the time of registration.

using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Links;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.Security.Authentication;
using Sitecore.Security.Domains;
using Sitecore.Web;
using System.Web;

namespace Feature.Forms.Pipelines
{
    public class CheckUserSession : HttpRequestProcessor
    {
        public override void Process(HttpRequestArgs args)
        {
            var url = HttpContext.Current.Request.Url.AbsoluteUri.ToLower();
            //If Sitecore CMS URL then skip check
            if (url.Contains("sitecore") || Context.Site.IsBackend || Context.Site.Domain.Equals(Domain.GetDomain("sitecore")) || url.Contains("register"))
            {
                return;
            }
            //Here Home Page is login page.
            var loginPage = Context.Database.GetItem(Constant.LoginPage);
            var isLoginPage = loginPage.ID.Equals(Context.Item.ID);

            if (Context.Item != null)
            {
                //loginPage = no and authenicate = yes or //loginPage = yes and authenicate = no
                if ((!isLoginPage && Context.User.IsAuthenticated) || (isLoginPage && !Context.User.IsAuthenticated))
                    return;
                //loginPage = no and authenicate = no
                if (!isLoginPage && !Context.User.IsAuthenticated)
                    RedirectToLoginPage(loginPage);
                //loginPage = yes and authenicate = yes
                if (isLoginPage && Context.User.IsAuthenticated)
                    RedirectToItsCountryPage();
            }


        }
        #region Private Methods
        /// <summary>
        /// Check user session, if not valid redirect to configure page.
        /// </summary>
        private void RedirectToLoginPage(Item loginPage)
        {
            string redirectUrl = LinkManager.GetItemUrl(loginPage);
            RedirectUrl(redirectUrl);
        }
        /// <summary>
        /// If logged-in user trying to open url in browser different window/tab, user will redirect to landing/welcome page
        /// </summary>
        private void RedirectToItsCountryPage()
        {
            var user = AuthenticationManager.GetActiveUser();
            var countryBaseUrl = ((LinkField)(Context.Database.GetItem(Constant.CountryFolder)?.Fields[Constant.CountryPageField])).GetFriendlyUrl();
            var userCountryUrl = $"{HttpContext.Current.Request.Url?.Scheme}://{HttpContext.Current.Request.Url?.Host}{countryBaseUrl}/{user.Profile.GetCustomProperty(Constant.Country)}";
            RedirectUrl(userCountryUrl);
        }

        private void RedirectUrl(string url)
        {
            WebUtil.Redirect(url);
        }

        #endregion Private Methods
    }
}


I tried to test the code with the above mentioned points but still there may be some gaps (not major) please feel free to modify in your code repo. :-)

The Config file:

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <httpRequestBegin>
        <processor patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="Feature.Forms.Pipelines.CheckUserSession, Feature.Forms" />
      </httpRequestBegin>
    </pipelines>
  </sitecore>
</configuration>

1 comment:

  1. https://sitecorepeanuts.blogspot.com/2024/03/redirect-to-login-page-if-user-is-not.html

    ReplyDelete

Creating Solr core for sitecore using command prompt

We setup the solr cores using command “C:\solr8985\sc103solr-8.11.2\bin>solr.cmd create -c sitecore_sxa_web_index -d sitecore_configset” ...