Beispiel #1
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
            {
                var loginStatus   = UserLoginStatus.LOGIN_FAILURE;
                var objUser       = UserController.ValidateUser(PortalId, txtUsername.Text, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                //Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, txtUsername.Text, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = chkCookie.Checked
                };
                OnUserAuthenticated(eventArgs);
            }
        }
Beispiel #2
0
 public void OnUserAuthenticated(UserAuthenticatedEventArgs ea)
 {
     if (UserAuthenticated != null)
     {
         UserAuthenticated(null, ea);
     }
 }
Beispiel #3
0
        public void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;

            string userName = Service + "-" + user.Id;

            UserInfo objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "",
                                                               Service, "",
                                                               settings.PortalName, IPAddress,
                                                               ref loginStatus);


            //Raise UserAuthenticated Event
            UserAuthenticatedEventArgs eventArgs = new UserAuthenticatedEventArgs(objUserInfo, userName, loginStatus, Service);

            eventArgs.AutoRegister = true;

            NameValueCollection profileProperties = new NameValueCollection();

            profileProperties.Add("FirstName", user.FirstName);
            profileProperties.Add("LastName", user.LastName);
            profileProperties.Add("Email", user.Email);
            profileProperties.Add("DisplayName", user.DisplayName);
            if (!String.IsNullOrEmpty(user.Locale))
            {
                profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
            }
            //profileProperties.Add("City", user.City);
            profileProperties.Add("ProfileImage", user.ProfileImage);
            profileProperties.Add("Website", user.Website);

            if (String.IsNullOrEmpty(user.TimeZoneInfo))
            {
#pragma warning disable 612,618

                int timeZone;
                if (Int32.TryParse(user.Timezone, out timeZone))
                {
                    TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);

                    profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
                }

