コード例 #1
0
        private SiteUser CreateUser(
            string openId,
            string email,
            string loginName,
            string name,
            bool emailIsVerified)
        {
            SiteUser newUser = new SiteUser(siteSettings);
            newUser.Email = email;

            if (loginName.Length > 50) loginName = loginName.Substring(0, 50);

            int i = 1;
            while (SiteUser.LoginExistsInDB(
                siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50) loginName = loginName.Remove(40, 1);
                i++;

            }
            if ((name == null) || (name.Length == 0)) name = loginName;
            newUser.LoginName = loginName;
            newUser.Name = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;
            newUser.Password = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri = openId;
            newUser.Save();

            //test
            //emailIsVerified = false;

            if (siteSettings.UseSecureRegistration)
            {
                if (!emailIsVerified)
                {
                    newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());

                }
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
            #if!MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey) { continue; }
            #endif
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
            #if!MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey) { continue; }
            #endif
                if ((propertyDefinition.RequiredForRegistration)||(propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());
            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);
            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            // we'll map them next time they login
            //OpenIdRpxHelper rpxHelper = new OpenIdRpxHelper(rpxApiKey, rpxBaseUrl);
            //rpxHelper.Map(openId, newUser.UserGuid.ToString());

            DoSubscribe(newUser);

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            return newUser;
        }
コード例 #2
0
        void application_AuthenticateRequest(object sender, EventArgs e)
        {
            //if (debugLog) log.Debug("AuthHandlerHttpModule Application_AuthenticateRequest");

            if (sender == null) return;

            HttpApplication app = (HttpApplication)sender;
            if (app.Request == null) { return; }
            if (!app.Request.IsAuthenticated) { return; }

            if(WebUtils.IsRequestForStaticFile(app.Request.Path)) { return; }
            if (app.Request.Path.ContainsCaseInsensitive(".ashx")) { return; }
            if (app.Request.Path.ContainsCaseInsensitive(".axd")) { return; }
            if (app.Request.Path.ContainsCaseInsensitive("setup/default.aspx")) { return; }

            //if (debugLog) log.Debug("IsAuthenticated == true");
            SiteSettings siteSettings;
            try
            {
                siteSettings = CacheHelper.GetCurrentSiteSettings();
            }
            catch (System.Data.Common.DbException ex)
            {
                // can happen during upgrades
                log.Error(ex);
                return;
            }
            catch (Exception ex)
            {
                // hate to trap System.Exception but SqlCeException doe snot inherit from DbException as it should
                if (DatabaseHelper.DBPlatform() != "SqlCe") { throw; }
                log.Error(ex);
                return;
            }
            bool useFolderForSiteDetection = WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites;

            // Added by Haluk Eryuksel - 2006-01-23
            // support for Windows authentication
            if (
                (app.User.Identity.AuthenticationType == "NTLM")
                || (app.User.Identity.AuthenticationType == "Negotiate")
                // || ( Context.User.Identity.AuthenticationType == "Windows" )
                )
            {
                //Added by Benedict Chan - 2008-08-05
                //Added Cookie here so that we don't have to check the users in every page, also to authenticate under NTLM with "useFolderForSiteDetection == true"
                string cookieName = "siteguid" + siteSettings.SiteGuid;
                if (!CookieHelper.CookieExists(cookieName))
                {
                    bool existsInDB;
                    existsInDB = SiteUser.LoginExistsInDB(siteSettings.SiteId, app.Context.User.Identity.Name);

                    if (!existsInDB)
                    {
                        SiteUser u = new SiteUser(siteSettings);
                        u.Name = app.Context.User.Identity.Name;
                        u.LoginName = app.Context.User.Identity.Name;
                        u.Email = GuessEmailAddress(u.Name);
                        u.Password = SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars);

                        mojoMembershipProvider m = Membership.Provider as mojoMembershipProvider;
                        if (m != null)
                        {
                            u.Password = m.EncodePassword(siteSettings, u, u.Password);
                        }

                        u.Save();
                        NewsletterHelper.ClaimExistingSubscriptions(u);

                        UserRegisteredEventArgs args = new UserRegisteredEventArgs(u);
                        OnUserRegistered(args);

                    }

                    SiteUser siteUser = new SiteUser(siteSettings, app.Context.User.Identity.Name);
                    CookieHelper.SetCookie(cookieName, siteUser.UserGuid.ToString(), true);

                    //Copied logic from SiteLogin.cs  Since we will skip them if we use NTLM
                    if (siteUser.UserId > -1 && siteSettings.AllowUserSkins && siteUser.Skin.Length > 0)
                    {
                        SiteUtils.SetSkinCookie(siteUser);
                    }

                    // track user ip address
                    try
                    {
                        UserLocation userLocation = new UserLocation(siteUser.UserGuid, SiteUtils.GetIP4Address());
                        userLocation.SiteGuid = siteSettings.SiteGuid;
                        userLocation.Hostname = app.Request.UserHostName;
                        userLocation.Save();
                        log.Info("Set UserLocation : " + app.Request.UserHostName + ":" + SiteUtils.GetIP4Address());
                    }
                    catch (Exception ex)
                    {
                        log.Error(SiteUtils.GetIP4Address(), ex);
                    }
                }

                //End-Added by Benedict Chan

            }
            // End-Added by Haluk Eryuksel

            if ((useFolderForSiteDetection) && (!WebConfigSettings.UseRelatedSiteMode))
            {
                // replace GenericPrincipal with custom one
                //string roles = string.Empty;
                if (!(app.Context.User is mojoIdentity))
                {
                    app.Context.User = new mojoPrincipal(app.Context.User);
                }
            }
        }
