Auto Portal Login: Log in users from another portal  (C#)

DotNetNuke allows you to create child portals which operate as separate websites. In some cases one might find it desirable to allow a user of a portal to log into another portal by simply clicking a link. If the user does not have an account in the destination portal, their account will be copied from the sending portal.

The following module (requires DotNetNuke 4.8 or higher) will do that:

AutoPortalLogin_01.00.00_Install.zip

Using The Module

To use the module, create a second portal and in that second portal, add the Auto Portal Login module. In the settings for the module, set the Mode to Send and enter a portal name and a destination url.

Place another instance of the module in the destination portal, on the page specified by the Portal url.

In the Settings for the module, ensure that the module is in Receive mode.

The Code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
using DotNetNuke;
using DotNetNuke.Security;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Common;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Membership;
using System.Text;
using System.Data.SqlClient;
using DotNetNuke.Data;
using DotNetNuke.Security.Roles;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Authentication;
using DotNetNuke.Entities.Portals;
 
namespace AutoPortalLogin
{
    public partial class View : PortalModuleBase
    {
        #region strLoginMode
        private string strLoginMode
        {
            get
            {
                string strLoginMode = "Receive";
                if (Settings.Contains("LoginMode"))
                {
                    strLoginMode = (string)Settings["LoginMode"];
                }
                return strLoginMode;
            }
        }
        #endregion
 
        #region strPortalName
        private string strPortalName
        {
            get
            {
                string strPortalName = "Master Portal";
                if (Settings.Contains("PortalName"))
                {
                    strPortalName = (string)Settings["PortalName"];
                }
                return strPortalName;
            }
        }
        #endregion
 
        #region strPortalURL
        private string strPortalURL
        {
            get
            {
                string strPortalURL = "http://localhost";
                if (Settings.Contains("PortalURL"))
                {
                    strPortalURL = (string)Settings["PortalURL"];
                }
                return strPortalURL;
            }
        }
        #endregion
 
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    // Set Send or Receive mode
                    mvAutoPortalLogin.SetActiveView((strLoginMode == "Receive") ? vwReceiveMode : vwSendMode);
 
                    // If in Send mode only display if user is logged in
                    if ((this.UserInfo.UserID != -1) & (strLoginMode == "Send"))
                    {
                        mvAutoPortalLogin.Visible = true;
                        lnkMasterPortal.Text = strPortalName;
                    }
                    else
                    {
                        mvAutoPortalLogin.Visible = false;
                    }
 
                    // In Receive mode
                    if (strLoginMode == "Receive")
                    {
                        ReceiveMode();
                    }
                }
            }
 
            catch (Exception exc)
            {
                // Module failed to load
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 
        #region ReceiveMode
        private void ReceiveMode()
        {
            string strportaluser = "";
            int intportalkey = 0;
 
            // Get the PortalKey (Token)
            if (Request.QueryString["portalkey"] != null)
            {
                try
                {
                    intportalkey = Convert.ToInt32(Request.QueryString["portalkey"]);
                }
                catch (Exception ex)
                {
                    intportalkey = 0;
                }
            }
 
            // Get the User
            if (Request.QueryString["portaluser"] != null)
            {
                strportaluser = Request.QueryString["portaluser"];
 
                if (strportaluser != "")
                {
                    // Check the User and get the Sending PortalID
                    int intPortalID = CheckUser(strportaluser, intportalkey);
                    if (intPortalID != 0)
                    {
                        // The user has been found and the Token is valid 
 
                        // Is the user already in the current portal?
                        UserInfo UserInfo = UserController.GetUserByName(PortalId, strportaluser);
                        if (UserInfo == null)
                        {
                            // User is not in the current portal - Add them
                            UserInfo = UserController.GetUserByName(intPortalID, strportaluser);
                            AddUserToCurrentPortal(UserInfo.UserID);
                            // Update the roles for the user
                            UpdateUserRoles(UserInfo, intPortalID);
                        }
 
                        // Login the User
                        UserController.UserLogin(PortalId, UserInfo, PortalSettings.PortalName, GetIPAddress(), true);
                        // Reset the user token so it can't be used again
                        SetUserToken(strportaluser);
                        // Redirect the user to the current page
                        Response.Redirect(Request.RawUrl);
                    }
                    else
                    {
                        // For whatever reason it was a bad Token. 
                        // Reset the Token in case a hacker is trying to guess the number
                        // The hacker is now chasing a moving target
                        SetUserToken(strportaluser);
                    }
                }
            }
        }
        #endregion
 
        #region GetIPAddress
        private string GetIPAddress()
        {
            string sIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (sIPAddress == "")
            {
                sIPAddress = Request.ServerVariables["REMOTE_ADDR"];
            }
            return sIPAddress;
        }
        #endregion
 
        #region lnkMasterPortal_Click
        protected void lnkMasterPortal_Click(object sender, EventArgs e)
        {
            int intRandomNumber = SetUserToken(UserInfo.Username);
            Response.Redirect(string.Format("{0}?portaluser={1}&portalkey={2}", strPortalURL, UserInfo.Username, 
		intRandomNumber.ToString()));
        }
        #endregion
 
        #region SetUserToken
        private int SetUserToken(string portaluser)
        {
            // Get a random password
            int intRandomNumber = 0;
            Random RandomClass = new Random();
            intRandomNumber = RandomClass.Next();
 
            try
            {
                StringBuilder mySqlString = new StringBuilder();
 
                // Delete user if they exist
                mySqlString.Append("DELETE From {databaseOwner}{objectQualifier}AutoPortalLogin ");
                mySqlString.Append("WHERE Username = @Username ");
 
                SqlParameter prmUsername = new SqlParameter("@Username", SqlDbType.NVarChar, 100);
 
                prmUsername.Value = portaluser;
                DataProvider.Instance().ExecuteSQL(mySqlString.ToString(), prmUsername);
 
                // Add User
                mySqlString.Append("INSERT INTO {databaseOwner}{objectQualifier}AutoPortalLogin ");
                mySqlString.Append("(Username, PortalID, Token) ");
                mySqlString.Append("VALUES (@Username, @PortalID, @Token) ");
 
                SqlParameter prmPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
                SqlParameter prmToken = new SqlParameter("@Token", SqlDbType.Int, 4);
 
                prmPortalID.Value = PortalId ;
                prmToken.Value = intRandomNumber;
                DataProvider.Instance().ExecuteSQL(mySqlString.ToString(), prmUsername, prmPortalID, prmToken);
            }
 
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
            }
 
            return intRandomNumber;
        }
        #endregion
 
        #region CheckUser
        private int CheckUser(string portaluser, int token)
        {
            int intPortalID = 0;
            try
            {
                StringBuilder mySqlString = new StringBuilder();
                mySqlString.Append("SELECT PortalID ");
                mySqlString.Append("From {databaseOwner}{objectQualifier}AutoPortalLogin ");
                mySqlString.Append("WHERE Username = @Username ");
                mySqlString.Append("AND Token = @Token ");
 
                SqlParameter prmUsername = new SqlParameter("@Username", SqlDbType.NVarChar, 100);
                SqlParameter prmToken = new SqlParameter("@Token", SqlDbType.Int, 4);
 
                prmUsername.Value = portaluser;
                prmToken.Value = token;
 
                using (IDataReader dr = (IDataReader)DataProvider.Instance().ExecuteSQL(mySqlString.ToString(), 
			prmUsername, prmToken))
                {
                    while (dr.Read())
                    {
                        intPortalID = Convert.ToInt32(dr["PortalID"]);
                    }
                }
 
            }
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
            }
 
            return intPortalID;
        }
        #endregion
 
        #region AddUserToCurrentPortal
        private void AddUserToCurrentPortal(int UserID)
        {
            try
            {
                // update the UserPortals table to add the user to the current portal 
                StringBuilder mySqlString = new StringBuilder();
                mySqlString.Append("INSERT INTO {databaseOwner}{objectQualifier}UserPortals ");
                mySqlString.Append("(UserId, PortalId) ");
                mySqlString.Append("VALUES (@UserId, @PortalId) ");
 
                SqlParameter prmUserId = new SqlParameter("@UserId", SqlDbType.Int, 4);
                SqlParameter prmPortalId = new SqlParameter("@PortalId", SqlDbType.Int, 4);
 
                prmUserId.Value = UserID;
                prmPortalId.Value = PortalId;
                DataProvider.Instance().ExecuteSQL(mySqlString.ToString(), prmUserId, prmPortalId);
            }
 
            catch (Exception exc)
            {
                Exceptions.LogException(exc);
            }
        }
        #endregion
 
        #region UpdateUserRoles
        private void UpdateUserRoles(UserInfo objUserInfo, int SendingPortalID)
        {
            UserInfo SendingPortalUserInfo = UserController.GetUserByName(SendingPortalID, objUserInfo.Username);
            RoleController RoleController = new RoleController();
            RoleInfo RoleInfo;
 
            // Add the user to the roles that they are in in the Sending portal           
            foreach (string strRole in SendingPortalUserInfo.Roles)
            {
                RoleInfo = RoleController.GetRoleByName(PortalId, strRole);
                if (!(RoleInfo == null))
                {
                    RoleController.AddUserRole(PortalId, objUserInfo.UserID, RoleInfo.RoleID, DateTime.MaxValue);
                }
            }
 
        }
        #endregion
    }
}

[Back to: The ADefWebserver DotNetNuke HELP WebSite]


DotNetNuke® is a registered trademark of DotNetNuke Corporation