#pragma warning restore 612,618
            }
            else
            {
                profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
            }


            addCustomProperties(profileProperties);

            eventArgs.Profile = profileProperties;

            SaveTokenCookie(String.Empty);

            onAuthenticated(eventArgs);
        }
        /// <summary>
        ///     Raises the <see cref="Pop3CommandProcessor.UserAuthenticated" />
        ///     event.
        /// </summary>
        /// <param name="e">
        ///     The <see cref="UserAuthenticatedEventArgs" />
        ///     instance containing the event data.
        /// </param>
        /// <remarks>Occurs once the client has successfully authenticated.</remarks>
        protected virtual void OnUserAuthenticated(UserAuthenticatedEventArgs e)
        {
            EventHandler <UserAuthenticatedEventArgs> handler = UserAuthenticated;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Beispiel #5
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || !this.UseCaptcha)
            {
                var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                string userName    = PortalSecurity.Instance.InputFilter(
                    this.txtUsername.Text,
                    PortalSecurity.FilterFlag.NoScripting |
                    PortalSecurity.FilterFlag.NoAngleBrackets |
                    PortalSecurity.FilterFlag.NoMarkup);

                // DNN-6093
                // check if we use email address here rather than username
                UserInfo userByEmail         = null;
                var      emailUsedAsUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", this.PortalId, false);

                if (emailUsedAsUsername)
                {
                    // one additonal call to db to see if an account with that email actually exists
                    userByEmail = UserController.GetUserByEmail(PortalController.GetEffectivePortalId(this.PortalId), userName);

                    if (userByEmail != null)
                    {
                        // we need the username of the account in order to authenticate in the next step
                        userName = userByEmail.Username;
                    }
                }

                UserInfo objUser = null;

                if (!emailUsedAsUsername || userByEmail != null)
                {
                    objUser = UserController.ValidateUser(this.PortalId, userName, this.txtPassword.Text, "DNN", string.Empty, this.PortalSettings.PortalName, this.IPAddress, ref loginStatus);
                }

                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = loginStatus != UserLoginStatus.LOGIN_FAILURE;
                }

                // Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = this.chkCookie.Checked,
                };
                this.OnUserAuthenticated(eventArgs);
            }
        }
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
            {
                var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                string userName    = new PortalSecurity().InputFilter(txtUsername.Text,
                                                                      PortalSecurity.FilterFlag.NoScripting |
                                                                      PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                      PortalSecurity.FilterFlag.NoMarkup);

                //DNN-6093
                //check if we use email address here rather than username
                if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                {
                    var testUser = UserController.GetUserByEmail(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 authenticate in the next step
                    }
                }

                var objUser       = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                if (loginStatus != UserLoginStatus.LOGIN_FAILURE && PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                {
                    //make sure internal username matches current e-mail address
                    if (objUser.Username.ToLower() != objUser.Email.ToLower())
                    {
                        UserController.ChangeUsername(objUser.UserID, objUser.Email);
                    }

                    Response.Cookies.Remove("USERNAME_CHANGED");
                }

                //Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = chkCookie.Checked
                };
                OnUserAuthenticated(eventArgs);
            }
        }
        private void UserAuthenticated(object sender, UserAuthenticatedEventArgs e)
        {
            NameValueCollection profileProperties = e.Profile;

            this.User.Username      = e.UserToken;
            this.AuthenticationType = e.AuthenticationType;
            this.UserToken          = e.UserToken;

            foreach (string key in profileProperties)
            {
                switch (key)
                {
                case "FirstName":
                    this.User.FirstName = profileProperties[key];
                    break;

                case "LastName":
                    this.User.LastName = profileProperties[key];
                    break;

                case "Email":
                    this.User.Email = profileProperties[key];
                    break;

                case "DisplayName":
                    this.User.DisplayName = profileProperties[key];
                    break;

                default:
                    this.User.Profile.SetProfileProperty(key, profileProperties[key]);
                    break;
                }
            }

            // Generate a random password for the user
            this.User.Membership.Password = UserController.GeneratePassword();

            if (!string.IsNullOrEmpty(this.User.Email))
            {
                this.CreateUser();
            }
            else
            {
                this.AddLocalizedModuleMessage(this.LocalizeString("NoEmail"), ModuleMessage.ModuleMessageType.RedError, true);
                foreach (DnnFormItemBase formItem in this.userForm.Items)
                {
                    formItem.Visible = formItem.DataField == "Email";
                }

                this.userForm.DataBind();
            }
        }
        public override void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var loginStatus = UserLoginStatus.LOGIN_FAILURE;

            var userData = GetCurrentUser <RedditUserData>();

            string userName = "******" + userData.Email;

            var userInfo = UserController.ValidateUser(settings.PortalId, userName, "",
                                                       RedditService, "",
                                                       settings.PortalName, IPAddress,
                                                       ref loginStatus);


            var eventArgs = new UserAuthenticatedEventArgs(userInfo, userName, loginStatus, RedditService)
            {
                AutoRegister = true
            };

            eventArgs.Profile = new NameValueCollection();

            if (userInfo == null || (string.IsNullOrEmpty(userInfo.FirstName) && !string.IsNullOrEmpty(userData.FirstName)))
            {
                eventArgs.Profile.Add("FirstName", userData.FirstName);
            }
            if (userInfo == null || (string.IsNullOrEmpty(userInfo.LastName) && !string.IsNullOrEmpty(userData.LastName)))
            {
                eventArgs.Profile.Add("LastName", userData.LastName);
            }
            if (userInfo == null || (string.IsNullOrEmpty(userInfo.Email) && !string.IsNullOrEmpty(userData.Email)))
            {
                eventArgs.Profile.Add("Email", userData.PreferredEmail);
            }
            if (userInfo == null ||
                (string.IsNullOrEmpty(userInfo.DisplayName) && !string.IsNullOrEmpty(userData.DisplayName)) ||
                (userInfo.DisplayName == userData.Name && userInfo.DisplayName != userData.DisplayName))
            {
                eventArgs.Profile.Add("DisplayName", userData.DisplayName);
            }

            onAuthenticated(eventArgs);
        }
