/// <summary>
    /// Returns where condition for specialized role conditions or <c>null</c> in case no roles were selected.
    /// </summary>
    /// <param name="selector">Condition to use (ANY/ALL)</param>
    /// <param name="selectedRoles">Values separated with semicolon</param>
    /// <remarks>
    /// <c>null</c> is returned in order to allow calling <see cref="WhereConditionBase{TParent}.WhereNot"/> on method's result
    /// (empty <see cref="WhereCondition"/> would cause appending "NOT" to SQL query).
    /// </remarks>
    private WhereCondition GetRolesSelectorCondition(string selector, string selectedRoles)
    {
        if (String.IsNullOrEmpty(selectedRoles))
        {
            return(null);
        }

        string[] roles = selectedRoles.Split(';');

        var globalRolesCondition = GetGlobalRolesCondition(roles);

        var roleCondition = GetSiteRolesCondition(roles).Or(globalRolesCondition);

        var query = UserRoleInfoProvider.GetUserRoles()
                    .Column("UserID")
                    .WhereIn("RoleID", RoleInfoProvider.GetRoles()
                             .Column("RoleID")
                             .Where(roleCondition))
                    .Where(new WhereCondition()
                           .WhereNull("ValidTo")
                           .Or()
                           .WhereGreaterThan("ValidTo", DateTime.Now))
                    .GroupBy("UserID");

        if (selector.Equals(UniGrid.ALL, StringComparison.OrdinalIgnoreCase))
        {
            query.Having(condition => condition.WhereEquals(new CountColumn("RoleID"), roles.Length));
        }

        var userIdColumn = SessionInsteadOfUser ? "SessionUserID" : "UserID";

        return(new WhereCondition().WhereIn(userIdColumn, query));
    }
Exemple #2
0
        public async Task AddToRoleAsync_UserIsNotInRole_UserRoleInfoCreated()
        {
            var user = new User(mMembershipFakeFactory.UserEnabledWithEmail);
            await mUserStore.AddToRoleAsync(user, MembershipFakeFactory.ROLE_MEMBER);

            CMSAssert.All(
                () => Assert.AreEqual(1, UserRoleInfoProvider.GetUserRoles().Count),
                () => Assert.IsNotNull(UserRoleInfoProvider.GetUserRoleInfo(user.Id, mMembershipFakeFactory.MemberRole.RoleID)));
        }
Exemple #3
0
    private string GetRoleUsers()
    {
        var data = UserRoleInfoProvider.GetUserRoles().Where("RoleID = " + RoleID).Columns("UserID");

        if (data.Any())
        {
            return(TextHelper.Join(";", DataHelper.GetStringValues(data.Tables[0], "UserID")));
        }

        return(String.Empty);
    }
    private string GetRoleUsers()
    {
        DataSet ds = UserRoleInfoProvider.GetUserRoles("RoleID = " + RoleID, null, 0, "UserID");

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            return(TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "UserID")));
        }

        return(String.Empty);
    }
    /// <summary>
    /// Gets roles for current user.
    /// </summary>
    private void LoadCurrentRoles()
    {
        if (CurrentMember != null)
        {
            // Get user roles
            var data = UserRoleInfoProvider.GetUserRoles().Where("UserID = " + CurrentMember.MemberUserID + "AND RoleID IN (SELECT RoleID FROM CMS_Role WHERE RoleGroupID = " + CurrentMember.MemberGroupID + ")").Columns("RoleID");
            if (data.Any())
            {
                currentValues = TextHelper.Join(";", DataHelper.GetStringValues(data.Tables[0], "RoleID"));
            }

            currentRolesLoaded = true;
        }
    }
Exemple #6
0
    /// <summary>
    /// Gets roles for current user.
    /// </summary>
    private void LoadCurrentRoles()
    {
        if (this.gmi != null)
        {
            // Get user roles
            DataSet ds = UserRoleInfoProvider.GetUserRoles("UserID = " + gmi.MemberUserID + "AND RoleID IN (SELECT RoleID FROM CMS_Role WHERE RoleGroupID = " + gmi.MemberGroupID + ")", null, 0, "RoleID");
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "RoleID"));
            }

            currentRolesLoaded = true;
        }
    }
Exemple #7
0
        public async Task RemoveFromRoleAsync_UserIsInRole_UserRoleInfoDeletedUserAndRoleExists()
        {
            var role = mMembershipFakeFactory.AdminRole;
            var user = new User(mMembershipFakeFactory.UserEnabledWithEmail);

            UserRoleInfoProvider.AddUserToRole(mMembershipFakeFactory.UserEnabledWithEmail, mMembershipFakeFactory.AdminRole);

            await mUserStore.RemoveFromRoleAsync(user, role.RoleName);

            CMSAssert.All(
                () => Assert.AreEqual(0, UserRoleInfoProvider.GetUserRoles().Count),
                () => Assert.IsNull(UserRoleInfoProvider.GetUserRoleInfo(user.Id, role.RoleID)),
                () => Assert.IsNotNull(RoleInfoProvider.GetRoleInfo(role.RoleID)),
                () => Assert.IsNotNull(UserInfoProvider.GetUserInfo(user.Id)));
        }
