Redirect Users SharePoint WebPart

This code snippet will allow you to redirect users to various sites based on their login.

[csharp]

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Microsoft.SharePoint.Portal.UserProfiles;

using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint;                         // Needed for Site Objects (SPSite)
using Microsoft.SharePoint.WebControls;               // Needed for SPControl
using System.Security.Principal;
using System.Runtime.InteropServices;

 

namespace ARB.PageRedirect
{
        //==============================================================================================
        /// <summary>
        /// Adam Buenz
        /// ARB Security Solutions
        /// </summary>
        //==============================================================================================
        //
        [DefaultProperty(“”), ToolboxData(“<{0}:PageRedirector runat=server></{0}:PageRedirector>”)]
        public class PageRedirector : System.Web.UI.WebControls.WebControl
        {
                //
                //——————————————————————————————
                /// <remarks>PortalOrSite Property: Portal or Site indicator (“P” or “S”)</remarks>
                ///
                private const string defaultPortalOrSite = “S”;
                private string portalOrSite = defaultPortalOrSite;
                [Bindable(true),
                Category(“Assembly Class Settings”),
                DefaultValue(defaultPortalOrSite),
                Description(“Portal or Site Setting (P or S)”)]
                public string PortalOrSite
                {
                        get
                        {
                                return portalOrSite;
                        }

                        set
                        {
                                portalOrSite = value;
                        }
                }
                //
                //——————————————————————————————
                /// <remarks>DefaultRedirUrl Property: Default Redirect Url (default if no user information
                /// is available </remarks>
                ///
                private const string defaultDefaultRedirUrl = “”;
                private string defaultRedirUrl = defaultDefaultRedirUrl;
                [Bindable(true),
                Category(“Assembly Class Settings”),
                DefaultValue(defaultDefaultRedirUrl),
                Description(“Default Url to redirect to if no user info available”)]
                public string DefaultRedirUrl
                {
                        get
                        {
                                return defaultRedirUrl;
                        }

                        set
                        {
                                defaultRedirUrl = value;
                        }
                }