Beispiel #9
0
        /// <summary>
        /// cmdLogin_Click runs when the login button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	9/24/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        ///     [cnurse]    12/11/2005  Updated to reflect abstraction of Membership
        ///     [cnurse]    07/03/2007  Moved from Sign.ascx.vb
        /// </history>
        private void OnLoginClick(object sender, EventArgs e)
        {
            if ((UseCaptcha && ctlCaptcha.IsValid) || (!UseCaptcha))
            {
                var loginStatus   = UserLoginStatus.LOGIN_FAILURE;
                var objUser       = UserController.ValidateUser(PortalId, txtUsername.Text, txtPassword.Text, "DNN", txtVerification.Text, PortalSettings.PortalName, IPAddress, ref loginStatus);
                var authenticated = Null.NullBoolean;
                var message       = Null.NullString;
                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    //Check if its the first time logging in to a verified site
                    if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration)
                    {
                        if (!divVerify.Visible)
                        {
                            //Display Verification Rows so User can enter verification code
                            divVerify.Visible = true;
                            message           = "EnterCode";
                        }
                        else
                        {
                            message = !String.IsNullOrEmpty(txtVerification.Text) ? "InvalidCode" : "EnterCode";
                        }
                    }
                    else
                    {
                        message = "UserNotAuthorized";
                    }
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                //Raise UserAuthenticated Event
                var eventArgs = new UserAuthenticatedEventArgs(objUser, txtUsername.Text, loginStatus, "DNN")
                {
                    Authenticated = authenticated, Message = message
                };
                OnUserAuthenticated(eventArgs);
            }
        }
        /// <summary>
        /// UserAuthenticated runs when the user is authenticated by one of the child
        /// Authentication controls
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	07/10/2007  Created
        /// </history>
        protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e)
        {
            LoginStatus = e.LoginStatus;

            //Check the Login Status
            switch (LoginStatus)
            {
            case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                switch (e.Message)
                {
                case "EnterCode":
                    AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true);
                    break;

                case "InvalidCode":
                case "UserNotAuthorized":
                    AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    break;

                default:
                    AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    break;
                }
                break;

            case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true);
                //notify administrator about account lockout ( possible hack attempt )
                var Custom = new ArrayList {
                    e.UserToken
                };

                var message = new Message
                {
                    FromUserID = PortalSettings.AdministratorId,
                    ToUserID   = PortalSettings.AdministratorId,
                    Subject    = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom),
                    Body       = Localization.GetSystemMessage(PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom),
                    Status     = MessageStatusType.Unread
                };
                //_messagingController.SaveMessage(_message);

                Mail.SendEmail(PortalSettings.Email, PortalSettings.Email, message.Subject, message.Body);
                break;

            case UserLoginStatus.LOGIN_FAILURE:
                //A Login Failure can mean one of two things:
                //  1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account
                //  2 - User was not authenticated
                if (e.Authenticated)
                {
                    PageNo             = 1;
                    AuthenticationType = e.AuthenticationType;
                    AutoRegister       = e.AutoRegister;
                    ProfileProperties  = e.Profile;
                    UserToken          = e.UserToken;

                    ShowPanel();
                }
                else
                {
                    if (string.IsNullOrEmpty(e.Message))
                    {
                        AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true);
                    }
                    else
                    {
                        AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true);
                    }
                }
                break;

            default:
                if (e.User != null)
                {
                    //First update the profile (if any properties have been passed)
                    AuthenticationType = e.AuthenticationType;
                    ProfileProperties  = e.Profile;
                    UpdateProfile(e.User, true);
                    ValidateUser(e.User, false);
                }
                break;
            }
        }
Beispiel #11
0
        public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var loginStatus = UserLoginStatus.LOGIN_FAILURE;

            string userName = Service + "-" + user.Id;

            var objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "",
                                                          Service, "",
                                                          settings.PortalName, IPAddress,
                                                          ref loginStatus);


            //Raise UserAuthenticated Event
            var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, userName, loginStatus, Service)
            {
                AutoRegister = true
            };

            var profileProperties = new NameValueCollection();

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName)))
            {
                profileProperties.Add("FirstName", user.FirstName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName)))
            {
                profileProperties.Add("LastName", user.LastName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email)))
            {
                profileProperties.Add("Email", user.PreferredEmail);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName)))
            {
                profileProperties.Add("DisplayName", user.DisplayName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage)))
            {
                profileProperties.Add("ProfileImage", user.ProfileImage);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website)))
            {
                profileProperties.Add("Website", user.Website);
            }
            if ((objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale")))) && !string.IsNullOrEmpty(user.Locale))
            {
                profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
            }

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))))
            {
                if (String.IsNullOrEmpty(user.TimeZoneInfo))
                {
                    int timeZone;
                    if (Int32.TryParse(user.Timezone, out timeZone))
                    {
                        var timeZoneInfo = Localization.Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);

                        profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
                    }
                }
                else
                {
                    profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
                }
            }

            addCustomProperties(profileProperties);

            eventArgs.Profile = profileProperties;

            if (Mode == AuthMode.Login)
            {
                SaveTokenCookie(String.Empty);
            }

            onAuthenticated(eventArgs);
        }
Beispiel #12
0
 private void HandleUserAuthenticated(object sender, UserAuthenticatedEventArgs e)
 {
 }