Exemple #8
0
 /// <summary>
 /// deletes all the roles assigned to particular user
 /// </summary>
 /// <param name="userID"></param>
 private void DeleteUserRoles(int userID)
 {
     try
     {
         var userRoleData = UserRoleInfoProvider.GetUserRoles()
                            .WhereEquals("UserID", userID)
                            .ToList();
         if (!DataHelper.DataSourceIsEmpty(userRoleData))
         {
             userRoleData.ForEach(x =>
             {
                 UserRoleInfoProvider.DeleteUserRoleInfo(x);
             });
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("UsersList", "DeleteUserRoles", ex);
     }
 }
Exemple #9
0
        /// <summary>
        /// Removes <see cref="User"/> from <see cref="Role"/>.
        /// </summary>
        /// <param name="user">User entity.</param>
        /// <param name="roleName">Role name.</param>
        public Task RemoveFromRoleAsync(User user, string roleName)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (String.IsNullOrWhiteSpace(roleName))
            {
                throw new ArgumentException("Argument cannot be null or empty", nameof(roleName));
            }

            var userRole = UserRoleInfoProvider.GetUserRoles()
                           .WhereEquals("UserID", user.Id)
                           .WhereEquals("RoleID", GetRoleByRoleName(roleName, SiteID).RoleID)
                           .FirstObject;

            UserRoleInfoProvider.DeleteUserRoleInfo(userRole);

            return(Task.FromResult(0));
        }
    private string GetUniGridWhereCondition()
    {
        // Global administrators can see all forms.
        if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
        {
            return("FormSiteID = " + SiteContext.CurrentSiteID);
        }

        var bizFormsAvailableForUser = BizFormInfoProvider.GetBizForms()
                                       .Column("CMS_Form.FormID")
                                       .OnSite(SiteContext.CurrentSiteID)
                                       .Distinct()
                                       .Source(s => s.LeftJoin <BizFormRoleInfo>("FormID", "FormID"))
                                       .Where(new WhereCondition()
                                              .WhereIn("RoleID", UserRoleInfoProvider.GetUserRoles().Column("RoleID").WhereEquals("UserID", currentUser.UserID))
                                              .Or()
                                              .WhereNull("FormAccess")
                                              .Or()
                                              .WhereEquals("FormAccess", (int)FormAccessEnum.AllBizFormUsers));

        return(new WhereCondition().WhereIn("CMS_Form.FormID", bizFormsAvailableForUser).ToString(true));
    }
