/// -----------------------------------------------------------------------------
        /// <summary>
        /// ValidateUser runs when the user has been authorized by the data store.  It validates for
        /// things such as an expiring password, valid profile, or missing DNN User Association
        /// </summary>
        /// <param name="objUser">The logged in User</param>
        /// <param name="ignoreExpiring">Ignore the situation where the password is expiring (but not yet expired)</param>
        /// <history>
        ///     [cnurse]	03/15/2006
        ///     [cnurse]    07/03/2007  Moved from Sign.ascx.vb
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ValidateUser(UserInfo objUser, bool ignoreExpiring)
        {
            UserValidStatus validStatus = UserValidStatus.VALID;
            string          strMessage  = Null.NullString;
            DateTime        expiryDate  = Null.NullDate;

            if (!objUser.IsSuperUser)
            {
                validStatus = UserController.ValidateUser(objUser, PortalId, ignoreExpiring);
            }
            if (PasswordConfig.PasswordExpiry > 0)
            {
                expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry);
            }
            UserId = objUser.UserID;

            //Check if the User has valid Password/Profile
            switch (validStatus)
            {
            case UserValidStatus.VALID:
                //Set the Page Culture(Language) based on the Users Preferred Locale
                if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null))
                {
                    Localization.SetLanguage(objUser.Profile.PreferredLocale);
                }
                else
                {
                    Localization.SetLanguage(PortalSettings.DefaultLanguage);
                }

                //Set the Authentication Type used
                AuthenticationController.SetAuthenticationType(AuthenticationType);

                //Complete Login
                UserController.UserLogin(PortalId, objUser, PortalSettings.PortalName, AuthenticationLoginBase.GetIPAddress(), chkCookie.Checked);

                //redirect browser
                Response.Redirect(RedirectURL, true);
                break;

            case UserValidStatus.PASSWORDEXPIRED:
                strMessage = string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.PASSWORDEXPIRING:
                strMessage = string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = true;
                break;

            case UserValidStatus.UPDATEPASSWORD:
                AddModuleMessage("PasswordUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.UPDATEPROFILE:
                //Admin has forced profile update
                AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo = 3;
                break;
            }
            ShowPanel();
        }