Beispiel #13
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);
            }
        }
            public static ActionResult UserAuthenticated(UserAuthenticatedEventArgs e)
            {
                ActionResult actionResult = new ActionResult();

                LoginStatus = e.LoginStatus;

                //Check the Login Status
                switch (LoginStatus)
                {
                case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                    switch (e.Message)
                    {
                    case "UnverifiedUser":
                        if (e.User != null)
                        {
                            //First update the profile (if any properties have been passed)
                            AuthenticationType = e.AuthenticationType;
                            //ProfileProperties = e.Profile;
                            RememberMe = e.RememberMe;
                            //UpdateProfile(e.User, true);
                            actionResult = ValidateUser(e.User, false);
                        }
                        break;

                    case "EnterCode":
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;

                    case "InvalidCode":
                    case "UserNotAuthorized":
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;

                    default:
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                        break;
                    }
                    break;

                case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                    if (Host.AutoAccountUnlockDuration > 0)
                    {
                        actionResult.AddError("UserLockedOut", string.Format(Localization.GetString("UserLockedOut", LocalResourceFile), Host.AutoAccountUnlockDuration));
                    }
                    else
                    {
                        actionResult.AddError("UserLockedOut_ContactAdmin", Localization.GetString("UserLockedOut_ContactAdmin", LocalResourceFile));
                    }
                    //notify administrator about account lockout ( possible hack attempt )
                    ArrayList Custom = new ArrayList {
                        e.UserToken
                    };

                    Message message = new Message
                    {
                        FromUserID = PortalSettings.Current.AdministratorId,
                        ToUserID   = PortalSettings.Current.AdministratorId,
                        Subject    = Localization.GetSystemMessage(PortalSettings.Current, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom),
                        Body       = Localization.GetSystemMessage(PortalSettings.Current, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom),
                        Status     = MessageStatusType.Unread
                    };
                    //_messagingController.SaveMessage(_message);

                    Mail.SendEmail(PortalSettings.Current.Email, PortalSettings.Current.Email, message.Subject, message.Body);
                    break;

                case UserLoginStatus.LOGIN_FAILURE:
                    //A Login Failure can mean one of two things:
                    //  1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account
                    //  2 - User was not authenticated
                    if (string.IsNullOrEmpty(e.Message))
                    {
                        actionResult.AddError("LoginFailed", Localization.GetString("LoginFailed", LocalResourceFile));
                    }
                    else
                    {
                        actionResult.AddError(e.Message.ToString(), Localization.GetString(e.Message, LocalResourceFile));
                    }
                    break;

                default:
                    if (e.User != null)
                    {
                        //First update the profile (if any properties have been passed)
                        AuthenticationType = e.AuthenticationType;
                        //ProfileProperties = e.Profile;
                        RememberMe = e.RememberMe;
                        //UpdateProfile(e.User, true);
                        actionResult = ValidateUser(e.User, (e.AuthenticationType != "DNN"));
                    }
                    break;
                }
                return(actionResult);
            }
Beispiel #15
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);
        }
Beispiel #16
0
        private void OnUserAuthenticated(object sender, UserAuthenticatedEventArgs e)
        {
            MainViewModel mainViewModel = new MainViewModel(e.Username);

            CurrentViewModel = mainViewModel;
        }
Beispiel #17
0
            public static UserAuthenticatedEventArgs UserLogin(dynamic userLogin)
            {
                string          IPAddress   = UserRequestIPAddressController.Instance.GetUserRequestIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
                UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
                string          userName    = PortalSecurity.Instance.InputFilter(userLogin.Username,
                                                                                  PortalSecurity.FilterFlag.NoScripting |
                                                                                  PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                                  PortalSecurity.FilterFlag.NoMarkup);
                //check if we use email address here rather than username
                //UserInfo userByEmail = null;
                //bool emailUsedAsUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalSettings.Current.PortalId, false);

                //if (emailUsedAsUsername)
                //{
                //    // one additonal call to db to see if an account with that email actually exists
                //    userByEmail = UserController.GetUserByEmail(PortalSettings.Current.PortalId, userName);

                //    if (userByEmail != null)
                //    {
                //        //we need the username of the account in order to authenticate in the next step
                //        userName = userByEmail.Username;
                //    }
                //}


                //if (!emailUsedAsUsername || userByEmail != null)
                //{
                UserInfo objUser = UserController.ValidateUser(PortalSettings.Current.PortalId, userName, userLogin.Password, "DNN", string.Empty, PortalSettings.Current.PortalName, IPAddress, ref loginStatus);
                //}

                bool   authenticated = Null.NullBoolean;
                string message       = Null.NullString;

                if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                {
                    message = "UserNotAuthorized";
                }
                else
                {
                    authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                }

                //if (objUser != null && loginStatus != UserLoginStatus.LOGIN_FAILURE && emailUsedAsUsername)
                //{
                //    //make sure internal username matches current e-mail address
                //    if (objUser.Username.ToLower() != objUser.Email.ToLower())
                //    {
                //        UserController.ChangeUsername(objUser.UserID, objUser.Email);
                //        userName = objUser.Username = objUser.Email;
                //    }
                //}

                //Raise UserAuthenticated Event
                UserAuthenticatedEventArgs eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                {
                    Authenticated = authenticated,
                    Message       = message,
                    RememberMe    = userLogin.Remember
                };

                //if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER)
                //{
                //    UserController.UserLogin(PortalSettings.Current.PortalId, objUser, PortalSettings.Current.PortalName, IPAddress, false);
                //}

                return(eventArgs);
            }
 private void OnUserAuthenticated(object sender, UserAuthenticatedEventArgs e)
 {
     this.CurrentSecurityAddIn++;
     this.Controls.Clear();
     this.BuildSurvey();
 }