コード例 #3
0
        private void CreateUser(
            string openId,
            string email,
            string loginName,
            string name)
        {
            SiteUser newUser = new SiteUser(siteSettings);
            newUser.Email = email;

            if (loginName.Length > 50) loginName = loginName.Substring(0, 50);

            int i = 1;
            while (SiteUser.LoginExistsInDB(
                siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50) loginName = loginName.Remove(40, 1);
                i++;

            }
            if ((name == null) || (name.Length == 0)) name = loginName;
            newUser.LoginName = loginName;
            newUser.Name = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;
            newUser.Password = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri = openId;
            newUser.Save();
            if (siteSettings.UseSecureRegistration)
            {
                newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                if ((propertyDefinition.RequiredForRegistration)||(propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());
            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);
            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            DoUserLogin(newUser);
        }
コード例 #4
0
        private void CreateUser(string windowsLiveId)
        {
            SiteUser newUser = new SiteUser(siteSettings);
            newUser.WindowsLiveId = windowsLiveId;
            newUser.Name = SecurityHelper.RemoveMarkup(txtUserName.Text);
            newUser.LoginName = newUser.Name;
            newUser.Email = txtEmail.Text;
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;
            newUser.Password = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.Save();
            if (siteSettings.UseSecureRegistration)
            {
                newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
            #if!MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey) { continue; }
            #endif
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
            #if!MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey) { continue; }
            #endif
                if ((propertyDefinition.RequiredForRegistration)||(propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());
            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);
            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            DoUserLogin(newUser);
        }
コード例 #5
0
ファイル: mojoSetup.cs プロジェクト: joedavis01/mojoportal
        private static SiteUser EnsureAdminUser(SiteSettings site)
        {
            // if using related sites mode there is a problem if we already have user [email protected]
            // and we create another one in the child site with the same email and login so we need to make it different
            // we could just skip creating this user since in related sites mode all users come from the first site
            // but then if the config were changed to not related sites mode there would be no admin user
            // so in related sites mode we create one only as a backup in case settings are changed later
            int countOfSites = SiteSettings.SiteCount();
            string siteDifferentiator = string.Empty;
            if (
                (countOfSites >= 1)
                && (WebConfigSettings.UseRelatedSiteMode)
                )
            {
                siteDifferentiator = site.SiteId.ToString(CultureInfo.InvariantCulture);
            }

            mojoMembershipProvider membership = Membership.Provider as mojoMembershipProvider;
            bool overridRelatedSiteMode = true;
            SiteUser adminUser = new SiteUser(site, overridRelatedSiteMode);
            adminUser.Email = "admin" + siteDifferentiator + "@admin.com";
            adminUser.Name = "Admin";
            adminUser.LoginName = "admin" + siteDifferentiator;
            bool userExists = false;
            if (site.UseEmailForLogin)
            {
                userExists = SiteUser.EmailExistsInDB(site.SiteId, adminUser.Email);
            }
            else
            {
                userExists = SiteUser.LoginExistsInDB(site.SiteId, adminUser.LoginName);
            }

            if (!userExists)
            {
                adminUser.Password = "******";

                if (membership != null)
                {
                    adminUser.Password = membership.EncodePassword(site, adminUser, "admin");
                }

                adminUser.PasswordQuestion = "What is your user name?";
                adminUser.PasswordAnswer = "admin";
                adminUser.Save();

                //Role.AddUser(adminRole.RoleId, adminUser.UserId, adminRole.RoleGuid, adminUser.UserGuid);
            }
            else
            {
                if (site.UseEmailForLogin)
                {
                    adminUser = new SiteUser(site, adminUser.Email);
                }
                else
                {
                    adminUser = new SiteUser(site, adminUser.LoginName);
                }
            }

            return adminUser;
        }
コード例 #6
0
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            /*
             * Takes, as input, a user name, a password (the user's current password), and a
             * new password and updates the password in the membership data source.
             * ChangePassword returns true if the password was updated successfully. Otherwise,
             * it returns false. Before changing a password, ChangePassword calls the provider's
             * virtual OnValidatingPassword method to validate the new password. It then
             * changes the password or cancels the action based on the outcome of the call. If the
             * user name, password, new password, or password answer is not valid,
             * ChangePassword does not throw an exception; it simply returns false. Following a
             * successful password change, ChangePassword updates the user's
             * LastPasswordChangedDate.
             */

            bool result = false;

            if (
                (username == null) || (username == String.Empty)
                || (oldPassword == null) || (oldPassword == String.Empty)
                || (newPassword == null) || (newPassword == String.Empty)
                )
            {
                return result;
            }

            SiteSettings siteSettings = GetSiteSettings();
            if (siteSettings == null) { return result; }

            if (newPassword.Length < siteSettings.MinRequiredPasswordLength)
            {
                throw new ArgumentException(ResourceHelper.GetMessageTemplate("PasswordNotLongEnoughMessage.config"));
            }

            int countNonAlphanumericCharacters = 0;
            for (int i = 0; i < newPassword.Length; i++)
            {
                if (!char.IsLetterOrDigit(newPassword, i))
                {
                    countNonAlphanumericCharacters++;
                }
            }

            if (countNonAlphanumericCharacters < siteSettings.MinRequiredNonAlphanumericCharacters)
            {
                throw new ArgumentException(ResourceHelper.GetMessageTemplate("PasswordRequiresMoreNonAlphanumericCharactersMessage.config"));
            }

            if (siteSettings.PasswordStrengthRegularExpression.Length > 0)
            {
                if (!Regex.IsMatch(newPassword, siteSettings.PasswordStrengthRegularExpression))
                {
                    throw new ArgumentException(
                        ResourceHelper.GetMessageTemplate("PasswordDoesntMatchRegularExpressionMessage.config"));
                }
            }

            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, newPassword, false);
            OnValidatingPassword(e);

            if (e.Cancel)
            {
                if (e.FailureInformation != null)
                {
                    throw e.FailureInformation;
                }
                else
                {
                    throw new ArgumentException("The custom password validation failed.");
                }
            }

            SiteUser siteUser = new SiteUser(siteSettings, username);
            if (siteUser.UserId == -1) { return result; }

            if (
                ((MembershipPasswordFormat)siteSettings.PasswordFormat == MembershipPasswordFormat.Hashed)
                && (!siteSettings.UseLdapAuth)
                )
            {
                if (siteUser.Password == EncodePassword(siteUser.PasswordSalt + oldPassword,MembershipPasswordFormat.Hashed))
                {
                    siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                    siteUser.Password = EncodePassword(siteUser.PasswordSalt + newPassword, MembershipPasswordFormat.Hashed);
                    siteUser.MustChangePwd = false;
                    siteUser.PasswordFormat = siteSettings.PasswordFormat;
                    result = siteUser.Save();
                }
            }
            else if ((MembershipPasswordFormat)siteSettings.PasswordFormat == MembershipPasswordFormat.Encrypted)
            {
                if (siteUser.Password == EncodePassword(siteUser.PasswordSalt + oldPassword, MembershipPasswordFormat.Encrypted))
                {
                    siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                    siteUser.Password = EncodePassword(siteUser.PasswordSalt + newPassword, MembershipPasswordFormat.Encrypted);
                    siteUser.MustChangePwd = false;
                    siteUser.PasswordFormat = siteSettings.PasswordFormat;
                    result = siteUser.Save();
                }
            }
            else if ((MembershipPasswordFormat)siteSettings.PasswordFormat == MembershipPasswordFormat.Clear)
            {
                if (siteUser.Password == oldPassword)
                {
                    siteUser.Password = newPassword;
                    siteUser.MustChangePwd = false;
                    siteUser.PasswordFormat = siteSettings.PasswordFormat;
                    result = siteUser.Save();
                }
            }

            if (result)
            {
                if (WebConfigSettings.LogIpAddressForPasswordChanges)
                {
                   log.Info("password for user " + siteUser.Name + " was changed from ip address " + SiteUtils.GetIP4Address());
                }

                siteUser.UpdateLastPasswordChangeTime();
            }

            return result;
        }
