Sunday, May 23, 2010

nopCommerce - Allow only logged in users to view catalog programmatically

I'm currently working on a nopCommerce installation where the requirement is to give two sites that run on the same database. The first site is a public facing site which operates as a normal e-commerce site. The second site, is a private registered users only site, that is slightly modified from the public site. This will require some customizations which will be covered later, but first, we'll basically run these 2 sites on separate sub-domains so that we can reference the same database, but have 2 sites that operate differently.

Now, the private site needs to be viewable by registered/logged in users only. This can be accomplished in the admin area by simply navigating to: Configuration -> Global Settings -> Other -> Allow navigation only for registered customers. Check this box and users will not be allowed to surf the site without first registering and/or logging in. However, this is a database setting, and would apply to all sites targeting this database. This will not work for my needs.

Luckily, there is a very simple solution. On my private site, we'll add 2 lines of code to the Root.Master.cs page in the OnLoad event:


protected override void OnLoad(EventArgs e)

        {

            //Check to see if the customer is logged in, if not redirect to the login/register page

            if (NopContext.Current.User == null)

                Response.Redirect("~/login.aspx");

            base.OnLoad(e);

        }



And Viola! The masterpage will now check if the NopContext.Current.User object is null, and it will be if you're not logged in, and if so then redirect to a login page. We'll apply a new nested masterpage here to remove any navigation elements other than login and register.

No comments:

Post a Comment