Beispiel #19
0
        protected override void OnUserAuthenticated(UserAuthenticatedEventArgs ea)
        {
            _portalRegistrationValue = -1;

            // Adding roles to list and removing in profile list
            var    roles    = new List <String>();
            string userName = null;

            foreach (var key in ea.Profile.AllKeys)
            {
                if (key.StartsWith("Role_"))
                {
                    roles.Add(ea.Profile[key]);
                    ea.Profile.Remove(key);
                }
                if (key.StartsWith("epicDisplayName"))
                {
                    userName = ea.Profile[key];
                }
            }

            switch (ea.LoginStatus)
            {
            case UserLoginStatus.LOGIN_SUCCESS:

                // Adding roles
                var user      = ea.User;
                var userRoles = RoleController.Instance.GetUserRoles(ea.User, true);

                if (user != null && userRoles != null)
                {
                    foreach (var userRol in userRoles)
                    {
                        RoleInfo oldRole = RoleController.Instance.GetRoleByName(user.PortalID, userRol.RoleName);
                        if (oldRole != null && oldRole.RoleName != "Registered Users" && oldRole.RoleName != "Subscribers")
                        {
                            // I used the release date of the first game of Epic Games ZZT October 1, 1991
                            // as the effective date to mark the roles synchronized by the Epic Games provider.
                            if (userRol.EffectiveDate == DateTime.Parse("1991-10-01"))
                            {
                                RoleController.DeleteUserRole(user, oldRole, PortalSettings, false);
                            }
                        }
                    }
                    foreach (var rol in roles)
                    {
                        RoleInfo newRole = RoleController.Instance.GetRoleByName(user.PortalID, rol);
                        if (newRole != null)
                        {
                            // I used the release date of the first game of Epic Games ZZT October 1, 1991
                            // as the effective date to mark the roles synchronized by the Epic Games provider.
                            RoleController.Instance.AddUserRole(user.PortalID, user.UserID, newRole.RoleID, RoleStatus.Approved, false, DateTime.Parse("1991-10-01"), DateTime.MaxValue);
                        }
                    }
                }

                base.OnUserAuthenticated(ea);

                break;

            case UserLoginStatus.LOGIN_FAILURE:
                // TODO: confirm if we have to create authorized users
                SavePortalRegistrationType();
                //prevent send new user registration mail
                var emailSetting = PortalSettings.Email;
                PortalSettings.Email = string.Empty;

                base.OnUserAuthenticated(ea);

                //restore the email setting
                PortalSettings.Email = emailSetting;

                // Adding roles

                var newUser = DotNetNuke.Entities.Users.UserController.GetUserByName(userName);
                if (newUser != null)
                {
                    foreach (var rol in roles)
                    {
                        RoleInfo newRole = RoleController.Instance.GetRoleByName(newUser.PortalID, rol);
                        if (newRole != null)
                        {
                            RoleController.Instance.AddUserRole(newUser.PortalID, newUser.UserID, newRole.RoleID, RoleStatus.Approved, false, DateTime.MinValue, DateTime.MaxValue);
                        }
                    }
                }

                RestorePortalRegistrationType();
                break;

            case UserLoginStatus.LOGIN_USERLOCKEDOUT:
                AddModuleMessage("UserLockout", ModuleMessage.ModuleMessageType.RedError, true);
                break;

            case UserLoginStatus.LOGIN_USERNOTAPPROVED:
                AddModuleMessage("UserNotApproved", ModuleMessage.ModuleMessageType.RedError, true);
                break;
            }
        }