コード例 #7
0
        void rptRoleMembers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                int userId = Convert.ToInt32(e.CommandArgument);

                SiteUser user = new SiteUser(siteSettings, userId);

                Role.RemoveUser(roleID, userId);

                if (user.UserId > -1)
                {
                    user.RolesChanged = true;
                    user.Save();
                }

            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }
コード例 #8
0
ファイル: UserRoles.ascx.cs プロジェクト: saiesh86/TravelBlog
        private void UserRoles_ItemCommand(object sender, DataListCommandEventArgs e)
        {
            int roleID = Convert.ToInt32(userRoles.DataKeys[e.Item.ItemIndex]);
            SiteUser user = new SiteUser(siteSettings, userId);

            Role.RemoveUser(roleID, userId);
            userRoles.EditItemIndex = -1;
            if (user.UserId > -1)
            {
                user.RolesChanged = true;
                user.Save();
            }

            BindRoles();

            upRoles.Update();

            //WebUtils.SetupRedirect(this, Request.RawUrl);
            //return;
        }
コード例 #9
0
ファイル: SiteUtils.cs プロジェクト: joedavis01/mojoportal
        public static SiteUser CreateMinimalUser(SiteSettings siteSettings, string email, bool includeInMemberList, string adminComments)
        {
            if (siteSettings == null)
            {
                throw new ArgumentException("a valid siteSettings object is required for this method");
            }
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException("a valid email address is required for this method");
            }

            if (!Email.IsValidEmailAddressSyntax(email))
            {
                throw new ArgumentException("a valid email address is required for this method");
            }

            //first make sure he doesn't exist
            SiteUser siteUser = SiteUser.GetByEmail(siteSettings, email);
            if ((siteUser != null)&&(siteUser.UserGuid != Guid.Empty)) { return siteUser; }

            siteUser = new SiteUser(siteSettings);
            siteUser.Email = email;
            string login = SuggestLoginNameFromEmail(siteSettings.SiteId, email);
            //int offset = 1;
            //while (SiteUser.LoginExistsInDB(siteSettings.SiteId, login))
            //{
            //    login = login + offset.ToString(CultureInfo.InvariantCulture);
            //    offset += 1;
            //}

            siteUser.LoginName = login;
            siteUser.Name = login;
            siteUser.Password = SiteUser.CreateRandomPassword(siteSettings.MinRequiredPasswordLength + 2, WebConfigSettings.PasswordGeneratorChars);
            mojoMembershipProvider m = Membership.Provider as mojoMembershipProvider;
            if (m != null)
            {
                siteUser.Password = m.EncodePassword(siteSettings, siteUser, siteUser.Password);
            }

            siteUser.ProfileApproved = true;
            siteUser.DisplayInMemberList = includeInMemberList;
            siteUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            siteUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer;

            if (!string.IsNullOrEmpty(adminComments)) { siteUser.Comment = adminComments; }

            siteUser.Save();

            Role.AddUserToDefaultRoles(siteUser);

            return siteUser;
        }