Example #2
0
        protected override void OnLoad(EventArgs e)
        {
            if (Request.QueryString["noSAML"] != null)
            {
            }
            else
            {
                base.OnLoad(e);
                staticPortalSettings = PortalSettings;
                string redirectTo = "~/";
                try
                {
                    config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                    if (Request.HttpMethod == "POST" && !Request.IsAuthenticated)
                    {
                        //specify the certificate that your SAML provider has given to you
                        string samlCertificate = config.TheirCert;

                        Saml.Response samlResponse = new Saml.Response(samlCertificate);
                        LogToEventLog("Request:", Request.Form["SAMLResponse"].ToString());
                        samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]); //SAML providers usually POST the data into this var
                                                                                      //String xmlExample = "";
                                                                                      //samlResponse.LoadXml(xmlExample);

                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  ", samlResponse.ToString()));

                        if (samlResponse.IsValid())
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml valid");
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  {0}", samlResponse.Xml.ToString()));
                            //WOOHOO!!! user is logged in
                            //YAY!

                            //Obtain optional items
                            string username = "", email = "", firstname = "", lastname = "", displayname = "";
                            var    rolesList         = new List <string>();
                            var    requiredRolesList = new List <string>();
                            try
                            {
                                username = samlResponse.GetNameID();

                                if (username == null)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS NULL");
                                }
                                else
                                {
                                    if (username == "")
                                    {
                                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS EMPTY");
                                    }
                                }


                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Username is: {0} ", username));

                                email = samlResponse.GetUserProperty(config.usrEmail);
                                if (email == null)
                                {
                                    email = samlResponse.GetUserProperty("email");
                                }
                                firstname = samlResponse.GetUserProperty(config.usrFirstName);
                                if (firstname == null)
                                {
                                    firstname = samlResponse.GetUserProperty("firstName");
                                }
                                lastname = samlResponse.GetUserProperty(config.usrLastName);
                                if (lastname == null)
                                {
                                    lastname = samlResponse.GetUserProperty("lastName");
                                }
                                displayname = samlResponse.GetUserProperty(config.usrDisplayName);
                                if (displayname == null)
                                {
                                    displayname = samlResponse.GetUserProperty("displayName");
                                }

                                var roles = samlResponse.GetUserProperty(config.RoleAttribute);
                                if (!string.IsNullOrWhiteSpace(roles))
                                {
                                    rolesList = roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                }

                                var requiredRoles = samlResponse.GetUserProperty(config.RequiredRoles);
                                if (!string.IsNullOrWhiteSpace(requiredRoles))
                                {
                                    requiredRolesList = requiredRoles.Split(new[] { ',' },
                                                                            StringSplitOptions.RemoveEmptyEntries).ToList();
                                }
                            }
                            catch (Exception ex)
                            {
                                //insert error handling code
                                //no, really, please do
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception:......{0}", ex.InnerException.Message));
                            }


                            UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, username);


                            if (userInfo == null)
                            {
                                //user does not exists, it needs to be created.
                                userInfo = new UserInfo();
                                try
                                {
                                    if (username != null && email != null && firstname != null && lastname != null)
                                    {
                                        if (displayname == null)
                                        {
                                            userInfo.DisplayName = firstname + " " + lastname;
                                        }
                                        else
                                        {
                                            userInfo.DisplayName = displayname;
                                        }

                                        userInfo.FirstName           = firstname;
                                        userInfo.LastName            = lastname;
                                        userInfo.Username            = username;
                                        userInfo.Email               = email;
                                        userInfo.PortalID            = PortalSettings.PortalId;
                                        userInfo.IsSuperUser         = false;
                                        userInfo.Membership.Password = UserController.GeneratePassword();

                                        var usrCreateStatus = new UserCreateStatus();

                                        usrCreateStatus = UserController.CreateUser(ref userInfo);

                                        if (usrCreateStatus == UserCreateStatus.Success)
                                        {
                                            UserInfo usrInfo = UserController.GetUserByName(PortalSettings.PortalId, username);
                                            SetProfileProperties(samlResponse, usrInfo);

                                            //Add roles if needed, since a new user no need to remove roles or process that condition
                                            if (rolesList.Any())
                                            {
                                                AssignRolesFromList(usrInfo, rolesList);
                                            }
                                        }
                                        else
                                        {
                                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user..." + usrCreateStatus.ToString());
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user...exception:  " + ex.InnerException.Message);
                                }
                            }
                            else
                            {
                                //User already exists

                                //Wen unlock it if necessary
                                if (userInfo.Membership.LockedOut)
                                {
                                    UserController.UnLockUser(userInfo);
                                }
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username));


                                try
                                {
                                    //We update the user's info
                                    userInfo.DisplayName = displayname;
                                    userInfo.FirstName   = firstname;
                                    userInfo.LastName    = lastname;
                                    userInfo.Email       = email;

                                    UserController.UpdateUser(PortalSettings.PortalId, userInfo);

                                    //We update the user's properties
                                    SetProfileProperties(samlResponse, userInfo);

                                    //Ensure roles if neeeded
                                    if (rolesList.Any())
                                    {
                                        AssignRolesFromList(userInfo, rolesList);
                                    }

                                    //If we have a required role list, remove any of those items that were not in the SAML attribute
                                    if (requiredRolesList.Any())
                                    {
                                        var toRemove = requiredRolesList.Where(req => !rolesList.Contains(req))
                                                       .ToList();
                                        RemoveRolesFromList(userInfo, toRemove);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error updating existing user...exception:  " + ex.InnerException.Message);
                                }
                            }


                            UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true);
                            UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE;
                            if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                            {
                                SetLoginDate(username);
                                //Raise UserAuthenticated Event
                                var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one.  How did it get named SAML????
                                {
                                    Authenticated = true,
                                    Message       = "User authorized",
                                    RememberMe    = false
                                };
                                OnUserAuthenticated(eventArgs);
                            }
                        }
                        else
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml not valid");
                        }
                    }
                    else if (Request.IsAuthenticated)
                    {
                        //Do Nothing if the request is authenticated
                    }
                    else
                    {
                        XmlDocument request = GenerateSAMLRequest();
                        //X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName);
                        //request = StaticHelper.SignSAMLRequest(request, cert);
                        LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml));
                        String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request);
                        redirectTo = config.IdPURL + (config.IdPURL.Contains("?") ? "&" : "?") + "SAMLRequest=" + convertedRequestXML;
                        if (Request.QueryString.Count > 0)
                        {
                            redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&"));
                        }

                        Response.Redirect(Page.ResolveUrl(redirectTo), false);
                    }
                }
                catch (System.Threading.ThreadAbortException tae)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception is {0}", tae.Message));
                    //Response.Redirect(Page.ResolveUrl(redirectTo), false);
                }
                catch (Exception ex)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception  {0}", ex.Message));
                    //redirectTo = "~/";
                }

                //Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
        }
            //private static void UpdateProfile(UserInfo objUser, bool update)
            //{
            //    bool bUpdateUser = false;
            //    if (ProfileProperties.Count > 0)
            //    {
            //        foreach (string key in ProfileProperties)
            //        {
            //            switch (key)
            //            {
            //                case "FirstName":
            //                    if (objUser.FirstName != ProfileProperties[key])
            //                    {
            //                        objUser.FirstName = ProfileProperties[key];
            //                        bUpdateUser = true;
            //                    }
            //                    break;
            //                case "LastName":
            //                    if (objUser.LastName != ProfileProperties[key])
            //                    {
            //                        objUser.LastName = ProfileProperties[key];
            //                        bUpdateUser = true;
            //                    }
            //                    break;
            //                case "Email":
            //                    if (objUser.Email != ProfileProperties[key])
            //                    {
            //                        objUser.Email = ProfileProperties[key];
            //                        bUpdateUser = true;
            //                    }
            //                    break;
            //                case "DisplayName":
            //                    if (objUser.DisplayName != ProfileProperties[key])
            //                    {
            //                        objUser.DisplayName = ProfileProperties[key];
            //                        bUpdateUser = true;
            //                    }
            //                    break;
            //                default:
            //                    objUser.Profile.SetProfileProperty(key, ProfileProperties[key]);
            //                    break;
            //            }
            //        }
            //        if (update)
            //        {
            //            if (bUpdateUser)
            //            {
            //                UserController.UpdateUser(PortalSettings.Current.PortalId, objUser);
            //            }
            //            ProfileController.UpdateUserProfile(objUser);
            //        }
            //    }
            //}


            /// -----------------------------------------------------------------------------
            /// <summary>
            /// ValidateUser runs when the user has been authorized by the data store.  It validates for
            /// things such as an expiring password, valid profile, or missing DNN User Association
            /// </summary>
            /// <param name="objUser">The logged in User</param>
            /// <param name="ignoreExpiring">Ignore the situation where the password is expiring (but not yet expired)</param>
            /// -----------------------------------------------------------------------------
            private static ActionResult ValidateUser(UserInfo objUser, bool ignoreExpiring)
            {
                ActionResult    actionResult = new ActionResult();
                UserValidStatus validStatus  = UserValidStatus.VALID;
                string          strMessage   = Null.NullString;
                DateTime        expiryDate   = Null.NullDate;

                validStatus = UserController.ValidateUser(objUser, PortalSettings.Current.PortalId, ignoreExpiring);

                if (PasswordConfig.PasswordExpiry > 0)
                {
                    expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry);
                }

                //Check if the User has valid Password/Profile
                switch (validStatus)
                {
                case UserValidStatus.VALID:
                    //check if the user is an admin/host and validate their IP
                    if (Host.EnableIPChecking)
                    {
                        bool isAdminUser = objUser.IsSuperUser || objUser.IsInRole(PortalSettings.Current.AdministratorRoleName);
                        if (isAdminUser)
                        {
                            if (IPFilterController.Instance.IsIPBanned(HttpContext.Current.Request.UserHostAddress))
                            {
                                PortalSecurity.Instance.SignOut();
                                actionResult.AddError("IPAddressBanned", Localization.GetString("IPAddressBanned", LocalResourceFile));
                                break;
                            }
                        }
                    }

                    //Set the Page Culture(Language) based on the Users Preferred Locale
                    if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null) && LocaleEnabled(objUser.Profile.PreferredLocale))
                    {
                        Localization.SetLanguage(objUser.Profile.PreferredLocale);
                    }
                    else
                    {
                        Localization.SetLanguage(PortalSettings.Current.DefaultLanguage);
                    }

                    //Set the Authentication Type used
                    AuthenticationController.SetAuthenticationType(AuthenticationType);

                    //Complete Login
                    IUserRequestIPAddressController userRequestIpAddressController = UserRequestIPAddressController.Instance;
                    string ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
                    UserController.UserLogin(PortalSettings.Current.PortalId, objUser, PortalSettings.Current.PortalName, ipAddress, RememberMe);

                    //check whether user request comes with IPv6 and log it to make sure admin is aware of that
                    if (string.IsNullOrWhiteSpace(ipAddress))
                    {
                        string ipAddressV6 = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request), IPAddressFamily.IPv6);

                        if (!string.IsNullOrWhiteSpace(ipAddressV6))
                        {
                            AddEventLog(objUser.UserID, objUser.Username, PortalSettings.Current.PortalId, "IPv6", ipAddressV6);
                        }
                    }

                    //redirect browser
                    //var redirectUrl = RedirectURL;

                    //Clear the cookie
                    HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", "")
                    {
                        Expires = DateTime.Now.AddDays(-1),
                        Path    = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/")
                    });

                    actionResult.RedirectURL = GetRedirectUrl();
                    break;

                case UserValidStatus.PASSWORDEXPIRED:
                    //strMessage = string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString());
                    //AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                    actionResult.AddError("PASSWORDEXPIRED", string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString()));
                    break;

                case UserValidStatus.PASSWORDEXPIRING:
                    //strMessage = string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString());
                    //AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                    actionResult.AddError("PASSWORDEXPIRING", string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString()));

                    break;

                case UserValidStatus.UPDATEPASSWORD:
                    string portalAlias = Globals.AddHTTP(PortalSettings.Current.PortalAlias.HTTPAlias);
                    if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled)
                    {
                        UserController.ResetPasswordToken(objUser);
                        objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID);
                    }
                    string redirTo = string.Format("{0}/default.aspx?ctl=PasswordReset&resetToken={1}&forced=true", portalAlias, objUser.PasswordResetToken);
                    //Response.Redirect(redirTo);
                    break;

                case UserValidStatus.UPDATEPROFILE:
                    //Save UserID in ViewState so that can update profile later

                    //When the user need update its profile to complete login, we need clear the login status because if the logrin is from
                    //3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation.
                    actionResult.Data = new { UserExtensionURL = ServiceProvider.NavigationManager.NavigateURL("", "mid=0", "icp=true", "guid=fa7ca744-1677-40ef-86b2-ca409c5c6ed3#/updateprofile?uid=" + objUser.UserID) };
                    PortalSecurity.Instance.SignOut();
                    //Admin has forced profile update
                    actionResult.AddError("ProfileUpdate", Localization.GetString("ProfileUpdate", LocalResourceFile));
                    break;

                case UserValidStatus.MUSTAGREETOTERMS:
                    if (PortalSettings.Current.DataConsentConsentRedirect == -1)
                    {
                        //AddModuleMessage("MustConsent", ModuleMessage.ModuleMessageType.YellowWarning, true);
                        actionResult.AddError("MUSTAGREETOTERMS", string.Format(Localization.GetString("MustConsent", LocalResourceFile), expiryDate.ToLongDateString()));
                    }
                    else
                    {
                        // Use the reset password token to identify the user during the redirect
                        UserController.ResetPasswordToken(objUser);
                        objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID);
                        actionResult.RedirectURL = ServiceProvider.NavigationManager.NavigateURL(PortalSettings.Current.DataConsentConsentRedirect, "", string.Format("token={0}", objUser.PasswordResetToken));
                    }
                    break;
                }
                return(actionResult);
            }