Beispiel #20
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            ///TRY TO LOGIN WITH WS
            var result = Innovaction.WSManager.ValidateLogin(txtUsername.Text, txtPassword.Text);

            if (result.responseCode.ToString() == Innovaction.CustomerDataWS.responseCode.SUCCESS.ToString())
            {
                /****** CREATE USER ******/

                //We create the new user in the portal, even if it exists we don't care
                UserInfo newUser = new UserInfo();
                newUser.Username            = txtUsername.Text;
                newUser.PortalID            = PortalId;
                newUser.DisplayName         = txtUsername.Text;
                newUser.Email               = txtUsername.Text;
                newUser.FirstName           = txtUsername.Text;
                newUser.LastName            = txtUsername.Text;
                newUser.Membership.Password = txtPassword.Text;
                //newUser.Profile.SetProfileProperty("tel", "47940983");

                //The line that creates the new User
                DotNetNuke.Security.Membership.UserCreateStatus userResult = DotNetNuke.Entities.Users.UserController.CreateUser(ref newUser);


                /****** LOGIN USER AT THE PORTAL ******/

                var myUser = DotNetNuke.Entities.Users.UserController.GetUserByName(txtUsername.Text);                 // IF WE USE THIS WE CAN LOGIN WITHOUT PASSWORD
                DotNetNuke.Entities.Users.UserController.UserLogin(PortalId, myUser, PortalSettings.PortalName, "", false);

                //try to redirect
                string myReturnUrl = "";
                try
                {
                    myReturnUrl = System.Web.HttpContext.Current.Request.QueryString["returnurl"].ToString();
                }
                catch
                {
                }

                if (myReturnUrl != "")
                {
                    string unescapedUrl = System.Uri.UnescapeDataString(myReturnUrl);
                    System.Web.HttpContext.Current.Response.Redirect(unescapedUrl);
                }

                else
                {
                    System.Web.HttpContext.Current.Response.Redirect("/");
                }



                /*
                 * var eventArgs = new UserAuthenticatedEventArgs(myUser, txtUsername.Text, UserLoginStatus.LOGIN_SUCCESS, "DNN")
                 *                                              {
                 *                                                      Authenticated = True,
                 *                                                      Message = "",
                 *                                                      RememberMe = False
                 *                                              };
                 *
                 *      OnUserAuthenticated(eventArgs);
                 *
                 * //System.Web.HttpContext.Current.Response.Redirect("http://www.bspdota.com.ar/hola?=" + "1.0.1" + result.responseCode.ToString());
                 */
            }

            else             ///ELSE TRY WITH DOTNETNUKE
            {
                if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
                {
                    var loginStatus   = UserLoginStatus.LOGIN_FAILURE;
                    var objUser       = UserController.ValidateUser(PortalId, txtUsername.Text, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                    var authenticated = Null.NullBoolean;
                    var message       = Null.NullString;
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        message = "UserNotAuthorized";
                    }
                    else
                    {
                        authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                    }

                    //Raise UserAuthenticated Event
                    var eventArgs = new UserAuthenticatedEventArgs(objUser, txtUsername.Text, loginStatus, "DNN")
                    {
                        Authenticated = authenticated,
                        Message       = message,
                        RememberMe    = chkCookie.Checked
                    };
                    OnUserAuthenticated(eventArgs);
                }
            }
        }
        public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var loginStatus = UserLoginStatus.LOGIN_FAILURE;

            var objUserInfo = UserController.ValidateUser(settings.PortalId, user.Id, string.Empty, _service, string.Empty, settings.PortalName, IPAddress, ref loginStatus);


            // Raise UserAuthenticated Event
            var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, user.Id, loginStatus, _service)
            {
                AutoRegister = true
            };

            // TODO:
            var profileProperties = new NameValueCollection();

            if (string.IsNullOrEmpty(objUserInfo?.FirstName) && !string.IsNullOrEmpty(user.FirstName))
            {
                profileProperties.Add("FirstName", user.FirstName);
            }

            if (string.IsNullOrEmpty(objUserInfo?.LastName) && !string.IsNullOrEmpty(user.LastName))
            {
                profileProperties.Add("LastName", user.LastName);
            }

            if (string.IsNullOrEmpty(objUserInfo?.Email) && !string.IsNullOrEmpty(user.Email))
            {
                profileProperties.Add("Email", user.Email);
            }

            if (string.IsNullOrEmpty(objUserInfo?.DisplayName) && !string.IsNullOrEmpty(user.DisplayName))
            {
                profileProperties.Add("DisplayName", user.DisplayName);
            }

            if (string.IsNullOrEmpty(objUserInfo?.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website))
            {
                profileProperties.Add("Website", user.Website);
            }

            if (string.IsNullOrEmpty(objUserInfo?.Profile.GetPropertyValue("PreferredLocale")) && !string.IsNullOrEmpty(user.Locale))
            {
                if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-')))
                {
                    profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
                }
                else
                {
                    profileProperties.Add("PreferredLocale", settings.CultureCode);
                }
            }

            //if (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))))
            //{
            //    if (string.IsNullOrEmpty(user.TimeZoneInfo))
            //    {
            //        if (Int32.TryParse(user.Timezone, out int timeZone))
            //        {
            //            var timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);

            //            profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
            //        }
            //    }
            //    else
            //    {
            //        profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
            //    }
            //}

            addCustomProperties(profileProperties);

            eventArgs.Profile = profileProperties;

            onAuthenticated(eventArgs);
        }