                //
                //==========================================================================================
                /// <summary>
                /// CreateChildControls – Create the Child controls for this Control:
                /// </summary>
                //——————————————————————————————
                protected override void CreateChildControls()
                {

                }
                //
                //==========================================================================================
                /// <summary>
                /// Render – Render the HTML/controls:
                /// </summary>
                //——————————————————————————————
                protected override void Render(HtmlTextWriter output)
                {
                        // Make sure the control is ready:
                        //
                        EnsureChildControls();
                        //
                        SPSite TheCurSite = SPControl.GetContextSite(Context);
                        //SPWeb BaseWeb = TheCurSite.AllWebs[0];
                        SPWeb BaseWeb = TheCurSite.RootWeb;
                        string Department = “”;
                        // Get the current web:
                        SPWeb TheCurWeb = SPControl.GetContextWeb(Context);
                        // Get the current (Active) user:
                        bool FoundUser = false;

                        SPUser TheCurUserRef = TheCurWeb.CurrentUser;
                        SPUser TheCurUser = null;
                        try
                        {
                                TheCurUser = BaseWeb.Users[TheCurUserRef.LoginName];
                                FoundUser = true;
                        }
                        catch (Exception ErrHere)
                        {
                                TheCurUser = TheCurUserRef;
                                string SomeInfo = ErrHere.Message.ToString();
                                FoundUser = false;
                        }
                        //
                        if (FoundUser || !FoundUser)
                        {
                                // Get the Portal Context:
                                //
                                bool KeepGettingUPM = false;
                                SPSite PortSite = null;
                                PortalContext pc = null;

                                try
                                {
                                        PortSite = new SPSite(TheCurSite.MakeFullUrl(TheCurSite.PortalUrl));
                                        pc = PortalApplication.GetContext(PortSite.ID);
                                        KeepGettingUPM = true;
                                }
                                catch (Exception Msg1)
                                {
                                        string Msg1text = Msg1.Message.ToString();
                                        KeepGettingUPM = false;
                                        this.Page.Response.Write(“Portal Site or context error: ” + Msg1text);
                                }
                                //
                                // Get the User Profile Manager:
                                //
                                UserProfileManager upm = null;
                                if (KeepGettingUPM)
                                {
                                        try
                                        {
                                                upm = new UserProfileManager(pc);
                                        }
                                        catch          { KeepGettingUPM = false; }
                                }
                                //
                                // Get the User’s Profile:
                                //
                                try
                                {
                                        UserProfile CurUserProfile = upm.GetUserProfile(TheCurUser.LoginName);
                                        Department = (string)CurUserProfile[“Department”];
                                }
                                catch (Exception UPGetErr)
                                {
                                        //
                                        // No user profile – this is a problem for normal users so we will redirect:
                                        //
                                        string TheMsg = UPGetErr.Message.ToString();
                                        Department = “UNKNOWN”;
                                        this.Page.Response.Write(“USER PROFILE INFORMATION WAS NOT FOUND = ” + TheMsg);
                                }
                                string UrlToAdd = “”;
                                if (PortalOrSite == “P”)
                                {
                                        UrlToAdd = “/sites/”;
                                }
                                else
                                {
                                        UrlToAdd = “/sites/”;
                                        //                         UrlToAdd = “/”;
                                }

                                if (Department == “blahdept1”)
                                {
                                        this.Page.Response.Redirect(UrlToAdd + “blahdept1/default.aspx”);
                                }
                                if (Department == “blahdept2”)
                                {
                                        this.Page.Response.Redirect(UrlToAdd + “blahdept2/default.aspx”);
                                }
                                if (Department == “blahdept3”)
                                {
                                        this.Page.Response.Redirect(UrlToAdd + “blahdept3/default.aspx”);
                                }
                                if (Department == “blahdept4”)
                                {
                                        this.Page.Response.Redirect(UrlToAdd + “blahdept4/default.aspx”);
                                }
                                if (Department == “blahdept5”)
                                {
                                        this.Page.Response.Redirect(UrlToAdd + “blahdept5/default.aspx”);
                                }
                        }
                        //
                        // Unknown Department or not one we are interested in – redirect to the default:
                        //
                        // If portal, do nothing…
                        //
                        if (PortalOrSite == “P”)
                        {
                                // Do nothing….
                                return;
                        }
                        //
                        // Site – redirect to the default url:
                        //
                        if (PortalOrSite == “S”)
                        {
                                // Do nothing….
                                this.Page.Response.Redirect(DefaultRedirUrl);
                                return;
                        }
                        //
                        // End of Render
                }
                ///===========================================================================================
                /// <summary>
                /// CreateIdentity
                /// </summary>
                /// <param name=”User”></param>
                /// <param name=”Domain”></param>
                /// <param name=”Password”></param>
                /// <returns></returns>
                protected static WindowsIdentity CreateIdentity(string User, string Domain, string Password)
                {
                        // The Windows NT user token.
                        IntPtr tokenHandle = new IntPtr(0);

                        const int LOGON32_PROVIDER_DEFAULT = 0;
                        const int LOGON32_LOGON_NETWORK = 3;

                        tokenHandle = IntPtr.Zero;

                        // Call LogonUser to obtain a handle to an access token.
                        bool returnValue = LogonUser(User, Domain, Password,
                        LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
                        ref tokenHandle);

                        if (false == returnValue)
                        {
                                int ret = Marshal.GetLastWin32Error();
                                throw new Exception(“LogonUser failed with error code: ” +  ret);
                        }

                        System.Diagnostics.Debug.WriteLine(“Created user token: ” + tokenHandle);

                        //The WindowsIdentity class makes a new copy of the token.
                        //It also handles calling CloseHandle for the copy.
                        WindowsIdentity id = new WindowsIdentity(tokenHandle);
                        CloseHandle(tokenHandle);
                        return id;
                }

                [DllImport(“advapi32.dll”, SetLastError=true)]
                private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
                int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

                [DllImport(“kernel32.dll”, CharSet=CharSet.Auto)]
                private extern static bool CloseHandle(IntPtr handle);
        }
}

[/csharp]

Share

Leave a Reply

Your email address will not be published. Required fields are marked *