Exemple #11
0
    /// <summary>
    /// Page_load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check permissions and UI elements
        var user = MembershipContext.AuthenticatedUser;

        if (user != null)
        {
            if (!user.IsAuthorizedPerUIElement("CMS.Users", "CmsDesk.Roles"))
            {
                RedirectToUIElementAccessDenied("CMS.Users", "CmsDesk.Roles");
            }

            if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Roles", "Read"))
            {
                RedirectToAccessDenied("CMS.Roles", "Read");
            }
        }

        ScriptHelper.RegisterJQuery(Page);

        // Get user id and site Id from query
        mUserId = QueryHelper.GetInteger("userid", 0);

        // Show content placeholder where site selector can be shown
        CurrentMaster.DisplaySiteSelectorPanel = true;

        if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin))
        {
            plcSites.Visible = false;
            CurrentMaster.DisplaySiteSelectorPanel = false;
        }

        if (mUserId > 0)
        {
            // Check that only global administrator can edit global administrator's accounts
            mUserInfo = UserInfoProvider.GetUserInfo(mUserId);
            CheckUserAvaibleOnSite(mUserInfo);
            EditedObject = mUserInfo;

            if (!CheckGlobalAdminEdit(mUserInfo))
            {
                plcTable.Visible = false;
                ShowError(GetString("Administration-User_List.ErrorGlobalAdmin"));
                return;
            }

            // Set site selector
            siteSelector.DropDownSingleSelect.AutoPostBack = true;
            siteSelector.AllowAll   = false;
            siteSelector.AllowEmpty = false;

            // Global roles only for global admin
            if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin))
            {
                siteSelector.AllowGlobal = true;
            }

            // Only sites assigned to user
            siteSelector.UserId           = mUserId;
            siteSelector.OnlyRunningSites = false;
            siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged;

            if (!RequestHelper.IsPostBack())
            {
                mSiteId = SiteContext.CurrentSiteID;

                // If user is member of current site
                if (UserSiteInfoProvider.GetUserSiteInfo(mUserId, mSiteId) != null)
                {
                    // Force uniselector to preselect current site
                    siteSelector.Value = mSiteId;
                }

                // Force to load data
                siteSelector.Reload(true);
            }

            // Get truly selected item
            mSiteId = ValidationHelper.GetInteger(siteSelector.Value, 0);
        }

        usRoles.OnSelectionChanged += usRoles_OnSelectionChanged;
        string siteIDWhere = (mSiteId <= 0) ? " SiteID IS NULL " : " SiteID =" + mSiteId;

        usRoles.WhereCondition = siteIDWhere + " AND RoleGroupID IS NULL";

        usRoles.SelectItemPageUrl     = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx";
        usRoles.ListingWhereCondition = siteIDWhere + " AND RoleGroupID IS NULL AND UserID=" + mUserId;
        usRoles.ReturnColumnName      = "RoleID";
        usRoles.DynamicColumnName     = false;
        usRoles.GridName               = "User_Role_List.xml";
        usRoles.AdditionalColumns      = "ValidTo";
        usRoles.OnAdditionalDataBound += usMemberships_OnAdditionalDataBound;
        usRoles.DialogWindowHeight     = 760;

        // Exclude generic roles
        string    genericWhere = String.Empty;
        ArrayList genericRoles = RoleInfoProvider.GetGenericRoles();

        if (genericRoles.Count != 0)
        {
            foreach (string role in genericRoles)
            {
                genericWhere += "'" + SqlHelper.EscapeQuotes(role) + "',";
            }

            genericWhere            = genericWhere.TrimEnd(',');
            usRoles.WhereCondition += " AND ( RoleName NOT IN (" + genericWhere + ") )";
        }

        // Get the active roles for this site
        var roleIds = new IDQuery <RoleInfo>().Where(siteIDWhere).Column("RoleID");
        var data    = UserRoleInfoProvider.GetUserRoles().WhereEquals("UserID", mUserId).And().WhereIn("RoleID", roleIds).Columns("RoleID").TypedResult;

        if (data.Any())
        {
            mCurrentValues = TextHelper.Join(";", data.Select(i => i.RoleID));
        }

        // If not postback or site selection changed
        if (!RequestHelper.IsPostBack() || (mSiteId != Convert.ToInt32(ViewState["rolesOldSiteId"])))
        {
            // Set values
            usRoles.Value = mCurrentValues;
        }

        // Store selected site id
        ViewState["rolesOldSiteId"] = mSiteId;

        string script = "function setNewDateTime(date) {$cmsj('#" + hdnDate.ClientID + "').val(date);}";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "key", ScriptHelper.GetScript(script));

        string eventTarget   = Request[postEventSourceID];
        string eventArgument = Request[postEventArgumentID];

        if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID)
        {
            if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Users", "ManageUserRoles"))
            {
                RedirectToAccessDenied("CMS.Users", "Manage user roles");
            }

            int id = ValidationHelper.GetInteger(hdnDate.Value, 0);
            if (id != 0)
            {
                DateTime     dt  = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME);
                UserRoleInfo uri = UserRoleInfoProvider.GetUserRoleInfo(mUserId, id);
                if (uri != null)
                {
                    uri.ValidTo = dt;
                    UserRoleInfoProvider.SetUserRoleInfo(uri);

                    // Invalidate user
                    UserInfoProvider.InvalidateUser(mUserId);

                    ShowChangesSaved();
                }
            }
        }
    }
    protected void SetupControls()
    {
        // If current control context is widget or livesite hide site selector
        if (ControlsHelper.CheckControlContext(this, ControlContext.WIDGET_PROPERTIES) || ControlsHelper.CheckControlContext(this, ControlContext.LIVE_SITE))
        {
            ShowSiteFilter = false;
        }

        // Set prefix if not set
        if (ResourcePrefix == String.Empty)
        {
            // Set resource prefix based on mode
            if ((SelectionMode == SelectionModeEnum.Multiple) || (SelectionMode == SelectionModeEnum.MultipleButton) || (SelectionMode == SelectionModeEnum.MultipleTextBox))
            {
                usUsers.ResourcePrefix = "selectusers";
            }
        }

        // Add sites filter
        if (ShowSiteFilter)
        {
            usUsers.FilterControl = "~/CMSFormControls/Filters/SiteFilter.ascx";
            usUsers.SetValue("DefaultFilterValue", (SiteID > 0) ? SiteID : SiteContext.CurrentSiteID);
            usUsers.SetValue("FilterMode", "user");
        }

        // Generate WhereCondtion based on SelectUser's properties
        var usersWhereCondition = new WhereCondition();
        var userTypeInfo        = ObjectTypeManager.GetTypeInfo(UserInfo.OBJECT_TYPE);

        // Hide hidden users
        if (HideHiddenUsers)
        {
            var apparentUsersCondition = new WhereCondition().WhereEqualsOrNull("UserIsHidden", 0);
            usersWhereCondition.And(apparentUsersCondition);
        }

        // Hide disabled users
        if (HideDisabledUsers)
        {
            var enabledUsersCondition = new WhereCondition(UserInfoProvider.USER_ENABLED_WHERE_CONDITION);
            usersWhereCondition.And(enabledUsersCondition);
        }

        // Hide non-approved users
        if (HideNonApprovedUsers)
        {
            var approvedUserIDs = UserSettingsInfoProvider
                                  .GetUserSettings()
                                  .WhereEqualsOrNull("UserWaitingForApproval", 0)
                                  .Column("UserSettingsUserID");

            var approvedUsersCondition = new WhereCondition().WhereIn(userTypeInfo.IDColumn, approvedUserIDs);
            usersWhereCondition.And(approvedUsersCondition);
        }

        // Select group users
        if (GroupID > 0)
        {
            var groupUserIDs = new ObjectQuery(PredefinedObjectType.GROUPMEMBER)
                               .WhereEquals("MemberGroupID", GroupID)
                               .Column("MemberUserID");

            // Hide non-approved group users
            if (HideNonApprovedUsers)
            {
                groupUserIDs.WhereNull("MemberRejectedWhen");
            }

            var usersInGroupCondition = new WhereCondition().WhereIn(userTypeInfo.IDColumn, groupUserIDs);
            usersWhereCondition.And(usersInGroupCondition);
        }

        // Select users in role
        if (RoleID > 0)
        {
            var usersInRoleIDs = UserRoleInfoProvider
                                 .GetUserRoles()
                                 .WhereEquals("RoleID", RoleID)
                                 .Column("UserID");

            var usersInRoleCondition = new WhereCondition().WhereIn(userTypeInfo.IDColumn, usersInRoleIDs);
            usersWhereCondition.And(usersInRoleCondition);
        }

        // Select users depending on site; if filter enabled, where condition is added from filter itself
        if (!ShowSiteFilter && (SiteID >= 0) && !DisplayUsersFromAllSites)
        {
            int siteID      = (SiteID == 0) ? SiteContext.CurrentSiteID : SiteID;
            var siteUserIDs = UserSiteInfoProvider
                              .GetUserSites()
                              .WhereEquals("SiteID", siteID)
                              .Column("UserID");

            var siteUsersCondition = new WhereCondition().WhereIn(userTypeInfo.IDColumn, siteUserIDs);

            if (TreatGlobalAdminsAsSiteUsers)
            {
                siteUsersCondition.Or(GetPrivilegeLevelCondition());
            }

            usersWhereCondition.And(siteUsersCondition);
        }

        if (AlwaysShowGlobalAdministrators)
        {
            // New instance has to be created in order to produce brackets
            usersWhereCondition = new WhereCondition(usersWhereCondition).Or(GetPrivilegeLevelCondition());
        }

        // Add additional users
        if ((AdditionalUsers != null) && (AdditionalUsers.Length > 0))
        {
            var additionalUsersCondition = new WhereCondition().WhereIn(userTypeInfo.IDColumn, AdditionalUsers);

            new WhereCondition(usersWhereCondition).Or(additionalUsersCondition);
        }

        // Control where condition
        if (!String.IsNullOrEmpty(WhereCondition))
        {
            usersWhereCondition = new WhereCondition(usersWhereCondition).And(new WhereCondition(WhereCondition));
        }

        // Append generated where condition
        usUsers.WhereCondition = SqlHelper.AddWhereCondition(usUsers.WhereCondition, usersWhereCondition.ToString(expand: true));

        pnlUpdate.ShowProgress = (SelectionMode == SelectionModeEnum.Multiple);
    }
