Login user using Sitecore forms through Authentication Manager

 In this, we will check if the user exists and make him log in otherwise give an error. There is one Register button also that redirects to the Registration page.


The logic for login user is as:

using Foundation.Helper.Utility;
using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using Sitecore.Security.Accounts;
using Sitecore.Security.Authentication;
using System.Linq;
using System.Web;

namespace Feature.Forms.FormActions
{
    public class LoginUser : SubmitActionBase<string>
    {
        public LoginUser(ISubmitActionData submitActionData) : base(submitActionData)
        {
        }

        protected override bool TryParse(string value, out string target)
        {
            target = string.Empty;
            return true;
        }

        protected override bool Execute(string data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            var fields = GetFormFields(data, formSubmitContext);

            Assert.IsNotNull(fields, nameof(fields));

            if (UsernameOrPasswordFieldIsNull(fields))
            {
                return AbortForm(formSubmitContext);
            }

            var user = Login(fields.Username, fields.Password);

            if (user == null)
            {
                return AbortForm(formSubmitContext);
            }

            //Redirect to external URL
            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)}";

            formSubmitContext.RedirectUrl = userCountryUrl;
            formSubmitContext.RedirectOnSuccess = true;

            return true;
        }

        protected virtual User Login(string userName, string password)
        {
            var accountName = string.Empty;
            var domain = Context.Domain;
            if (domain != null)
            {
                accountName = domain.GetFullName(userName);
            }

            var result = AuthenticationManager.Login(accountName, password);
            if (!result)
            {
                return null;
            }

            var user = AuthenticationManager.GetActiveUser();
            return user;
        }

        private LoginUserFormFields GetFormFields(string data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            return new LoginUserFormFields
            {
                Username = Helper.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("Username"))),
                Password = Helper.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("Password")))
            };
        }

        private bool UsernameOrPasswordFieldIsNull(LoginUserFormFields field)
        {
            Assert.ArgumentNotNull(field, nameof(field));
            return field.Username == null || field.Password == null;
        }

        private bool UsernameOrPasswordValueIsNull(LoginUserFieldValues values)
        {
            Assert.ArgumentNotNull(values, nameof(values));
            return string.IsNullOrEmpty(values.Username) || string.IsNullOrEmpty(values.Password);
        }

        private bool AbortForm(FormSubmitContext formSubmitContext)
        {
            formSubmitContext.Abort();
            return false;
        }

        internal class LoginUserFormFields
        {
            public string Username { get; set; }
            public string Password { get; set; }

            public LoginUserFieldValues GetFieldValues()
            {
                return new LoginUserFieldValues
                {
                    Username = Helper.GetValue(Username),
                    Password = Helper.GetValue(Password)
                };
            }
        }

        internal class LoginUserFieldValues
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }
    }
}

using System.Collections.Generic;

namespace Foundation.Helper.Utility
{
    public class Helper
    {
        public static string GetValue(object field)
        {
            return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;
        }
        public static string GetDropdownValue(object field)
        {
            var value = field?.GetType().GetProperty("Value")?.GetValue(field, null);
            return ((List<string>)value)[0] ?? string.Empty;
        }
    }
}


1 comment:

  1. https://sitecorepeanuts.blogspot.com/2024/03/login-user-using-sitecore-forms-through.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” ...