Beispiel #22
0
 public void UserAuthenticated(object sender, UserAuthenticatedEventArgs e)
 {
     base.Log($"Endpoint {((IPEndPoint)e.EndPoint).ToString()} authenticated as : {e.UserName}", RecordKind.Status);
 }
Beispiel #23
0
        private void OnLoginClick(object sender, EventArgs e)
        {
            //It validates whether the user will be reset your password.
            var listUser = Membership.GetAllUsers().Cast <MembershipUser>().Where(x => x.Email.ToLower().Trim() == txtUsername.Text.ToLower().Trim() && x.Comment == "ChangePassword").FirstOrDefault();

            if (listUser != null)
            {
                // Gets user information
                _user = UserController.GetUserByEmail(PortalSettings.PortalId, txtUsername.Text.Trim());

                // Validates if the user is not removed from the system
                if (!_user.IsDeleted)
                {
                    //Web config parameters are validated and the password reset token
                    if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled)
                    {
                        UserController.ResetPasswordToken(_user);
                    }

                    //The email is sent to the user and the Comment field is updated in the table asp [ aspnet_Membership ]
                    Mail.SendMail(_user, MessageType.PasswordReminder, PortalSettings);
                    listUser.Comment = string.Empty;
                    Membership.UpdateUser(listUser);
                    Response.Redirect(NexsoHelper.GetCulturedUrlByTabName("RessetSecurityPassword"));
                }
            }
            else
            {
                if ((UseCaptcha && ctlCaptcha.IsValid) || !UseCaptcha)
                {
                    var    loginStatus = UserLoginStatus.LOGIN_FAILURE;
                    string userName    = new PortalSecurity().InputFilter(txtUsername.Text,
                                                                          PortalSecurity.FilterFlag.NoScripting |
                                                                          PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                          PortalSecurity.FilterFlag.NoMarkup);

                    //DNN-6093
                    //check if we use email address here rather than username
                    if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                    {
                        var testUser = UserController.GetUserByEmail(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 authenticate in the next step
                        }
                    }

                    var objUser       = UserController.ValidateUser(PortalId, userName, txtPassword.Text, "DNN", string.Empty, PortalSettings.PortalName, IPAddress, ref loginStatus);
                    var authenticated = Null.NullBoolean;
                    var message       = Null.NullString;
                    if (loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED)
                    {
                        message = "UserNotAuthorized";
                    }
                    else
                    {
                        authenticated = (loginStatus != UserLoginStatus.LOGIN_FAILURE);
                    }

                    if (loginStatus != UserLoginStatus.LOGIN_FAILURE && PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false))
                    {
                        //make sure internal username matches current e-mail address
                        if (objUser.Username.ToLower() != objUser.Email.ToLower())
                        {
                            UserController.ChangeUsername(objUser.UserID, objUser.Email);
                        }

                        Response.Cookies.Remove("USERNAME_CHANGED");
                    }

                    //Raise UserAuthenticated Event
                    var eventArgs = new UserAuthenticatedEventArgs(objUser, userName, loginStatus, "DNN")
                    {
                        Authenticated = authenticated,
                        Message       = message,
                        RememberMe    = chkCookie.Checked
                    };
                    OnUserAuthenticated(eventArgs);
                }
            }
        }
        public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action <NameValueCollection> addCustomProperties, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var loginStatus = UserLoginStatus.LOGIN_FAILURE;

            string userName = PrefixServiceToUserName ? Service + "-" + user.Id : user.Id;
            string token    = Service + "-" + user.Id;

            UserInfo objUserInfo;

            if (AutoMatchExistingUsers)
            {
                objUserInfo = MembershipProvider.Instance().GetUserByUserName(settings.PortalId, userName);
                if (objUserInfo != null)
                {
                    //user already exists... lets check for a token next...
                    var dnnAuthToken = MembershipProvider.Instance().GetUserByAuthToken(settings.PortalId, token, Service);
                    if (dnnAuthToken == null)
                    {
                        DataProvider.Instance().AddUserAuthentication(objUserInfo.UserID, Service, token, objUserInfo.UserID);
                    }
                }
            }

            objUserInfo = UserController.ValidateUser(settings.PortalId, userName, "",
                                                      Service, token,
                                                      settings.PortalName, IPAddress,
                                                      ref loginStatus);


            //Raise UserAuthenticated Event
            var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, Service)
            {
                AutoRegister = true,
                UserName     = userName,
            };

            var profileProperties = new NameValueCollection();

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName)))
            {
                profileProperties.Add("FirstName", user.FirstName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName)))
            {
                profileProperties.Add("LastName", user.LastName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email)))
            {
                profileProperties.Add("Email", user.PreferredEmail);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.DisplayName)))
            {
                profileProperties.Add("DisplayName", user.DisplayName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.ProfileImage)))
            {
                profileProperties.Add("ProfileImage", user.ProfileImage);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website)))
            {
                profileProperties.Add("Website", user.Website);
            }
            if ((objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale")))) && !string.IsNullOrEmpty(user.Locale))
            {
                if (LocaleController.IsValidCultureName(user.Locale.Replace('_', '-')))
                {
                    profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
                }
                else
                {
                    profileProperties.Add("PreferredLocale", settings.CultureCode);
                }
            }

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))))
            {
                if (String.IsNullOrEmpty(user.TimeZoneInfo))
                {
                    int timeZone;
                    if (Int32.TryParse(user.Timezone, out timeZone))
                    {
                        var timeZoneInfo = Localization.Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(timeZone);

                        profileProperties.Add("PreferredTimeZone", timeZoneInfo.Id);
                    }
                }
                else
                {
                    profileProperties.Add("PreferredTimeZone", user.TimeZoneInfo);
                }
            }

            addCustomProperties(profileProperties);

            eventArgs.Profile = profileProperties;

            if (Mode == AuthMode.Login)
            {
                SaveTokenCookie(String.Empty);
            }

            onAuthenticated(eventArgs);
        }
