Friday, October 5, 2012

HttpModule and Sharepoint Security

Hello guys,
 
Today I have got a task to block specific users accessing _layouts/settings.aspx page, hence I created an HttpModule as this would be the best implementation to let me examine incoming and outgoing requests and take action based on the request. HTTP Modules Overview
 
1. Create a class library
2. Implement the Interface IHttpModule
3. Implement the required methods (see ApplicationHttpModule.cs)
4. Strong name it and build
5. Copy the DLL into the GAC.
 
Now in the web.config of each sharepoint webapp - add the below entry under  
<modules runAllManagedModulesForAllRequests="true"> and <httpModules>
 
<add name="CustomApplicationHttpModule" type="ApplicationHttpModule.ApplicationMasterModule 
ApplicationHttpModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d9c0030627b434f" />
 
Do an IISReset and test it.
 
Enjoy. 
 
[Code]
namespace ApplicationHttpModule
{
    public class ApplicationMasterModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            try
            {
                context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
            }
            catch (Exception ex)
            {
            }
           
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            try
            {
                Page page = HttpContext.Current.CurrentHandler as Page;
                if (page != null)
                {
                    page.PreInit += new EventHandler(page_PreInit);
                }
            }
            catch (Exception ex)
            {
            }
        }

        void page_PreInit(object sender, EventArgs e)
        {
            try
            {
                Page page = sender as Page;

                if (page != null)
                {
                    if (page.Request.Url != null)
                    {
                        //Get current logged in user and check if he is authhorized
                        string currentUser = page.User.Identity.Name;
                        bool result = IsAuthorized(currentUser);

                        if (result == false)
                        {
                            #region If user access unauthorized layouts pages
                            if (page.Request.RawUrl.Contains("_layouts/settings.aspx") ||
                                page.Request.RawUrl.Contains("_layouts/viewlsts.aspx") ||
                                page.Request.RawUrl.Contains("_layouts/user.aspx")     ||
                                page.Request.RawUrl.Contains("AllItems.aspx")
                                )
                            {
                                page.Response.Redirect("~/_layouts/accessdenied.aspx");
                            }
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        bool IsAuthorized(string currentUser)
        {
            //List of authorized users
            List<string> AuthorizedList = new List<string>();
            AuthorizedList.Add("admin1");
            AuthorizedList.Add("contributor1");
            AuthorizedList.Add("designer1");
            AuthorizedList.Add("reader1");

            string[] splitted = currentUser.ToLower().Split('\\');
            if (splitted.Length == 2)
            {
                currentUser = splitted[1];
            }

            //Check if the current logged in user is authorized
            foreach (string strUser in AuthorizedList)
            {
                if (strUser == currentUser)
                {
                    return true;
                }
            }
            return false;
        }
    }
}

[Code]

Thursday, October 4, 2012

Model view presenter with Sharepoint and Mvc

Hello guys,

As we have got a big projects in Sharepoint therefore it's time to apply Patterns for performance, scalability, reusability and maintenance so started Goggling to find out which are the recommended patterns for Sharepoint .

As we already know MVC pattern would be suitable in ASP.Net scenario however Sharepoint doesn't support MVC ["Currently MVC doesn't directly integrate with SharePoint. That is something we'll be looking at supporting in the future though." Source: http://sharepointmvc.codeplex.com/wikipage?title=SharePointNativeMVC&referringTitle=Home]

Therefore they have introduced Model–view–presenter (MVP) which is a derivative of the model–view–controller (MVC) software pattern, also used mostly for building user interfaces – In MVP the presenter assumes the functionality of the "middle-man" (played by the controller in MVC). In MVP, all presentation logic is pushed to the presenter. Eventually, the model becomes strictly a domain model also engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic.

Roles definition:
• The model is an interface defining the data to be displayed or otherwise acted upon in the
user interface.
ð  The model is an interface defining the data to be displayed.

• The view is an interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
ð  View contains the Presenter instance (view "knows" presenter).
ð  View doesn't know nothing about the Model.
ð  View responsibility is to show the data provided by presenter.
ð  View class manages the controls on the page and it forwards user events to a presenter class.

• The presenter acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.
ð  Presenter is the only class knowing how to reach to model and retrieve the data needed for performing business logic.
ð  Presenter talks to the View through the view interface (abstracted representation of the View without UI specific attributes).
ð  Presenter purpose is to reach to model, retrieve the needed data, performs required processing and returns the UI prepared data to the view.
ð  Presenter contains the logic to respond to the events, update the model (business logic and data of the application) and, in turn, manipulate the state of the view.



Sharepoint and MVP


ASP.Net and MVP - Must read







Sharepoint and Architecture




Sharepoint and Service Locator



ASP.NET and Architecture


Download


Now as we have an idea how it works…lets implement it…I m sharing these sample codes as I didn't get much help from the net…hope it helps.

Project Sample Mvp4 (download the project for more details)
In the Mvp4UserControl class – The Presenter constructor is taking only one parameter and passing the current view.
Project Sample Mvp3 (download the project for more details)
In the Presenter class – The Presenter constructor is taking  2 parameters however It is not necessary in this case as I have used IServiceLocator to get the instance of the Product class (see Sharepoint and Service Locator in Source)




Project Sample Mvp5 (download the project for more details)
In the Mvp5UserControl class – The Presenter constructor is taking 2 parameters.
In this I have made a use of class Product – Created a new instance – Set the properties and then passing the object in the constructor.
Note that I have not use IServiceLocator

Project Sample Mvp6 (download the project for more details)
A Different implementation of Presenter
Note that I m taking 1 parameter and below using  IServiceLocator to get an instance of Product Class