コード例 #10
0
        public static void SaveProperty(
            SiteUser siteUser,
            Panel parentControl,
            mojoProfilePropertyDefinition propertyDefinition,
            Double legacyTimeZoneOffset,
            TimeZoneInfo timeZone)
        {
            String controlID;
            Control control;

            if (propertyDefinition.ISettingControlSrc.Length > 0)
            {
                controlID = "isc" + propertyDefinition.Name;
                control = parentControl.FindControl(controlID);
                if (control != null)
                {
                    siteUser.SetProperty(
                        propertyDefinition.Name,
                        ((ISettingControl)control).GetValue(),
                        propertyDefinition.SerializeAs,
                        propertyDefinition.LazyLoad);
                }

            }
            else
            {

                switch (propertyDefinition.Type)
                {
                    case "System.Boolean":

                        controlID = "chk" + propertyDefinition.Name;
                        control = parentControl.FindControl(controlID);
                        if (control != null)
                        {
                            siteUser.SetProperty(
                                propertyDefinition.Name,
                                ((CheckBox)control).Checked,
                                propertyDefinition.SerializeAs,
                                propertyDefinition.LazyLoad);

                        }

                        break;

                    case "System.DateTime":

                        controlID = "dp" + propertyDefinition.Name;
                        control = parentControl.FindControl(controlID);
                        if (control != null)
                        {
                            DatePickerControl dp = (DatePickerControl)control;
                            if (dp.Text.Length > 0)
                            {
                                DateTime dt;
                                if (DateTime.TryParse(
                                    dp.Text,
                                    CultureInfo.CurrentCulture,
                                    DateTimeStyles.AdjustToUniversal, out dt))
                                {

                                    if (propertyDefinition.IncludeTimeForDate)
                                    {
                                        if (timeZone != null)
                                        {
                                            dt = dt.ToUtc(timeZone);
                                        }
                                        else
                                        {
                                            dt = dt.AddHours(-legacyTimeZoneOffset);
                                        }

                                        if (propertyDefinition.Name == "DateOfBirth")
                                        {
                                            siteUser.DateOfBirth = dt.Date;
                                            siteUser.Save();
                                        }
                                        else
                                        {
                                            siteUser.SetProperty(
                                                propertyDefinition.Name,
                                                dt.ToString(),
                                                propertyDefinition.SerializeAs,
                                                propertyDefinition.LazyLoad);
                                        }
                                    }
                                    else
                                    {

                                        if(propertyDefinition.Name == "DateOfBirth")
                                        {
                                            siteUser.DateOfBirth = dt.Date;
                                            siteUser.Save();
                                        }
                                        else
                                        {
                                            siteUser.SetProperty(
                                            propertyDefinition.Name,
                                            dt.Date.ToShortDateString(),
                                            propertyDefinition.SerializeAs,
                                            propertyDefinition.LazyLoad);
                                        }

                                    }

                                }
                                else
                                {

                                        siteUser.SetProperty(
                                        propertyDefinition.Name,
                                        dp.Text,
                                        propertyDefinition.SerializeAs,
                                        propertyDefinition.LazyLoad);

                                }

                            }
                            else // blank
                            {
                                if (propertyDefinition.Name == "DateOfBirth")
                                {
                                    siteUser.DateOfBirth = DateTime.MinValue;
                                    siteUser.Save();
                                }
                                else
                                {
                                    siteUser.SetProperty(
                                        propertyDefinition.Name,
                                        String.Empty,
                                        propertyDefinition.SerializeAs,
                                        propertyDefinition.LazyLoad);
                                }
                            }
                        }

                        break;

                    case "System.String":
                    default:

                        if (propertyDefinition.OptionList.Count > 0)
                        {
                            if (propertyDefinition.Type == "CheckboxList")
                            {
                                controlID = "cbl" + propertyDefinition.Name;
                                control = parentControl.FindControl(controlID);
                                if (control != null)
                                {
                                    if (control is CheckBoxList)
                                    {
                                        CheckBoxList cbl = (CheckBoxList)control;

                                        siteUser.SetProperty(
                                            propertyDefinition.Name,
                                            cbl.Items.SelectedItemsToCommaSeparatedString(),
                                            propertyDefinition.SerializeAs,
                                            propertyDefinition.LazyLoad);

                                    }
                                }

                            }
                            else
                            {

                                controlID = "dd" + propertyDefinition.Name;
                                control = parentControl.FindControl(controlID);
                                if (control != null)
                                {
                                    if (control is DropDownList)
                                    {
                                        DropDownList dd = (DropDownList)control;
                                        if (dd.SelectedIndex > -1)
                                        {
                                            siteUser.SetProperty(
                                                propertyDefinition.Name,
                                                dd.SelectedValue,
                                                propertyDefinition.SerializeAs,
                                                propertyDefinition.LazyLoad);
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            controlID = "txt" + propertyDefinition.Name;
                            control = parentControl.FindControl(controlID);
                            if (control != null)
                            {
                                siteUser.SetProperty(
                                    propertyDefinition.Name,
                                    ((TextBox)control).Text,
                                    propertyDefinition.SerializeAs,
                                    propertyDefinition.LazyLoad);
                            }

                        }

                        break;

                }
            }
        }
コード例 #11
0
        public static void UpdateProfile(SiteUser su)
        {
            var yup = YafUserProfile.GetProfile(su.Email);

            // No MP counterpart to sync
            // yup.LastUpdatedDate
            // using IsDirty Property to sync to MP
            if (YafContext.Current.IsDirty)
            {
                // sync to MP
                su.AIM = yup.AIM;
                su.ICQ = yup.ICQ;
                su.Yahoo = yup.YIM;
                su.Interests = yup.Interests;
                su.MSN = yup.MSN;
                su.Occupation = yup.Occupation;

                switch (yup.Gender)
                {
                    case 0:
                        su.Gender = "";
                        break;
                    case 1:
                        su.Gender = "M";
                        break;
                    case 2:
                        su.Gender = "F";
                        break;
                    default:
                        su.Gender = "";
                        break;
                }

                su.Save();

                LegacyDb.user_setnotdirty(YafContext.Current.PageBoardID,YafContext.Current.PageUserID);
                YafContext.Current.Get<IRaiseEvent>().Raise(new UpdateUserEvent(YafContext.Current.PageUserID));
             }
            else
            {
                // sync to yaf
                yup.AIM = su.AIM;
                yup.ICQ = su.ICQ;
                yup.YIM = su.Yahoo;
                yup.RealName = su.FirstName + " " + su.LastName;
                yup.Interests = su.Interests;
                yup.MSN = su.MSN;
                yup.Occupation = su.Occupation;
                switch (su.Gender)
                {
                    case "":
                        yup.Gender = 0;
                        break;
                    case "M":
                        yup.Gender = 1;
                        break;
                    case "F":
                        yup.Gender = 2;
                        break;
                    default:
                        yup.Gender = 0;
                        break;
                }
            }
            // yup.Country = su.Country;
            yup.Save();
        }
コード例 #12
0
        public override string GetPassword(string userName, string passwordAnswer)
        {
            /*
             * Takes, as input, a user name and a password answer and returns that user's password.
             * If the user name is not valid, GetPassword throws a ProviderException. Before retrieving
             * a password, GetPassword verifies that EnablePasswordRetrieval is true.
             * If EnablePasswordRetrieval is false, GetPassword throws a NotSupportedException.
             * If EnablePasswordRetrieval is true but the password format is hashed, GetPassword
             * throws a ProviderException since hashed passwords cannot, by definition, be retrieved.
             * A membership provider should also throw a ProviderException from Initialize if
             * EnablePasswordRetrieval is true but the password format is hashed. GetPassword also
             * checks the value of the RequiresQuestionAndAnswer property before retrieving a password.
             * If RequiresQuestionAndAnswer is true, GetPassword compares the supplied password
             * answer to the stored password answer and throws a MembershipPasswordException if
             * the two don't match. GetPassword also throws a MembershipPasswordException if the
             * user whose password is being retrieved is currently locked out.
             */

            SiteSettings siteSettings = GetSiteSettings();

            if (!siteSettings.AllowPasswordRetrieval)
            {
                throw new MojoMembershipException(
                    ResourceHelper.GetMessageTemplate("PasswordRetrievalNotEnabledMessage.config")
                    );
            }

            if ((userName != null) && (siteSettings != null))
            {
                SiteUser siteUser = new SiteUser(siteSettings, userName);
                if (siteUser.UserId > -1)
                {
                    if (siteUser.IsLockedOut)
                    {
                        throw new MembershipPasswordException(
                            ResourceHelper.GetMessageTemplate("UserAccountLockedMessage.config"));
                    }

                    if (siteUser.IsDeleted)
                    {
                        throw new MembershipPasswordException(
                            ResourceHelper.GetMessageTemplate("UserNotFoundMessage.config"));
                    }

                    bool okToGetPassword = false;
                    if (siteSettings.RequiresQuestionAndAnswer)
                    {
                        if ((passwordAnswer != null) && (PasswordAnswerIsMatch(passwordAnswer, siteUser.PasswordAnswer)))
                        {
                            okToGetPassword = true;
                        }
                        else
                        {
                            if (siteSettings.MaxInvalidPasswordAttempts > 0)
                            {
                                siteUser.IncrementPasswordAnswerAttempts(siteSettings);

                                if (WebConfigSettings.LockAccountOnMaxPasswordAnswerTries)
                                {
                                    if (siteUser.FailedPasswordAnswerAttemptCount >= siteSettings.MaxInvalidPasswordAttempts)
                                    {
                                        siteUser.LockoutAccount();
                                    }
                                }

                            }
                        }

                    }
                    else
                    {
                        okToGetPassword = true;
                    }

                    if(okToGetPassword)
                    {
                        if (siteSettings.RequirePasswordChangeOnResetRecover)
                        {
                            siteUser.MustChangePwd = true;
                            siteUser.Save();
                        }

                        switch(PasswordFormat)
                        {
                            case MembershipPasswordFormat.Clear:

                                return siteUser.Password;

                            case MembershipPasswordFormat.Encrypted:

                                try
                                {
                                    if (siteUser.PasswordSalt.Length > 0)
                                    {
                                        return UnencodePassword(siteUser.Password, MembershipPasswordFormat.Encrypted).Replace(siteUser.PasswordSalt, string.Empty);
                                    }
                                    else
                                    {
                                        return UnencodePassword(siteUser.Password, MembershipPasswordFormat.Encrypted);
                                    }
                                }
                                catch (FormatException ex)
                                {
                                    log.Error(ex);
                                    throw new MembershipPasswordException("failure retrieving password");
                                }

                            case MembershipPasswordFormat.Hashed:

                                string newPassword = SiteUser.CreateRandomPassword(siteSettings.MinRequiredPasswordLength + 2, WebConfigSettings.PasswordGeneratorChars);

                                siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                                siteUser.Password = EncodePassword(siteUser.PasswordSalt + newPassword, MembershipPasswordFormat.Hashed);
                                siteUser.PasswordFormat = siteSettings.PasswordFormat;

                                //after the new random password is emailed to the user we can force him to change it again immediately after he logs in
                                siteUser.MustChangePwd = siteSettings.RequirePasswordChangeOnResetRecover;

                                // needed if we are sending a link for automatic login and force to change password instead of sending the random one by email
                                // will be cleared to Guid.Empty when password is changed
                                siteUser.PasswordResetGuid = Guid.NewGuid();
                                siteUser.Save();
                                //siteUser.UnlockAccount();
                                return newPassword;

                        }

                    }
                    else
                    {
                        return null;
                    }

                }
                else
                {
                    throw new ProviderException(ResourceHelper.GetMessageTemplate("UserNotFoundMessage.config"));

                }

            }

            return null;
        }
コード例 #13
0
        private bool PasswordIsValid(SiteSettings siteSettings, SiteUser siteUser, string providedPassword)
        {
            if (siteUser == null) { return false; }
            if (string.IsNullOrEmpty(providedPassword)) { return false; }

            bool isValid = false;
            bool didUpdatePassword = false;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    isValid = ClearTextPasswordIsValid(siteSettings, siteUser, providedPassword);
                    break;

                case MembershipPasswordFormat.Encrypted:

                    isValid = EncryptedPasswordIsValid(siteSettings, siteUser, providedPassword);

                    // this is to support older installations from before we used salt
                    if ((isValid) && (siteUser.PasswordSalt.Length == 0))
                    {   // user is valid but he doesn't have a salt
                        // generate a random salt and update the siteuser password to encrypted with salt
                        siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                        byte[] bIn = Encoding.Unicode.GetBytes(siteUser.PasswordSalt + providedPassword);
                        byte[] bRet = EncryptPassword(bIn);
                        siteUser.Password = Convert.ToBase64String(bRet);
                        siteUser.Save();

                    }

                    break;

                case MembershipPasswordFormat.Hashed:

                    isValid = HashedSha512PasswordIsValid(siteSettings, siteUser, providedPassword);

                    if ((!isValid) && (WebConfigSettings.CheckMD5PasswordHashAsFallback))
                    {
                        // previously we were using md5 so we need to check against that
                        // and if valid re-hash it with sha512
                        isValid = HashedMd5PasswordIsValid(siteSettings, siteUser, providedPassword);

                        if (isValid)
                        {
                            // update user to sha512 hash with random salt
                            // then set didUpdatePassword to true so we don't do it again below
                            siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                            siteUser.Password = GetSHA512Hash(siteUser.PasswordSalt + providedPassword);
                            siteUser.Save();
                            didUpdatePassword = true;

                        }

                    }

                    // this is to support older installations from before we used salt
                    if (
                        (isValid)
                        &&(!didUpdatePassword)
                        &&(siteUser.PasswordSalt.Length == 0)
                        )
                    {
                        // generate a random salt and update the siteuser password to encrypted with salt
                        siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                        siteUser.Password = GetSHA512Hash(siteUser.PasswordSalt + providedPassword);
                        siteUser.Save();

                    }

                    break;

            }

            if ((!isValid) && (WebConfigSettings.CheckAllPasswordFormatsOnAuthFailure))
            {
                // CheckAllPasswordFormatsOnAuthFailure is false by default so this code will not execute unless you change
                // it to true by adding it to web.config or user.config
                // <add key="CheckAllPasswordFormatsOnAuthFailure" value="true" />

                // Its purpose if true is to rescue a site
                // from a failed password format conversion. Consider what might happen if changing password formats does not
                // complete on all users. We queue it onto a background thread but if there are a very large number of rows
                // it is possible that the app may be recycled before it completes if someone touches web.config for example
                // or if memory limits on the app pool are reached, it could leave the database in a state where some users
                // are in the new password format and some in the old format and therefore cannot login
                // so this is a safety valve that can be enabled to fallback and check other formats and if
                // the user can be validated with another format then update him to the current format

                bool isValidByAlternateFormat = false;

                switch (PasswordFormat)
                {
                    case MembershipPasswordFormat.Clear:

                        isValidByAlternateFormat = EncryptedPasswordIsValid(siteSettings, siteUser, providedPassword);

                        if(!isValidByAlternateFormat)
                        {
                            isValidByAlternateFormat = HashedSha512PasswordIsValid(siteSettings, siteUser, providedPassword);

                            if((!isValidByAlternateFormat)&&(WebConfigSettings.CheckMD5PasswordHashAsFallback))
                            {
                                isValidByAlternateFormat = HashedMd5PasswordIsValid(siteSettings, siteUser, providedPassword);
                            }
                        }

                        if (isValidByAlternateFormat)
                        {
                            //current format is clear but user validated with another format so we need to update him to clear
                            siteUser.PasswordSalt = string.Empty;
                            siteUser.Password = providedPassword;
                            siteUser.Save();
                            isValid = true;
                        }

                        break;

                    case MembershipPasswordFormat.Encrypted:

                        isValidByAlternateFormat = ClearTextPasswordIsValid(siteSettings, siteUser, providedPassword);

                        if (!isValidByAlternateFormat)
                        {
                            isValidByAlternateFormat = HashedSha512PasswordIsValid(siteSettings, siteUser, providedPassword);

                            if ((!isValidByAlternateFormat) && (WebConfigSettings.CheckMD5PasswordHashAsFallback))
                            {
                                isValidByAlternateFormat = HashedMd5PasswordIsValid(siteSettings, siteUser, providedPassword);
                            }
                        }

                        if (isValidByAlternateFormat)
                        {
                            //current format is encrypted but user was validated with another format so we need to encrypt his password
                            siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                            siteUser.Password = EncodePassword(siteUser.PasswordSalt + providedPassword, MembershipPasswordFormat.Encrypted);
                            siteUser.Save();
                            isValid = true;
                        }

                        break;

                    case MembershipPasswordFormat.Hashed:

                        isValidByAlternateFormat = ClearTextPasswordIsValid(siteSettings, siteUser, providedPassword);

                        if (!isValidByAlternateFormat)
                        {
                            isValidByAlternateFormat = EncryptedPasswordIsValid(siteSettings, siteUser, providedPassword);

                            if ((!isValidByAlternateFormat) && (WebConfigSettings.CheckMD5PasswordHashAsFallback))
                            {
                                isValidByAlternateFormat = HashedMd5PasswordIsValid(siteSettings, siteUser, providedPassword);
                            }
                        }

                        if (isValidByAlternateFormat)
                        {
                            //current format is hashed but user was validated with another format so we need to hash his password
                            siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                            siteUser.Password = EncodePassword(siteUser.PasswordSalt + providedPassword, MembershipPasswordFormat.Hashed);
                            siteUser.Save();
                            isValid = true;
                        }

                        break;
                }

            }

            return isValid;
        }
コード例 #14
0
ファイル: SiteUser.cs プロジェクト: joedavis01/mojoportal
        public static string LoginLDAP(SiteSettings siteSettings, string loginId, string password, out SiteUser userCreatedForLdap)
        {
            userCreatedForLdap = null;
            int siteId = siteSettings.SiteId;
            if (UseRelatedSiteMode) { siteId = RelatedSiteID; }

            // if using ldap we don't login by email
            LdapUser user = LdapHelper.LdapLogin(siteSettings.SiteLdapSettings, loginId, password);
            if (user != null)
            {
                bool existsInDB = LoginExistsInDB(siteId, loginId);

                if (existsInDB)
                {
                    return user.CommonName;
                }
                else
                {
                    if (siteSettings.AutoCreateLdapUserOnFirstLogin)
                    {
                        userCreatedForLdap = new SiteUser(siteSettings);
                        if ((user.FirstName.Length > 0) && (user.LastName.Length > 0))
                        {
                            userCreatedForLdap.name = user.FirstName + " " + user.LastName;
                        }
                        else
                        {
                            userCreatedForLdap.name = user.CommonName;
                        }

                        userCreatedForLdap.LoginName = loginId;
                        userCreatedForLdap.email = user.Email;
                        // This password would be used during pre-LDAP fallback authentication, or if the site
                        // was changed back from LDAP to standard db authentication, so we need to populate
                        // it with something strong and unguessable.
                        userCreatedForLdap.Password = CreateRandomPassword(12, string.Empty);
                        userCreatedForLdap.Save();
                        //NewsletterHelper.ClaimExistingSubscriptions(u);
                        return user.CommonName;
                    }
                    else
                    {
                        return String.Empty;
                    }
                }
            }
            else
            {
                return String.Empty;
            }
        }
コード例 #15
0
        void btnSetUserFromGreyBox_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (hdnUserID.Value.Length == 0) { return; }
            try
            {
                int userId = Convert.ToInt32(hdnUserID.Value);
                SiteUser user = new SiteUser(siteSettings, userId);

                Role.AddUser(roleID, userId, role.RoleGuid, user.UserGuid);
                user.RolesChanged = true;
                user.Save();

                WebUtils.SetupRedirect(this, Request.RawUrl);

            }
            catch (FormatException) { }
        }
コード例 #16
0
ファイル: UserRoles.ascx.cs プロジェクト: saiesh86/TravelBlog
        private void AddRole_Click(Object sender, EventArgs e)
        {
            if ((userId > -1)&&(siteSettings != null))
            {
                SiteUser user = new SiteUser(siteSettings, userId);
                int roleID = int.Parse(allRoles.SelectedItem.Value, CultureInfo.InvariantCulture);
                Role role = new Role(roleID);
                Role.AddUser(roleID, userId, role.RoleGuid, user.UserGuid);
                user.RolesChanged = true;
                user.Save();

                BindRoles();

                upRoles.Update();

            }

            //WebUtils.SetupRedirect(this, Request.RawUrl);
        }
コード例 #17
0
        void btnApprove_Click(object sender, EventArgs e)
        {
            if (this.userID > -1)
            {
                SiteUser user = new SiteUser(siteSettings, this.userID);
                user.ApprovedForLogin = true;
                user.Save();

                //send user notification of approval
                if (WebConfigSettings.NotifyUsersOnAccountApproval)
                {
                    CultureInfo defaultCulture = SiteUtils.GetDefaultUICulture();
                    string signInLink = SiteUtils.GetNavigationSiteRoot() + "/Secure/Login.aspx";
                    SmtpSettings smtpSettings = SiteUtils.GetSmtpSettings();

                    //EmailMessageTask messageTask = new EmailMessageTask(smtpSettings);
                    //messageTask.EmailFrom = siteSettings.DefaultEmailFromAddress;
                    //messageTask.EmailFromAlias = siteSettings.DefaultFromEmailAlias;
                    //messageTask.EmailTo = user.Email;

                    string subjectFormat = ResourceHelper.GetResourceString("Resource", "AccountApprovedSubjectformat", defaultCulture, true);
                    //messageTask.Subject = string.Format(defaultCulture, subjectFormat, siteSettings.SiteName);

                    string textBodyTemplate = ResourceHelper.GetMessageTemplate(defaultCulture, "AccountApprovedMessage.config");
                    //messageTask.TextBody = string.Format(
                    //    defaultCulture,
                    //    textBodyTemplate,
                    //    siteSettings.SiteName,
                    //    signInLink
                    //    );

                    //messageTask.SiteGuid = siteSettings.SiteGuid;
                    //messageTask.QueueTask();
                    //WebTaskManager.StartOrResumeTasks();

                    Email.Send(
                        smtpSettings,
                        siteSettings.DefaultEmailFromAddress,
                        siteSettings.DefaultFromEmailAlias,
                        string.Empty,
                        user.Email,
                        string.Empty,
                        string.Empty,
                        string.Format(defaultCulture, subjectFormat, siteSettings.SiteName),
                        string.Format(defaultCulture, textBodyTemplate, siteSettings.SiteName, signInLink),
                        false,
                        Email.PriorityNormal);

                }

            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
            return;
        }
コード例 #18
0
        private void DoNewUserLogic(OpenIdEventArgs e)
        {
            if (e == null) { return; }

            ClaimsResponse claim = e.Response.GetExtension<ClaimsResponse>();
            if (claim == null) { return; }

            if (IsValidForUserCreation(e, claim))
            {
                if (SiteUser.EmailExistsInDB(siteSettings.SiteId, claim.Email))
                {
                    // show message that user should login and associate
                    // their open id account on their profile page.
                    lblError.Text = Resource.OpenIDRegisterUserEmailExistsMessage;
                    return;
                }
                else
                {
                    // create user automagically since we have all
                    // the needed data
                    SiteUser newUser = new SiteUser(siteSettings);
                    newUser.Email = claim.Email;
                    newUser.Name = claim.FullName;
                    string loginName = newUser.Name.Replace(" ", ".").ToLower();
                    if (loginName.Length > 50) loginName = loginName.Substring(0, 50);

                    if (SiteUser.LoginExistsInDB(
                        siteSettings.SiteId, loginName))
                    {
                        loginName = e.ClaimedIdentifier.ToString().Replace("http://", string.Empty).Replace("https://", string.Empty).Replace("/", string.Empty);
                        if (loginName.Length > 50) loginName = loginName.Substring(0, 50);

                        int i = 1;
                        while (SiteUser.LoginExistsInDB(
                            siteSettings.SiteId, loginName))
                        {
                            loginName += i.ToString();
                            if (loginName.Length > 50) loginName = loginName.Remove(40, 1);
                            i++;

                        }

                    }

                    newUser.LoginName = loginName;
                    newUser.Password = SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars);
                    newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
                    newUser.PasswordAnswer = Resource.ManageUsersDefaultSecurityAnswer;
                    newUser.OpenIdUri = e.ClaimedIdentifier.ToString();
                    newUser.Save();
                    if (siteSettings.UseSecureRegistration)
                    {
                        newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
                    }

                    // track user ip address
                    UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());
                    userLocation.SiteGuid = siteSettings.SiteGuid;
                    userLocation.Hostname = Page.Request.UserHostName;
                    userLocation.Save();

                    if (
                        (siteSettings.UseSecureRegistration)
                        && (newUser.RegisterConfirmGuid != Guid.Empty)
                        )
                    {
                        Notification.SendRegistrationConfirmationLink(
                            SiteUtils.GetSmtpSettings(),
                            ResourceHelper.GetMessageTemplate("RegisterConfirmEmailMessage.config"),
                            siteSettings.DefaultEmailFromAddress,
                            siteSettings.DefaultFromEmailAlias,
                            newUser.Email,
                            siteSettings.SiteName,
                            WebUtils.GetSiteRoot() + "/ConfirmRegistration.aspx?ticket=" +
                            newUser.RegisterConfirmGuid.ToString());

                        lblError.Text = Resource.LoginUnconfirmedEmailMessage;
                        log.Info("Automatically created User " + newUser.Name + " on login from open id. Tried to login but email address is not confirmed.");

                        return;
                    }

                    if (siteSettings.UseEmailForLogin)
                    {
                        FormsAuthentication.SetAuthCookie(
                            newUser.Email, true);
                    }
                    else
                    {
                        FormsAuthentication.SetAuthCookie(
                            newUser.LoginName, true);
                    }

                    if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites)
                    {
                        string cookieName = "siteguid" + siteSettings.SiteGuid;
                        CookieHelper.SetCookie(cookieName, newUser.UserGuid.ToString(), true);
                    }

                    newUser.UpdateLastLoginTime();

                    string redirectUrl = GetRedirectPath();
                    CookieHelper.ExpireCookie(returnUrlCookieName);
                    WebUtils.SetupRedirect(this, redirectUrl);
                    return;

                }

            }
            else
            {
                // user not found
                // required fields not available from open id
                // redirect to register page?
                // Or show message with Link to
                // register page
                string registerLinkHref = siteRoot
                    + "/Secure/RegisterWithOpenID.aspx";

                litNotRegisteredYetMessage.Text
                    = string.Format(
                    Resource.OpenIDMustRegisterBeforeLoginMesage,
                    registerLinkHref);

            }
        }