Beispiel #25
0
        public virtual void AuthenticateDnnUser(Auth0UserInfo user, PortalSettings settings, string IPAddress, Action <UserAuthenticatedEventArgs> onAuthenticated)
        {
            var loginStatus = UserLoginStatus.LOGIN_FAILURE;

            var objUserInfo = UserController.ValidateUser(
                settings.PortalId,
                user.UserId,
                "",
                _Service,
                "",
                settings.PortalName,
                IPAddress,
                ref loginStatus);


            //Raise UserAuthenticated Event
            var eventArgs = new UserAuthenticatedEventArgs(objUserInfo, user.UserId, loginStatus, _Service)
            {
                AutoRegister = true
            };

            var profileProperties = new NameValueCollection();

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.FirstName) && !string.IsNullOrEmpty(user.FirstName)))
            {
                profileProperties.Add("FirstName", user.FirstName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.LastName) && !string.IsNullOrEmpty(user.LastName)))
            {
                profileProperties.Add("LastName", user.LastName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Email) && !string.IsNullOrEmpty(user.Email)))
            {
                profileProperties.Add("Email", user.Email);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.DisplayName) && !string.IsNullOrEmpty(user.FullName)))
            {
                profileProperties.Add("DisplayName", user.FullName);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("ProfileImage")) && !string.IsNullOrEmpty(user.Picture)))
            {
                profileProperties.Add("ProfileImage", user.Picture);
            }
            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("Website")) && !string.IsNullOrEmpty(user.Website)))
            {
                profileProperties.Add("Website", user.Website);
            }
            if ((objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredLocale")))) && !string.IsNullOrEmpty(user.Locale))
            {
                if (IsValidCultureName(user.Locale.Replace('_', '-')))
                {
                    profileProperties.Add("PreferredLocale", user.Locale.Replace('_', '-'));
                }
                else
                {
                    profileProperties.Add("PreferredLocale", settings.CultureCode);
                }
            }

            if (objUserInfo == null || (string.IsNullOrEmpty(objUserInfo.Profile.GetPropertyValue("PreferredTimeZone"))))
            {
                profileProperties.Add("PreferredTimeZone", user.ZoneInformation);
            }

            eventArgs.Profile = profileProperties;

            //SaveTokenCookie(String.Empty);

            onAuthenticated(eventArgs);
        }