Exemple #13
0
        private static void ImportWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker worker = (BackgroundWorker)sender;

                // Save import profile
                if (ImportProfile.SaveImportProfile && !ImportProfile.UsesConsole)
                {
                    SaveFile(SaveImportProfile);
                }

                // Decide whether to import
                if (!ImportProfile.ImportNow && !ImportProfile.UsesConsole)
                {
                    return;
                }

                using (new CMSActionContext()
                {
                    LogEvents = false, ContinuousIntegrationAllowObjectSerialization = false
                })
                {
                    #region "Initialization"

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    DateTime start = DateTime.Now;

                    // Initialize CMS context
                    CMSInit();

                    if (ImportProfile.UsesConsole)
                    {
                        // Ensure object in case they are not present in import profile
                        EnsureObjects();
                    }

                    if (ImportProfile.ImportUsersOnlyFromSelectedRoles)
                    {
                        // Narrow down imported users according to imported roles
                        ImportProfile.Users.Clear();
                    }

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    // Initialize cumulative changed users and roles storages
                    var rolesChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.RolesCreated, WellKnownEventLogEventsEnum.RolesUpdated, WellKnownEventLogEventsEnum.RolesDeleted);
                    var usersChanged = new CumulatedChanges(WellKnownEventLogEventsEnum.UsersCreated, WellKnownEventLogEventsEnum.UsersUpdated, WellKnownEventLogEventsEnum.UsersDeleted);

                    #endregion

                    // Delete non-existing objects (this also prevents conflicting code names)
                    if (ImportProfile.DeleteNotExistingObjects)
                    {
                        DeleteNonExistingObjects(usersChanged, rolesChanged);
                    }

                    #region "Role import"

                    foreach (var siteInfo in ImportProfile
                             .Sites
                             .Select(site => SiteInfoProvider.GetSiteInfo(site.Key))
                             .Where(info => info != null))
                    {
                        foreach (Guid groupGuid in ImportProfile.Groups)
                        {
                            // Import canceled
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // Try to get group
                            IPrincipalObject group = PrincipalProvider.GetPrincipalObject(groupGuid);

                            // If group is still null
                            if (group == null)
                            {
                                MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject"));
                                warnings++;
                                // If deleting of not existing objects is enabled
                                if (ImportProfile.DeleteNotExistingObjects)
                                {
                                    DeleteRole(siteInfo, groupGuid);
                                }
                            }
                            else
                            {
                                // Get role description
                                string roleDescription = String.Empty;
                                if (ImportProfile.ImportRoleDescription && (group.Description != null))
                                {
                                    roleDescription = group.Description;
                                }

                                // Get correct role name format
                                string roleCodeName = group.GetCMSCodeName(true);

                                // Get role display name
                                string roleDisplayName = group.GetCMSDisplayName();

                                // Get safe role name
                                roleCodeName = ValidationHelper.GetSafeRoleName(roleCodeName, siteInfo.SiteName);

                                if (!String.IsNullOrEmpty(roleCodeName))
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_ImportingRole", roleDisplayName, CMS.Helpers.ResHelper.LocalizeString(siteInfo.DisplayName)));

                                    // Import role
                                    ImportRole(roleCodeName, roleDisplayName, siteInfo.SiteID, roleDescription, groupGuid, ImportProfile.UpdateObjectData, rolesChanged);

                                    if (ImportProfile.ImportUsersOnlyFromSelectedRoles)
                                    {
                                        ImportProfile.Users.AddRange(PrincipalProvider.GetUsersOf(group).Select(u => u.Identifier));
                                    }
                                }
                                else
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyRolename", group.Identifier));
                                    warnings++;
                                }
                            }
                        }
                    }

                    // Log created and updated and removed roles to EventLog
                    rolesChanged.WriteEventsToEventLog();

                    #endregion

                    #region "User import"

                    foreach (var user in ImportProfile
                             .Users
                             .Distinct()
                             .Select(userGuid => PrincipalProvider.GetPrincipalObject(userGuid)))
                    {
                        // Import canceled
                        if (worker.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }

                        if (user == null)
                        {
                            MessageLog.LogEvent(ResHelper.GetString("Log_SkippingNonExistingObject"));
                            continue;
                        }

                        string domainName = user.GetCMSCodeName(true);

                        if (!String.IsNullOrEmpty(domainName))
                        {
                            // Get user info object
                            UserInfo userInfo = (UserInfoProvider.GetUserInfoByGUID((Guid)user.Identifier) ?? UserInfoProvider.GetUserInfo(domainName));
                            bool     newUser  = (userInfo == null);

                            // When is desired to import new users only from selected roles
                            if (newUser && ImportProfile.ImportNewUsersOnlyFromSelectedRoles)
                            {
                                // Skip users that does not belong to one of selected role
                                bool skip = ImportProfile.Groups.Cast <Guid>().All(groupGuid => !user.IsPrincipalInGroup(groupGuid));
                                if (skip)
                                {
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SkippingDoesNotBelongToSelectedRole", domainName));
                                    continue;
                                }
                            }

                            if (ImportProfile.UpdateObjectData || newUser)
                            {
                                if (userInfo == null)
                                {
                                    userInfo = new UserInfo();
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_ImportingUser", domainName));
                                }
                                else
                                {
                                    // Add message to log
                                    MessageLog.LogEvent(ResHelper.GetString("Log_UpdatingUser", domainName));
                                }

                                using (var transaction = new CMSTransactionScope())
                                {
                                    if (newUser)
                                    {
                                        userInfo.UserIsDomain = true;
                                        userInfo.UserGUID     = (Guid)user.Identifier;

                                        // Set privilege level
                                        UserPrivilegeLevelEnum privilegeLevel = ImportProfile.ConfigureAsCMSEditor ? UserPrivilegeLevelEnum.Editor : UserPrivilegeLevelEnum.None;
                                        userInfo.SiteIndependentPrivilegeLevel = privilegeLevel;
                                    }

                                    if (userInfo.UserIsDomain)
                                    {
                                        // Set user's properties
                                        userInfo.UserIsExternal = true;
                                        userInfo.UserName       = domainName;
                                        userInfo.Enabled        = ValidationHelper.GetBoolean(user.Enabled, true);

                                        // Bind properties
                                        foreach (KeyValuePair <string, string> property in ImportProfile.UserProperties)
                                        {
                                            // Get attribute
                                            object attribute = user.GetProperty(property.Value);

                                            if (attribute != null)
                                            {
                                                try
                                                {
                                                    string attrValue;

                                                    // Get string representation of the attribute
                                                    if (attribute is float || attribute is double || attribute is decimal)
                                                    {
                                                        attrValue = String.Format(CultureInfo.InvariantCulture, "{0}", attribute);
                                                    }
                                                    else if (attribute.GetType() == typeof(byte[]))
                                                    {
                                                        attrValue = PrincipalProvider.GetSID(attribute);
                                                    }
                                                    else if (attribute.GetType().BaseType == typeof(MarshalByRefObject))
                                                    {
                                                        attrValue = PrincipalProvider.GetTimeFromInterval(attribute);
                                                    }
                                                    else
                                                    {
                                                        attrValue = attribute.ToString();
                                                    }

                                                    // Set property
                                                    userInfo.SetValue(property.Key, LimitLengthForField(attrValue, property.Key));
                                                }
                                                catch
                                                {
                                                    MessageLog.LogEvent(ResHelper.GetString("Log_ErrorParsingAttr", property.Value));
                                                    warnings++;
                                                }
                                            }
                                            else
                                            {
                                                FormFieldInfo field = UserFormInfo.GetFormField(property.Key);
                                                userInfo.SetValue(property.Key, field.GetPropertyValue(FormFieldPropertyEnum.DefaultValue));
                                            }
                                        }

                                        // Create full name if empty
                                        if (String.IsNullOrEmpty(userInfo.FullName))
                                        {
                                            userInfo.FullName = user.GetCMSDisplayName();
                                        }

                                        // Store user info object and its user-settings
                                        if (userInfo.ChangedColumns().Any())
                                        {
                                            // Store created/updated user for EventLog
                                            // User name is used, because AD accounts does not have to have first and/or given name specified (e.g. Guest, …)
                                            usersChanged.Add(userInfo.UserGUID, userInfo.UserName, newUser ? ChangeActionEnum.Created : ChangeActionEnum.Updated);

                                            UserInfoProvider.SetUserInfo(userInfo);
                                        }
                                    }
                                    else
                                    {
                                        MessageLog.LogEvent(ResHelper.GetString("Log_UserIsNotDomain", userInfo.UserName));
                                        warnings++;
                                    }

                                    transaction.Commit();
                                }
                            }
                            else
                            {
                                MessageLog.LogEvent(ResHelper.GetString("Log_SkippingExistingUser", domainName));
                            }

                            // Import canceled
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // Assign user to sites and roles (for domain users only)
                            if (!userInfo.UserIsDomain)
                            {
                                continue;
                            }


                            #region "Membership (roles) synchronization"

                            if (!newUser && !ImportProfile.UpdateMemberships && !ImportProfile.UpdateMemberships)
                            {
                                // No membership synchronization will be performed
                                continue;
                            }

                            // Initialize collection to cumulate membership changes
                            var memberShipChanges = new CumulatedRolesMembership();

                            // Load all user roles from DB
                            var userRoles = new HashSet <RoleInfo>(newUser
                                ? Enumerable.Empty <RoleInfo>() // non-existing user cannot be present in a single role (in DB)
                                : RoleInfoProvider
                                                                   .GetRoles()
                                                                   .WhereIn("RoleID",
                                                                            UserRoleInfoProvider
                                                                            .GetUserRoles()
                                                                            .WhereEquals("UserID", userInfo.UserID)
                                                                            .Column("RoleID"))
                                                                   .Columns("RoleID", "RoleGUID", "RoleDisplayName", "RoleIsDomain"));

                            // Store user's roles before membership synchronization
                            memberShipChanges.SetRolesBefore(userRoles);
                            foreach (KeyValuePair <string, List <Guid> > site in ImportProfile.Sites)
                            {
                                // Get site info object
                                var siteInfo = SiteInfoProvider.GetSiteInfo(site.Key);
                                if (siteInfo != null)
                                {
                                    try
                                    {
                                        // Add user to this site
                                        UserSiteInfoProvider.AddUserToSite(userInfo, siteInfo);
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageLog.LogEvent(ResHelper.GetString("Log_GeneralWarning", ex.Message));
                                        warnings++;
                                    }

                                    // Assign user to roles already existing in CMS
                                    if (newUser || ImportProfile.UpdateMemberships)
                                    {
                                        SetMemberships(user, userInfo, siteInfo, userRoles, site);
                                    }

                                    // Remove user from roles they is member no more
                                    if (!newUser && ImportProfile.UpdateMemberships)
                                    {
                                        RemoveExcessiveMemberships(user, userInfo, userRoles);
                                    }
                                }
                                else
                                {
                                    MessageLog.LogEvent(ResHelper.GetString("Log_SiteNotExist", site.Key));
                                    warnings++;
                                }
                            }

                            // Store user's roles after membership synchronization
                            memberShipChanges.SetRolesAfter(userRoles);

                            // Log created and removed memberships to EventLog
                            memberShipChanges.WriteEventsToEventLog(userInfo.UserName);

                            #endregion
                        }
                        else
                        {
                            // Add message to log
                            MessageLog.LogEvent(ResHelper.GetString("Log_SkippingEmptyUsername", user.Identifier));
                            warnings++;
                        }
                    }

                    // Log created and updated and deleted users to EventLog
                    usersChanged.WriteEventsToEventLog();

                    #endregion

                    // Import canceled
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    TimeSpan duration = DateTime.Now - start;

                    if (!worker.CancellationPending)
                    {
                        // Add message to log
                        MessageLog.LogEvent(warnings == 0
                            ? ResHelper.GetString("Log_ImportComplete", duration.Hours, duration.Minutes, duration.Seconds)
                            : ResHelper.GetString("Log_ImportCompleteWithWarnings", warnings, duration.Hours, duration.Minutes, duration.Seconds));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageLog.LogError(ResHelper.GetString("Error_General"), ex);
            }
        }
    private void EnsureAuthenticatedRole()
    {
        // Handle Global First
        RoleInfo AuthenticatedUserRole    = GetOrCreateRole(_AuthenticatedRole, _AuthenticatedRoleDisplayName, _AuthenticatedRoleDescription, null);
        RoleInfo NotAuthenticatedUserRole = GetOrCreateRole(_NotAuthenticatedRole, _NotAuthenticatedRoleDisplayName, _NotAuthenticatedRoleDescription, null);
        RoleInfo EveryoneUserRole         = GetOrCreateRole(_EveryoneRole, _EveryoneRoleDisplayName, _EveryoneRoleDescription, null);

        // Public user
        UserInfoProvider.GetUsers()
        .WhereEquals("username", "public")
        .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", NotAuthenticatedUserRole.RoleID)
                    .TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
        {
            HandleUserRole(x.UserID, NotAuthenticatedUserRole.RoleID);
        });

        // Non public users
        UserInfoProvider.GetUsers()
        .WhereNotEquals("username", "public")
        .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", AuthenticatedUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
        {
            HandleUserRole(x.UserID, AuthenticatedUserRole.RoleID);
        });

        // Now everyone
        UserInfoProvider.GetUsers()
        .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", EveryoneUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
        {
            HandleUserRole(x.UserID, EveryoneUserRole.RoleID);
        });

        // Now go through Site Users
        foreach (SiteInfo Site in SiteInfoProvider.GetSites())
        {
            RoleInfo SiteAuthenticatedUserRole    = GetOrCreateRole(_AuthenticatedRole, _AuthenticatedRoleDisplayName, _AuthenticatedRoleDescription, Site.SiteID);
            RoleInfo SiteNotAuthenticatedUserRole = GetOrCreateRole(_NotAuthenticatedRole, _NotAuthenticatedRoleDisplayName, _NotAuthenticatedRoleDescription, Site.SiteID);
            RoleInfo SiteEveryoneUserRole         = GetOrCreateRole(_EveryoneRole, _EveryoneRoleDisplayName, _EveryoneRoleDescription, Site.SiteID);

            // Public user
            UserInfoProvider.GetUsers()
            .WhereEquals("username", "public")
            .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray())
            .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteAuthenticatedUserRole.RoleID)
                        .TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
            {
                HandleUserRole(x.UserID, SiteAuthenticatedUserRole.RoleID);
            });

            // Non public users
            UserInfoProvider.GetUsers()
            .WhereNotEquals("username", "public")
            .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray())
            .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteNotAuthenticatedUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
            {
                HandleUserRole(x.UserID, SiteNotAuthenticatedUserRole.RoleID);
            });

            // Now everyone
            UserInfoProvider.GetUsers()
            .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray())
            .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteEveryoneUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x =>
            {
                HandleUserRole(x.UserID, SiteEveryoneUserRole.RoleID);
            });
        }
    }