Example #4
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ValidateUser runs when the user has been authorized by the data store.  It validates for
        /// things such as an expiring password, valid profile, or missing DNN User Association
        /// </summary>
        /// <param name="objUser">The logged in User</param>
        /// <param name="ignoreExpiring">Ignore the situation where the password is expiring (but not yet expired)</param>
        /// -----------------------------------------------------------------------------
        private void ValidateUser(UserInfo objUser, bool ignoreExpiring)
        {
            UserValidStatus validStatus = UserValidStatus.VALID;
            string          strMessage  = Null.NullString;
            DateTime        expiryDate  = Null.NullDate;

            validStatus = UserController.ValidateUser(objUser, PortalId, ignoreExpiring);

            if (PasswordConfig.PasswordExpiry > 0)
            {
                expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry);
            }
            UserId = objUser.UserID;

            //Check if the User has valid Password/Profile
            switch (validStatus)
            {
            case UserValidStatus.VALID:
                //Set the Page Culture(Language) based on the Users Preferred Locale
                if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null))
                {
                    Localization.SetLanguage(objUser.Profile.PreferredLocale);
                }
                else
                {
                    Localization.SetLanguage(PortalSettings.DefaultLanguage);
                }

                //Set the Authentication Type used
                AuthenticationController.SetAuthenticationType(AuthenticationType);

                //Complete Login
                UserController.UserLogin(PortalId, objUser, PortalSettings.PortalName, AuthenticationLoginBase.GetIPAddress(), RememberMe);

                //redirect browser
                var redirectUrl = RedirectURL;

                //Clear the cookie
                HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", "")
                {
                    Expires = DateTime.Now.AddDays(-1)
                });

                Response.Redirect(redirectUrl, true);
                break;

            case UserValidStatus.PASSWORDEXPIRED:
                strMessage = string.Format(Localization.GetString("PasswordExpired", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.PASSWORDEXPIRING:
                strMessage = string.Format(Localization.GetString("PasswordExpiring", LocalResourceFile), expiryDate.ToLongDateString());
                AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = true;
                break;

            case UserValidStatus.UPDATEPASSWORD:
                AddModuleMessage("PasswordUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo             = 2;
                pnlProceed.Visible = false;
                break;

            case UserValidStatus.UPDATEPROFILE:
                //When the user need update its profile to complete login, we need clear the login status because if the logrin is from
                //3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation.
                new PortalSecurity().SignOut();
                //Admin has forced profile update
                AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true);
                PageNo = 3;
                break;
            }
            ShowPanel();
        }