コード例 #19
0
        private void CreateUser()
        {
            if (SiteUser.EmailExistsInDB(siteSettings.SiteId, txtEmail.Text))
            {
                lblErrorMessage.Text = Resource.DuplicateEmailMessage;
                return ;
            }

            if (SiteUser.LoginExistsInDB(siteSettings.SiteId, txtLoginName.Text))
            {
                lblErrorMessage.Text = Resource.DuplicateUserNameMessage;
                return;
            }

            SiteUser user = new SiteUser(siteSettings);
            user.Name = txtName.Text;
            user.LoginName = txtLoginName.Text;
            user.Email = txtEmail.Text;
            user.TimeZoneId = siteSettings.TimeZoneId;

            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;
            user.Password = mojoMembership.EncodePassword(siteSettings, user, txtPassword.Text);
            user.MustChangePwd = chkRequirePasswordChange.Checked;

            if(user.Save())
            {
                user.PasswordQuestion = this.txtPasswordQuestion.Text;
                user.PasswordAnswer = this.txtPasswordAnswer.Text;
                user.Save();

                mojoProfileConfiguration profileConfig = mojoProfileConfiguration.GetConfig();
                // set default values
                foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
                {
                    if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeZoneIdKey) { continue; }

                    mojoProfilePropertyDefinition.SavePropertyDefault(user, propertyDefinition);
                }

                CacheHelper.ClearMembershipStatisticsCache();

                if (WebConfigSettings.NewsletterAutoSubscribeUsersCreatedByAdmin)
                {
                    DoSubscribe(user);
                }

                UserRegisteredEventArgs u = new UserRegisteredEventArgs(user);
                OnUserRegistered(u);

                WebUtils.SetupRedirect(this, SiteRoot
                    + "/Admin/ManageUsers.aspx?userId=" + user.UserId.ToInvariantString()
                    + "&username="******"&pageid=" + pageID.ToInvariantString());
                return;

            }
        }