Exemple #15
0
    /// <summary>
    /// Page_load event.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check permissions and UI elements
        CurrentUserInfo user = CMSContext.CurrentUser;

        if (user != null)
        {
            if (!user.IsAuthorizedPerUIElement("CMS.Administration", "Roles"))
            {
                RedirectToCMSDeskUIElementAccessDenied("CMS.Administration", "Roles");
            }

            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Roles", "Read"))
            {
                RedirectToAccessDenied("CMS.Roles", "Read");
            }
        }

        ScriptHelper.RegisterJQuery(Page);

        // Get user id and site Id from query
        userId = QueryHelper.GetInteger("userid", 0);

        // Show contentplaceholder where site selector can be shown
        CurrentMaster.DisplaySiteSelectorPanel = true;

        if ((SiteID > 0) && !CMSContext.CurrentUser.IsGlobalAdministrator)
        {
            plcSites.Visible = false;
            CurrentMaster.DisplaySiteSelectorPanel = false;
        }

        if (userId > 0)
        {
            // Check that only global administrator can edit global administrator's accouns
            ui = UserInfoProvider.GetUserInfo(userId);
            CheckUserAvaibleOnSite(ui);
            EditedObject = ui;

            if (!CheckGlobalAdminEdit(ui))
            {
                plcTable.Visible = false;
                ShowError(GetString("Administration-User_List.ErrorGlobalAdmin"));
                return;
            }


            // Set site selector
            siteSelector.DropDownSingleSelect.AutoPostBack = true;
            siteSelector.AllowAll   = false;
            siteSelector.AllowEmpty = false;

            // Global roles only for global admin
            if (CMSContext.CurrentUser.UserSiteManagerAdmin)
            {
                siteSelector.AllowGlobal = true;
            }

            // Only sites assigned to user
            siteSelector.UserId           = userId;
            siteSelector.OnlyRunningSites = false;
            siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged);

            if (!RequestHelper.IsPostBack())
            {
                siteId = CMSContext.CurrentSiteID;

                // If user is member of current site
                if (UserSiteInfoProvider.GetUserSiteInfo(userId, siteId) != null)
                {
                    // Force uniselector to preselect current site
                    siteSelector.Value = siteId;
                }

                // Force to load data
                siteSelector.UpdateWhereCondition();
                siteSelector.Reload(true);
            }

            // Get truly selected item
            siteId = ValidationHelper.GetInteger(siteSelector.Value, 0);
        }

        usRoles.OnSelectionChanged += new EventHandler(usRoles_OnSelectionChanged);
        string siteIDWhere = (siteId <= 0) ? " SiteID IS NULL " : " SiteID =" + siteId;

        usRoles.WhereCondition = siteIDWhere + " AND RoleGroupID IS NULL";

        usRoles.SelectItemPageUrl     = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx";
        usRoles.ListingWhereCondition = siteIDWhere + " AND RoleGroupID IS NULL AND UserID=" + userId;
        usRoles.ReturnColumnName      = "RoleID";
        usRoles.DynamicColumnName     = false;
        usRoles.GridName               = "User_Role_List.xml";
        usRoles.AdditionalColumns      = "ValidTo";
        usRoles.OnAdditionalDataBound += new CMSAdminControls_UI_UniSelector_UniSelector.AdditionalDataBoundEventHandler(usMemberships_OnAdditionalDataBound);

        // Exclude generic roles
        string    genericWhere = null;
        ArrayList genericRoles = RoleInfoProvider.GetGenericRoles();

        if (genericRoles.Count != 0)
        {
            foreach (string role in genericRoles)
            {
                genericWhere += "'" + role.Replace("'", "''") + "',";
            }

            genericWhere            = genericWhere.TrimEnd(',');
            usRoles.WhereCondition += " AND ( RoleName NOT IN (" + genericWhere + ") )";
        }

        // Get the active roles for this site
        DataSet ds = UserRoleInfoProvider.GetUserRoles("UserID = " + userId + " AND RoleID IN (SELECT RoleID FROM CMS_Role WHERE SiteID IS NULL OR SiteID = " + siteId + ")", null, 0, "RoleID");

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            currentValues = TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "RoleID"));
        }

        // If not postback or site selection changed
        if (!RequestHelper.IsPostBack() || (siteId != Convert.ToInt32(ViewState["rolesOldSiteId"])))
        {
            // Set values
            usRoles.Value = currentValues;
        }

        // Store selected site id
        ViewState["rolesOldSiteId"] = siteId;

        string script = "function setNewDateTime(date) {$j('#" + hdnDate.ClientID + "').val(date);}";

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "key", ScriptHelper.GetScript(script));

        string eventTarget   = Request["__EVENTTARGET"];
        string eventArgument = Request["__EVENTARGUMENT"];

        if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID)
        {
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Users", "ManageUserRoles"))
            {
                RedirectToAccessDenied("CMS.Users", "Manage user roles");
            }

            int id = ValidationHelper.GetInteger(hdnDate.Value, 0);
            if (id != 0)
            {
                DateTime     dt  = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME);
                UserRoleInfo uri = UserRoleInfoProvider.GetUserRoleInfo(userId, id);
                if (uri != null)
                {
                    uri.ValidTo = dt;
                    UserRoleInfoProvider.SetUserRoleInfo(uri);

                    // Invalidate user
                    UserInfoProvider.InvalidateUser(userId);

                    ShowChangesSaved();
                }
            }
        }
    }