Example #5
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            staticPortalSettings = PortalSettings;
            string redirectTo = "~/";

            try
            {
                config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                if (Request.HttpMethod == "POST" && !Request.IsAuthenticated)
                {
                    if (Request.Form["RelayState"] != null)
                    {
                        string relayState = HttpUtility.UrlDecode(Request.Form["RelayState"]);
                        LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", string.Format("relayState : {0}", relayState));
                        var relayStateSplit = relayState.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string s in relayStateSplit)
                        {
                            if (s.ToLower().StartsWith("returnurl"))
                            {
                                redirectTo = "~" + s.Replace("returnurl=", "");
                                break;
                            }
                        }
                    }


                    X509Certificate2          myCert = StaticHelper.GetCert(config.OurCertFriendlyName);
                    System.Text.ASCIIEncoding enc    = new System.Text.ASCIIEncoding();
                    string          responseXML      = enc.GetString(Convert.FromBase64String(Request.Form["SAMLResponse"]));
                    ResponseHandler responseHandler  = new ResponseHandler(responseXML, myCert,
                                                                           config.TheirCert
                                                                           );

                    LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", "responseXML : " + responseHandler.ResponseString());


                    string   emailFromSAMLResponse = responseHandler.GetNameID();
                    UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, emailFromSAMLResponse);
                    if (userInfo == null)
                    {
                        userInfo                     = new UserInfo();
                        userInfo.Username            = emailFromSAMLResponse;
                        userInfo.PortalID            = base.PortalId;
                        userInfo.DisplayName         = emailFromSAMLResponse;
                        userInfo.Email               = emailFromSAMLResponse;
                        userInfo.FirstName           = emailFromSAMLResponse;
                        userInfo.LastName            = emailFromSAMLResponse;
                        userInfo.Membership.Password = UserController.GeneratePassword(12).ToString();

                        UserCreateStatus rc = UserController.CreateUser(ref userInfo);
                        if (rc == UserCreateStatus.Success)
                        {
                            addRoleToUser(userInfo, "Subscribers", DateTime.MaxValue);
                        }
                    }
                    else
                    {
                        LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username));
                    }


                    string sessionIndexFromSAMLResponse = responseHandler.GetSessionIndex();
                    Session["sessionIndexFromSAMLResponse"] = sessionIndexFromSAMLResponse;


                    UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true);
                    UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE;
                    if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                    {
                        //Raise UserAuthenticated Event
                        var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one.  How did it get named SAML????
                        {
                            Authenticated = true,
                            Message       = "User authorized",
                            RememberMe    = false
                        };
                        OnUserAuthenticated(eventArgs);
                    }
                }
                else if (Request.IsAuthenticated)
                {
                    //if (!Response.IsRequestBeingRedirected)
                    //    Response.Redirect(Page.ResolveUrl("~/"), false);
                }
                else
                {
                    XmlDocument      request = GenerateSAMLRequest();
                    X509Certificate2 cert    = StaticHelper.GetCert(config.OurCertFriendlyName);
                    request = StaticHelper.SignSAMLRequest(request, cert);
                    LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml));
                    String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request);
                    redirectTo =
                        config.IdPURL +
                        (config.IdPURL.Contains("?") ? "&" : "?") +
                        "SAMLRequest=" + convertedRequestXML;
                    if (Request.QueryString.Count > 0)
                    {
                        redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&"));
                    }
                }
            }
            catch (System.Threading.ThreadAbortException tae)
            {
                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Redirecting to  {0}", redirectTo));
                Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
            catch (Exception ex)
            {
                LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception  {0}", ex.Message));
                redirectTo = "~/";
            }

            Response.Redirect(Page.ResolveUrl(redirectTo), false);
        }
        public dynamic Index(Entities.ResetPassword PasswordReset)
        {
            dynamic actionResult = new ExpandoObject();

            try
            {
                PasswordReset.ResetToken = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.Split('/')[HttpContext.Current.Request.UrlReferrer.AbsoluteUri.Split('/').Length - 1];
                UserInfo UserInfo = UserController.GetUserByPasswordResetToken(PortalSettings.Current.PortalId, PasswordReset.ResetToken);
                _ipAddress = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
                string username = PasswordReset.Username;
                if (PasswordReset.Password != PasswordReset.ConfirmPassword)
                {
                    string failed = Localization.GetString("PasswordMismatch");
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }
                string newPassword = PasswordReset.Password.Trim();
                if (UserController.ValidatePassword(newPassword) == false)
                {
                    string failed = Localization.GetString("PasswordResetFailed");
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }

                MembershipPasswordSettings settings = new MembershipPasswordSettings(PortalSettings.Current.PortalId);
                if (settings.EnableBannedList)
                {
                    MembershipPasswordController m = new MembershipPasswordController();
                    if (m.FoundBannedPassword(newPassword) || username == newPassword)
                    {
                        string failed = Localization.GetString("PasswordResetFailed");
                        LogFailure(failed, UserInfo);
                        actionResult.IsSuccess = false;
                        actionResult.Message   = failed;
                        return(actionResult);
                    }
                }
                if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalSettings.Current.PortalId, false))
                {
                    UserInfo testUser = UserController.GetUserByEmail(PortalSettings.Current.PortalId, username); // one additonal call to db to see if an account with that email actually exists
                    if (testUser != null)
                    {
                        username = testUser.Username; //we need the username of the account in order to change the password in the next step
                    }
                }
                if (UserController.ChangePasswordByToken(PortalSettings.PortalId, username, newPassword, null, PasswordReset.ResetToken, out string errorMessage) == false)
                {
                    string failed = errorMessage;
                    LogFailure(failed, UserInfo);
                    actionResult.IsSuccess = false;
                    actionResult.Message   = failed;
                    return(actionResult);
                }
                else
                {
                    //check user has a valid profile
                    UserInfo        user        = UserController.GetUserByName(PortalSettings.PortalId, username);
                    UserValidStatus validStatus = UserController.ValidateUser(user, PortalSettings.PortalId, false);
                    if (validStatus == UserValidStatus.UPDATEPROFILE)
                    {
                        LogSuccess(UserInfo);
                    }
                    else
                    {
                        //Log user in to site
                        LogSuccess(UserInfo);
                        UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                        UserController.UserLogin(PortalSettings.PortalId, username, PasswordReset.Password, "", "", "", ref loginStatus, false);
                        actionResult.Message = Localization.GetString("ChangeSuccessful", LocalResourceFile);
                    }
                }
                actionResult.IsSuccess   = true;
                actionResult.IsRedirect  = true;
                actionResult.RedirectURL = Managers.ResetPasswordManager.RedirectAfterLogin();
            }
            catch (Exception ex)
            {
                actionResult.IsSuccess = false;
                actionResult.Message   = ex.Message;
            }
            return(actionResult);
        }