コード例 #20
0
ファイル: mojoSetup.cs プロジェクト: joedavis01/mojoportal
        public static void CreateRequiredRolesAndAdminUser(SiteSettings site)
        {
            Role adminRole = new Role();
            adminRole.RoleName = "Admins";
            adminRole.SiteId = site.SiteId;
            adminRole.SiteGuid = site.SiteGuid;
            adminRole.Save();
            adminRole.RoleName = "Administrators";
            adminRole.Save();

            Role roleAdminRole = new Role();
            roleAdminRole.RoleName = "Role Admins";
            roleAdminRole.SiteId = site.SiteId;
            roleAdminRole.SiteGuid = site.SiteGuid;
            roleAdminRole.Save();
            roleAdminRole.RoleName = "Role Administrators";
            roleAdminRole.Save();

            Role contentAdminRole = new Role();
            contentAdminRole.RoleName = "Content Administrators";
            contentAdminRole.SiteId = site.SiteId;
            contentAdminRole.SiteGuid = site.SiteGuid;
            contentAdminRole.Save();

            Role authenticatedUserRole = new Role();
            authenticatedUserRole.RoleName = "Authenticated Users";
            authenticatedUserRole.SiteId = site.SiteId;
            authenticatedUserRole.SiteGuid = site.SiteGuid;
            authenticatedUserRole.Save();

            Role contentPublisherRole = new Role();
            contentPublisherRole.RoleName = "Content Publishers";
            contentPublisherRole.SiteId = site.SiteId;
            contentPublisherRole.SiteGuid = site.SiteGuid;
            contentPublisherRole.Save();

            Role contentAuthorRole = new Role();
            contentAuthorRole.RoleName = "Content Authors";
            contentAuthorRole.SiteId = site.SiteId;
            contentAuthorRole.SiteGuid = site.SiteGuid;
            contentAuthorRole.Save();

            Role newsletterAdminRole = new Role();
            newsletterAdminRole.RoleName = "Newsletter Administrators";
            newsletterAdminRole.SiteId = site.SiteId;
            newsletterAdminRole.SiteGuid = site.SiteGuid;
            newsletterAdminRole.Save();

            // if using related sites mode there is a problem if we already have user [email protected]
            // and we create another one in the child site with the same email and login so we need to make it different
            // we could just skip creating this user since in related sites mode all users come from the first site
            // but then if the config were changed to not related sites mode there would be no admin user
            // so in related sites mode we create one only as a backup in case settings are changed later
            int countOfSites = SiteSettings.SiteCount();
            string siteDifferentiator = string.Empty;
            if (
                (countOfSites >= 1)
                && (WebConfigSettings.UseRelatedSiteMode)
                )
            {
                if (site.SiteId > 1)
                {
                    siteDifferentiator = site.SiteId.ToInvariantString();
                }
            }

            mojoMembershipProvider membership = Membership.Provider as mojoMembershipProvider;
            bool overridRelatedSiteMode = true;
            SiteUser adminUser = new SiteUser(site, overridRelatedSiteMode);
            adminUser.Email = "admin" + siteDifferentiator + "@admin.com";
            adminUser.Name = "Admin";
            adminUser.LoginName = "admin" + siteDifferentiator;
            adminUser.Password = "******";

            if (membership != null)
            {
                adminUser.Password = membership.EncodePassword(site, adminUser, "admin");
            }

            adminUser.PasswordQuestion = "What is your user name?";
            adminUser.PasswordAnswer = "admin";
            adminUser.Save();

            Role.AddUser(adminRole.RoleId, adminUser.UserId, adminRole.RoleGuid, adminUser.UserGuid);
        }
コード例 #21
0
        public override string ResetPassword(string userName, string passwordAnswer)
        {
            /*
            Takes, as input, a user name and a password answer and replaces the user's current password
             * with a new, random password. ResetPassword then returns the new password. A
             * convenient mechanism for generating a random password is the
             * Membership.GeneratePassword method. If the user name is not valid, ResetPassword
             * throws a ProviderException. ResetPassword also checks the value of the
             * RequiresQuestionAndAnswer property before resetting a password. If
             * RequiresQuestionAndAnswer is true, ResetPassword compares the supplied password
             * answer to the stored password answer and throws a MembershipPasswordException if
             * the two don't match. Before resetting a password, ResetPassword verifies that
             * EnablePasswordReset is true. If EnablePasswordReset is false, ResetPassword throws
             * a NotSupportedException. If the user whose password is being changed is currently
             * locked out, ResetPassword throws a MembershipPasswordException. Before resetting a
             * password, ResetPassword calls the provider's virtual OnValidatingPassword method to
             * validate the new password. It then resets the password or cancels the action based on
             * the outcome of the call. If the new password is invalid, ResetPassword throws a
             * ProviderException. Following a successful password reset, ResetPassword updates the
             * user's LastPasswordChangedDate.
            */
            SiteSettings siteSettings = GetSiteSettings();

            if (!siteSettings.AllowPasswordReset)
            {
                throw new Exception("The method or operation is not implemented.");
            }

            String newPassword = null;

            if ((userName != null) && (siteSettings != null))
            {
                SiteUser siteUser = new SiteUser(siteSettings, userName);
                if (siteUser.UserId > -1)
                {

                    if (siteUser.IsLockedOut)
                    {
                        throw new MembershipPasswordException(
                            ResourceHelper.GetMessageTemplate("UserAccountLockedMessage.config"));
                    }

                    bool okToResetPassword = false;
                    if (siteSettings.RequiresQuestionAndAnswer)
                    {
                        if ((passwordAnswer != null) && (passwordAnswer == siteUser.PasswordAnswer))
                        {
                            okToResetPassword = true;
                        }
                        else
                        {
                            // if wrong answer or user is locked out
                            throw new MembershipPasswordException(ResourceHelper.GetMessageTemplate("PasswordWrongAnswerToQuestionMessage.config"));
                        }

                    }
                    else
                    {
                        okToResetPassword = true;
                    }

                    if (okToResetPassword)
                    {

                        newPassword = SiteUser.CreateRandomPassword(siteSettings.MinRequiredPasswordLength + 2, WebConfigSettings.PasswordGeneratorChars);

                        switch (PasswordFormat)
                        {
                            case MembershipPasswordFormat.Clear:
                                siteUser.Password = newPassword;
                                break;
                            default:
                                siteUser.PasswordSalt = SiteUser.CreateRandomPassword(128, WebConfigSettings.PasswordGeneratorChars);
                                siteUser.Password = EncodePassword(siteUser.PasswordSalt + newPassword, PasswordFormat);
                                break;
                        }

                        siteUser.MustChangePwd = siteSettings.RequirePasswordChangeOnResetRecover;
                        siteUser.PasswordFormat = siteSettings.PasswordFormat;
                        siteUser.Save();

                        siteUser.UpdateLastPasswordChangeTime();

                    }
                }
                else
                {
                    throw new ProviderException(ResourceHelper.GetMessageTemplate("UserNotFoundMessage.config"));

                }

            }

            return newPassword;
        }