/// <summary> /// Handles the GridReorder event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> protected void rGrid_GridReorder(object sender, GridReorderEventArgs e) { int entityTypeId = iSecured.TypeId; var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); List <Rock.Model.Auth> rules = authService.GetAuths(iSecured.TypeId, iSecured.Id, CurrentAction).ToList(); authService.Reorder(rules, e.OldIndex, e.NewIndex); rockContext.SaveChanges(); Authorization.ReloadAction(iSecured.TypeId, iSecured.Id, CurrentAction); BindGrid(); }
/// <summary> /// Handles the Delete event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); Rock.Model.Auth auth = authService.Get(e.RowKeyId); if (auth != null) { authService.Delete(auth); rockContext.SaveChanges(); Authorization.ReloadAction(iSecured.TypeId, iSecured.Id, CurrentAction); } BindGrid(); }
/// <summary> /// Handles the Delete event of the gGroups control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gGroups_Delete( object sender, RowEventArgs e ) { RockTransactionScope.WrapTransaction( () => { GroupService groupService = new GroupService(); AuthService authService = new AuthService(); Group group = groupService.Get( (int)e.RowKeyValue ); if ( group != null ) { string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole; if ( isSecurityRoleGroup ) { foreach ( var auth in authService.Queryable().Where( a => a.GroupId.Equals( group.Id ) ).ToList() ) { authService.Delete( auth, CurrentPersonId ); authService.Save( auth, CurrentPersonId ); } } groupService.Delete( group, CurrentPersonId ); groupService.Save( group, CurrentPersonId ); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); Rock.Security.Role.Flush( group.Id ); } } } ); BindGrid(); }
/// <summary> /// Handles the Click event of the lbAddUser control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbAddUser_Click(object sender, EventArgs e) { if (ppUser.PersonId.HasValue) { int?personAliasId = ppUser.PersonAliasId; if (personAliasId.HasValue) { using (var rockContext = new RockContext()) { var authService = new Rock.Model.AuthService(rockContext); var existingAuths = authService.GetAuths(iSecured.TypeId, iSecured.Id, CurrentAction).ToList(); if (!existingAuths.Any(a => a.PersonAliasId.HasValue && a.PersonAliasId.Value == personAliasId.Value)) { int order = existingAuths.Count > 0 ? existingAuths.Last().Order + 1 : 0; Rock.Model.Auth auth = new Rock.Model.Auth(); auth.EntityTypeId = iSecured.TypeId; auth.EntityId = iSecured.Id; auth.Action = CurrentAction; auth.AllowOrDeny = "A"; auth.SpecialRole = Rock.Model.SpecialRole.None; auth.PersonAliasId = personAliasId; auth.Order = order; authService.Add(auth); rockContext.SaveChanges(); Authorization.ReloadAction(iSecured.TypeId, iSecured.Id, CurrentAction); } } } } pnlAddUser.Visible = false; phList.Visible = true; BindGrid(); }
/// <summary> /// Handles the SelectedIndexChanged event of the rblAllowDeny control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void rblAllowDeny_SelectedIndexChanged(object sender, EventArgs e) { RadioButtonList rblAllowDeny = (RadioButtonList)sender; GridViewRow selectedRow = rblAllowDeny.NamingContainer as GridViewRow; if (selectedRow != null) { int id = (int)rGrid.DataKeys[selectedRow.RowIndex]["Id"]; var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); Rock.Model.Auth auth = authService.Get(id); if (auth != null) { auth.AllowOrDeny = rblAllowDeny.SelectedValue; rockContext.SaveChanges(); Authorization.ReloadAction(iSecured.TypeId, iSecured.Id, CurrentAction); } } BindGrid(); }
/// <summary> /// Load the static Authorizations object /// </summary> public static void Load() { Authorizations = new Dictionary<int, Dictionary<int, Dictionary<string, List<AuthRule>>>>(); AuthService authService = new AuthService(); foreach ( Auth auth in authService.Queryable(). OrderBy( A => A.EntityTypeId ).ThenBy( A => A.EntityId ).ThenBy( A => A.Action ).ThenBy( A => A.Order ) ) { if ( !Authorizations.ContainsKey( auth.EntityTypeId ) ) Authorizations.Add( auth.EntityTypeId, new Dictionary<int, Dictionary<string, List<AuthRule>>>() ); Dictionary<int, Dictionary<string, List<AuthRule>>> entityAuths = Authorizations[auth.EntityTypeId]; if ( !entityAuths.ContainsKey( auth.EntityId ?? 0 ) ) entityAuths.Add( auth.EntityId ?? 0, new Dictionary<string, List<AuthRule>>() ); Dictionary<string, List<AuthRule>> instanceAuths = entityAuths[auth.EntityId ?? 0]; if ( !instanceAuths.ContainsKey( auth.Action ) ) instanceAuths.Add( auth.Action, new List<AuthRule>() ); List<AuthRule> actionPermissions = instanceAuths[auth.Action]; actionPermissions.Add( new AuthRule( auth ) ); } }
/// <summary> /// Copies the authorizations from one <see cref="ISecured" /> object to another /// </summary> /// <param name="sourceEntity">The source entity.</param> /// <param name="targetEntity">The target entity.</param> /// <param name="rockContext">The rock context.</param> /// <param name="action">Optional action (if ommitted or left blank, all actions will be copied).</param> /// <remarks> /// This method will save any previous changes made to the context /// </remarks> public static void CopyAuthorization( ISecured sourceEntity, ISecured targetEntity, RockContext rockContext, string action = "" ) { Load(); var sourceEntityTypeId = sourceEntity.TypeId; var targetEntityTypeId = targetEntity.TypeId; AuthService authService = new AuthService( rockContext ); // Delete the current authorizations for the target entity foreach ( Auth auth in authService.Get( targetEntityTypeId, targetEntity.Id ).ToList() ) { if ( string.IsNullOrWhiteSpace( action ) || auth.Action.Equals( action, StringComparison.OrdinalIgnoreCase ) ) { authService.Delete( auth ); } } rockContext.SaveChanges(); // Copy target auths to source auths int order = 0; foreach ( Auth sourceAuth in authService.Get( sourceEntityTypeId, sourceEntity.Id ).ToList() ) { if ( ( string.IsNullOrWhiteSpace( action ) || sourceAuth.Action.Equals( action, StringComparison.OrdinalIgnoreCase ) ) && targetEntity.SupportedActions.ContainsKey( sourceAuth.Action ) ) { Auth auth = new Auth(); auth.EntityTypeId = targetEntityTypeId; auth.EntityId = targetEntity.Id; auth.Action = sourceAuth.Action; auth.AllowOrDeny = sourceAuth.AllowOrDeny; auth.GroupId = sourceAuth.GroupId; auth.PersonAliasId = sourceAuth.PersonAliasId; auth.SpecialRole = sourceAuth.SpecialRole; auth.Order = order++; authService.Add( auth ); rockContext.SaveChanges(); } } ReloadEntity( targetEntityTypeId, targetEntity.Id, rockContext ); }
/// <summary> /// Mies the allow all users. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="rockContext">The rock context.</param> private static void MyAllowAllUsers( ISecured entity, string action, RockContext rockContext ) { var authService = new AuthService( rockContext ); // Delete any existing rules in database foreach ( Auth auth in authService .GetAuths( entity.TypeId, entity.Id, action ) ) { authService.Delete( auth ); } rockContext.SaveChanges(); // Create the rule in the database Auth auth1 = new Auth(); auth1.EntityTypeId = entity.TypeId; auth1.EntityId = entity.Id; auth1.Order = 0; auth1.Action = action; auth1.AllowOrDeny = "A"; auth1.SpecialRole = SpecialRole.AllUsers; authService.Add( auth1 ); rockContext.SaveChanges(); // Reload the static dictionary for this action ReloadAction( entity.TypeId, entity.Id, action, rockContext ); }
/// <summary> /// Handles the Delete event of the gGroups control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gGroups_Delete( object sender, RowEventArgs e ) { // NOTE: Very similar code in GroupDetail.btnDelete_Click RockTransactionScope.WrapTransaction( () => { GroupService groupService = new GroupService(); AuthService authService = new AuthService(); Group group = groupService.Get( (int)e.RowKeyValue ); if ( group != null ) { string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); if (isSecurityRoleGroup) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId == group.Id ).ToList() ) { authService.Delete( auth, CurrentPersonId ); authService.Save( auth, CurrentPersonId ); } } groupService.Delete( group, CurrentPersonId ); groupService.Save( group, CurrentPersonId ); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } } ); BindGrid(); }
/// <summary> /// Handles the Delete event of the gGroups control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gGroups_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); AuthService authService = new AuthService( rockContext ); Group group = groupService.Get( e.RowKeyId ); if ( group != null ) { if ( !group.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdGridWarning.Show( "You are not authorized to delete this group", ModalAlertType.Information ); return; } string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); if ( isSecurityRoleGroup ) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId == group.Id ).ToList() ) { authService.Delete( auth ); } } groupService.Delete( group ); rockContext.SaveChanges(); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } BindGrid(); }
/// <summary> /// Copies any auths for the original pages and blocks over to the copied pages and blocks. /// </summary> /// <param name="pageGuidDictionary">The dictionary containing the original page guids and the corresponding copied page guids.</param> /// <param name="blockGuidDictionary">The dictionary containing the original block guids and the corresponding copied block guids.</param> /// <param name="rockContext">The rock context.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> private void GeneratePageBlockAuths( Dictionary<Guid, Guid> pageGuidDictionary, Dictionary<Guid, Guid> blockGuidDictionary, RockContext rockContext, int? currentPersonAliasId = null ) { var authService = new AuthService( rockContext ); var pageService = new PageService( rockContext ); var blockService = new BlockService( rockContext ); var pageGuid = Rock.SystemGuid.EntityType.PAGE.AsGuid(); var blockGuid = Rock.SystemGuid.EntityType.BLOCK.AsGuid(); Dictionary<Guid, int> pageIntDictionary = pageService.Queryable() .Where( p => pageGuidDictionary.Keys.Contains( p.Guid ) || pageGuidDictionary.Values.Contains( p.Guid ) ) .ToDictionary( p => p.Guid, p => p.Id ); Dictionary<Guid, int> blockIntDictionary = blockService.Queryable() .Where( p => blockGuidDictionary.Keys.Contains( p.Guid ) || blockGuidDictionary.Values.Contains( p.Guid ) ) .ToDictionary( p => p.Guid, p => p.Id ); var pageAuths = authService.Queryable().Where( a => a.EntityType.Guid == pageGuid && pageIntDictionary.Values.Contains( a.EntityId.Value ) ) .ToList(); var blockAuths = authService.Queryable().Where( a => a.EntityType.Guid == blockGuid && blockIntDictionary.Values.Contains( a.EntityId.Value ) ) .ToList(); foreach ( var pageAuth in pageAuths ) { var newPageAuth = pageAuth.Clone( false ); newPageAuth.CreatedByPersonAlias = null; newPageAuth.CreatedByPersonAliasId = currentPersonAliasId; newPageAuth.CreatedDateTime = RockDateTime.Now; newPageAuth.ModifiedByPersonAlias = null; newPageAuth.ModifiedByPersonAliasId = currentPersonAliasId; newPageAuth.ModifiedDateTime = RockDateTime.Now; newPageAuth.Id = 0; newPageAuth.Guid = Guid.NewGuid(); newPageAuth.EntityId = pageIntDictionary[pageGuidDictionary[pageIntDictionary.Where( d => d.Value == pageAuth.EntityId.Value ).FirstOrDefault().Key]]; authService.Add( newPageAuth ); } foreach ( var blockAuth in blockAuths ) { var newBlockAuth = blockAuth.Clone( false ); newBlockAuth.CreatedByPersonAlias = null; newBlockAuth.CreatedByPersonAliasId = currentPersonAliasId; newBlockAuth.CreatedDateTime = RockDateTime.Now; newBlockAuth.ModifiedByPersonAlias = null; newBlockAuth.ModifiedByPersonAliasId = currentPersonAliasId; newBlockAuth.ModifiedDateTime = RockDateTime.Now; newBlockAuth.Id = 0; newBlockAuth.Guid = Guid.NewGuid(); newBlockAuth.EntityId = blockIntDictionary[blockGuidDictionary[blockIntDictionary.Where( d => d.Value == blockAuth.EntityId.Value ).FirstOrDefault().Key]]; authService.Add( newBlockAuth ); } rockContext.SaveChanges(); }
/// <summary> /// Sets the role actions. /// </summary> private void SetRoleActions() { cblRoleActionList.Items.Clear(); using ( var rockContext = new RockContext() ) { var authService = new AuthService( rockContext ); var actions = iSecured.SupportedActions; foreach ( var action in actions ) { if ( action.Key == CurrentAction ) { lActionDescription.Text = action.Value; ListItem roleItem = new ListItem( action.Key ); roleItem.Selected = true; cblRoleActionList.Items.Add( roleItem ); } else { Rock.Model.SpecialRole specialRole = Rock.Model.SpecialRole.None; int? groupId = ddlRoles.SelectedValue.AsIntegerOrNull(); switch ( groupId ) { case -1: specialRole = Rock.Model.SpecialRole.AllUsers; break; case -2: specialRole = Rock.Model.SpecialRole.AllAuthenticatedUsers; break; case -3: specialRole = Rock.Model.SpecialRole.AllUnAuthenticatedUsers; break; default: specialRole = Rock.Model.SpecialRole.None; break; } if ( groupId < 0 ) { groupId = null; } if ( !authService.GetAuths( iSecured.TypeId, iSecured.Id, action.Key ) .Any( a => a.SpecialRole == specialRole && a.GroupId == groupId ) ) { cblRoleActionList.Items.Add( new ListItem( action.Key ) ); } } } } }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDelete_Click( object sender, EventArgs e ) { int? parentGroupId = null; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); AuthService authService = new AuthService( rockContext ); Group group = groupService.Get( int.Parse( hfGroupId.Value ) ); if ( group != null ) { if ( !group.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this group.", ModalAlertType.Information ); return; } parentGroupId = group.ParentGroupId; string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); if ( isSecurityRoleGroup ) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId == group.Id ).ToList() ) { authService.Delete( auth ); } } groupService.Delete( group ); rockContext.SaveChanges(); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } // reload page, selecting the deleted group's parent var qryParams = new Dictionary<string, string>(); if ( parentGroupId != null ) { qryParams["GroupId"] = parentGroupId.ToString(); } NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDelete_Click( object sender, EventArgs e ) { int? parentGroupId = null; RockContext rockContext = new RockContext(); GroupService groupService = new GroupService( rockContext ); AuthService authService = new AuthService( rockContext ); Group group = groupService.Get( hfGroupId.Value.AsInteger() ); if ( group != null ) { if ( !group.IsAuthorized( Authorization.EDIT, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this group.", ModalAlertType.Information ); return; } parentGroupId = group.ParentGroupId; string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsActive && ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ); if ( isSecurityRoleGroup ) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId == group.Id ).ToList() ) { authService.Delete( auth ); } } // If group has a non-named schedule, delete the schedule record. if ( group.ScheduleId.HasValue ) { var scheduleService = new ScheduleService( rockContext ); var schedule = scheduleService.Get( group.ScheduleId.Value ); if ( schedule != null && schedule.ScheduleType != ScheduleType.Named ) { // Make sure this is the only group trying to use this schedule. if ( !groupService.Queryable().Where( g => g.ScheduleId == schedule.Id && g.Id != group.Id ).Any() ) { scheduleService.Delete( schedule ); } } } groupService.Delete( group ); rockContext.SaveChanges(); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } // reload page, selecting the deleted group's parent var qryParams = new Dictionary<string, string>(); if ( parentGroupId != null ) { qryParams["GroupId"] = parentGroupId.ToString(); } qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDeleteConfirm_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext ); ConnectionTypeService connectionTypeService = new ConnectionTypeService( rockContext ); AuthService authService = new AuthService( rockContext ); ConnectionType connectionType = connectionTypeService.Get( int.Parse( hfConnectionTypeId.Value ) ); if ( connectionType != null ) { if ( !connectionType.IsAuthorized( Authorization.ADMINISTRATE, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this connection type.", ModalAlertType.Information ); return; } string errorMessage; if ( !connectionTypeService.CanDelete( connectionType, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } connectionTypeService.Delete( connectionType ); rockContext.SaveChanges(); ConnectionWorkflowService.FlushCachedTriggers(); } } NavigateToParentPage(); }
/// <summary> /// Reloads the authorizations for the specified entity and action. /// </summary> /// <param name="entityTypeId">The entity type id.</param> /// <param name="entityId">The entity id.</param> /// <param name="action">The action.</param> public static void ReloadAction( int entityTypeId, int entityId, string action ) { var rockContext = new RockContext(); // If there's no Authorizations object, create it if ( Authorizations == null ) Load( rockContext ); else { // Delete the current authorizations if ( Authorizations.ContainsKey( entityTypeId ) ) if ( Authorizations[entityTypeId].ContainsKey( entityId ) ) if ( Authorizations[entityTypeId][entityId].ContainsKey( action ) ) Authorizations[entityTypeId][entityId][action] = new List<AuthRule>(); // Find the Authrules for the given entity type, entity id, and action AuthService authService = new AuthService( rockContext ); foreach ( Auth auth in authService.GetAuths( entityTypeId, entityId, action ) ) { if ( !Authorizations.ContainsKey( auth.EntityTypeId ) ) Authorizations.Add( auth.EntityTypeId, new Dictionary<int, Dictionary<string, List<AuthRule>>>() ); Dictionary<int, Dictionary<string, List<AuthRule>>> entityAuths = Authorizations[auth.EntityTypeId]; if ( !entityAuths.ContainsKey( auth.EntityId ?? 0 ) ) entityAuths.Add( auth.EntityId ?? 0, new Dictionary<string, List<AuthRule>>() ); Dictionary<string, List<AuthRule>> instanceAuths = entityAuths[auth.EntityId ?? 0]; if ( !instanceAuths.ContainsKey( auth.Action ) ) instanceAuths.Add( auth.Action, new List<AuthRule>() ); List<AuthRule> actionPermissions = instanceAuths[auth.Action]; actionPermissions.Add( new AuthRule( auth ) ); } } }
/// <summary> /// Updates authorization rules for the entity so that the current person is allowed to perform the specified action. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="rockContext">The rock context.</param> public static void AllowPerson( ISecured entity, string action, Person person, RockContext rockContext = null ) { if ( person != null ) { rockContext = rockContext ?? new RockContext(); // If there's no Authorizations object, create it if ( Authorizations == null ) { Load( rockContext ); } var authService = new AuthService( rockContext ); // If there are not entries in the Authorizations object for this entity type and entity instance, create // the dictionary entries if ( !Authorizations.Keys.Contains( entity.TypeId ) ) { Authorizations.Add( entity.TypeId, new Dictionary<int, Dictionary<string, List<AuthRule>>>() ); } if ( !Authorizations[entity.TypeId].Keys.Contains( entity.Id ) ) { Authorizations[entity.TypeId].Add( entity.Id, new Dictionary<string, List<AuthRule>>() ); } List<AuthRule> rules = null; if ( Authorizations[entity.TypeId][entity.Id].Keys.Contains( action ) ) { rules = Authorizations[entity.TypeId][entity.Id][action]; } else { rules = new List<AuthRule>(); Authorizations[entity.TypeId][entity.Id].Add( action, rules ); } int order = 0; Auth auth = new Auth(); auth.EntityTypeId = entity.TypeId; auth.EntityId = entity.Id; auth.Order = order++; auth.Action = action; auth.AllowOrDeny = "A"; auth.SpecialRole = SpecialRole.None; auth.PersonId = person.Id; authService.Add( auth ); foreach(var rule in rules) { var existingAuth = authService.Get( rule.Id ); existingAuth.Order = order++; } rockContext.SaveChanges(); rules.Insert(0, new AuthRule( auth ) ); } }
/// <summary> /// Removes that two authorization rules that made the entity private. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="rockContext">The rock context.</param> public static void MakeUnPrivate( ISecured entity, string action, Person person, RockContext rockContext = null ) { if ( IsPrivate( entity, action, person ) ) { rockContext = rockContext ?? new RockContext(); var authService = new AuthService( rockContext ); // if is private, then there are only two rules for this action that should be deleted foreach ( AuthRule authRule in Authorizations[entity.TypeId][entity.Id][action] ) { var oldAuth = authService.Get( authRule.Id ); authService.Delete( oldAuth ); } rockContext.SaveChanges(); Authorizations[entity.TypeId][entity.Id][action] = new List<AuthRule>(); } }
/// <summary> /// Makes the entity private by setting up two authorization rules, one granting the selected person, and /// then another that denies all other users. /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="rockContext">The rock context.</param> public static void MakePrivate( ISecured entity, string action, Person person, RockContext rockContext = null ) { if ( !IsPrivate( entity, action, person ) ) { if ( person != null ) { rockContext = rockContext ?? new RockContext(); // If there's no Authorizations object, create it if ( Authorizations == null ) { Load( rockContext ); } var authService = new AuthService( rockContext ); // If there are not entries in the Authorizations object for this entity type and entity instance, create // the dictionary entries if ( !Authorizations.Keys.Contains( entity.TypeId ) ) { Authorizations.Add( entity.TypeId, new Dictionary<int, Dictionary<string, List<AuthRule>>>() ); } if ( !Authorizations[entity.TypeId].Keys.Contains( entity.Id ) ) { Authorizations[entity.TypeId].Add( entity.Id, new Dictionary<string, List<AuthRule>>() ); } if ( !Authorizations[entity.TypeId][entity.Id].Keys.Contains( action ) ) { Authorizations[entity.TypeId][entity.Id].Add( action, new List<AuthRule>() ); } else { // If existing rules exist, delete them. foreach ( AuthRule authRule in Authorizations[entity.TypeId][entity.Id][action] ) { var oldAuth = authService.Get( authRule.Id ); authService.Delete( oldAuth ); } } var rules = new List<AuthRule>(); Auth auth1 = new Auth(); auth1.EntityTypeId = entity.TypeId; auth1.EntityId = entity.Id; auth1.Order = 0; auth1.Action = action; auth1.AllowOrDeny = "A"; auth1.SpecialRole = SpecialRole.None; auth1.PersonId = person.Id; authService.Add( auth1 ); Auth auth2 = new Auth(); auth2.EntityTypeId = entity.TypeId; auth2.EntityId = entity.Id; auth2.Order = 1; auth2.Action = action; auth2.AllowOrDeny = "D"; auth2.SpecialRole = SpecialRole.AllUsers; authService.Add( auth2 ); rockContext.SaveChanges(); rules.Add( new AuthRule( auth1 ) ); rules.Add( new AuthRule( auth2 ) ); Authorizations[entity.TypeId][entity.Id][action] = rules; } } }
/// <summary> /// Copies the authorizations from one <see cref="ISecured" /> object to another /// </summary> /// <param name="sourceEntity">The source entity.</param> /// <param name="targetEntity">The target entity.</param> /// <param name="rockContext">The rock context.</param> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static void CopyAuthorization( ISecured sourceEntity, ISecured targetEntity, RockContext rockContext = null ) { rockContext = rockContext ?? new RockContext(); // If there's no Authorizations object, create it if ( Authorizations == null ) { Load( rockContext ); } var sourceEntityTypeId = sourceEntity.TypeId; var targetEntityTypeId = targetEntity.TypeId; AuthService authService = new AuthService( rockContext ); // Delete the current authorizations for the target entity foreach ( Auth auth in authService.Get( targetEntityTypeId, targetEntity.Id ) ) { authService.Delete( auth ); } Dictionary<string, List<AuthRule>> newActions = new Dictionary<string, List<AuthRule>>(); int order = 0; if ( Authorizations.ContainsKey( sourceEntityTypeId ) && Authorizations[sourceEntityTypeId].ContainsKey( sourceEntity.Id ) ) { foreach ( KeyValuePair<string, List<AuthRule>> action in Authorizations[sourceEntityTypeId][sourceEntity.Id] ) { if ( targetEntity.SupportedActions.ContainsKey( action.Key ) ) { newActions.Add( action.Key, new List<AuthRule>() ); foreach ( AuthRule rule in action.Value ) { Auth auth = new Auth(); auth.EntityTypeId = targetEntityTypeId; auth.EntityId = targetEntity.Id; auth.Order = order; auth.Action = action.Key; auth.AllowOrDeny = rule.AllowOrDeny; auth.SpecialRole = rule.SpecialRole; auth.PersonId = rule.PersonId; auth.GroupId = rule.GroupId; authService.Add( auth ); newActions[action.Key].Add( new AuthRule( rule.Id, rule.EntityId, rule.AllowOrDeny, rule.SpecialRole, rule.PersonId, rule.GroupId, rule.Order ) ); order++; } } } } rockContext.SaveChanges(); if ( !Authorizations.ContainsKey( targetEntityTypeId ) ) { Authorizations.Add( targetEntityTypeId, new Dictionary<int, Dictionary<string, List<AuthRule>>>() ); } Dictionary<int, Dictionary<string, List<AuthRule>>> entityType = Authorizations[targetEntityTypeId]; if ( !entityType.ContainsKey( targetEntity.Id ) ) { entityType.Add( targetEntity.Id, new Dictionary<string, List<AuthRule>>() ); } entityType[targetEntity.Id] = newActions; }
/// <summary> /// Adds the parent rules. /// </summary> /// <param name="authService">The authentication service.</param> /// <param name="itemRules">The item rules.</param> /// <param name="parentRules">The parent rules.</param> /// <param name="parent">The parent.</param> /// <param name="action">The action.</param> /// <param name="recurse">if set to <c>true</c> [recurse].</param> private void AddParentRules( AuthService authService, List<AuthRule> itemRules, List<MyAuthRule> parentRules, ISecured parent, string action, bool recurse ) { if ( parent != null ) { var entityType = Rock.Web.Cache.EntityTypeCache.Read( parent.TypeId ); foreach ( var auth in authService.GetAuths( parent.TypeId, parent.Id, action ) ) { var rule = new AuthRule( auth ); if ( !itemRules.Exists( r => r.SpecialRole == rule.SpecialRole && r.PersonId == rule.PersonId && r.GroupId == rule.GroupId ) && !parentRules.Exists( r => r.AuthRule.SpecialRole == rule.SpecialRole && r.AuthRule.PersonId == rule.PersonId && r.AuthRule.GroupId == rule.GroupId ) ) { var myRule = new MyAuthRule( rule ); myRule.EntityTitle = string.Format( "{0} <small>({1})</small>", parent.ToString(), entityType.FriendlyName ?? entityType.Name ).TrimStart(); parentRules.Add( myRule ); } } if ( recurse ) { AddParentRules( authService, itemRules, parentRules, parent.ParentAuthority, action, true ); } } }
/// <summary> /// Deletes the family's addresses, phone numbers, photos, viewed records, and people. /// TODO: delete attendance codes for attendance data that's about to be deleted when /// we delete the person record. /// </summary> /// <param name="families">The families.</param> /// <param name="rockContext">The rock context.</param> private void DeleteExistingFamilyData( XElement families, RockContext rockContext ) { PersonService personService = new PersonService( rockContext ); PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext ); PersonViewedService personViewedService = new PersonViewedService( rockContext ); PageViewService pageViewService = new PageViewService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); PersonAliasService personAliasService = new PersonAliasService( rockContext ); NoteService noteService = new NoteService( rockContext ); AuthService authService = new AuthService( rockContext ); foreach ( var elemFamily in families.Elements( "family" ) ) { Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid(); GroupService groupService = new GroupService( rockContext ); Group family = groupService.Get( guid ); if ( family != null ) { var groupMemberService = new GroupMemberService( rockContext ); var members = groupMemberService.GetByGroupId( family.Id ); // delete the people records string errorMessage; List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList(); foreach ( var person in members.Select( m => m.Person ) ) { person.GivingGroup = null; person.GivingGroupId = null; person.PhotoId = null; // delete phone numbers foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) ) { if ( phone != null ) { phoneNumberService.Delete( phone ); } } // delete person viewed records foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) ) { personViewedService.Delete( view ); } // delete page viewed records foreach ( var view in pageViewService.GetByPersonId( person.Id ) ) { pageViewService.Delete( view ); } // delete notes created by them or on their record. foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) ) { noteService.Delete( note ); } //// delete any GroupMember records they have //foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) ) //{ // groupMemberService.Delete( groupMember ); //} //// delete any Authorization data //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) ) //{ // authService.Delete( auth ); //} // delete their aliases foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) ) { personAliasService.Delete( alias ); } //foreach ( var relationship in person.Gro) // Save these changes so the CanDelete passes the check... //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); if ( personService.CanDelete( person, out errorMessage ) ) { personService.Delete( person ); //rockContext.ChangeTracker.DetectChanges(); //rockContext.SaveChanges( disablePrePostProcessing: true ); } } //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); // delete all member photos foreach ( var photo in binaryFileService.GetByIds( photoIds ) ) { binaryFileService.Delete( photo ); } DeleteGroupAndMemberData( family, rockContext ); } } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { using ( var rockContext = new RockContext() ) { var authService = new AuthService( rockContext ); var itemRules = new List<AuthRule>(); foreach ( var auth in authService.GetAuths( iSecured.TypeId, iSecured.Id, CurrentAction ) ) { itemRules.Add( new AuthRule( auth ) ); } rGrid.DataSource = itemRules; rGrid.DataBind(); var parentRules = new List<MyAuthRule>(); AddParentRules( authService, itemRules, parentRules, iSecured.ParentAuthorityPre, CurrentAction, false ); AddParentRules( authService, itemRules, parentRules, iSecured.ParentAuthority, CurrentAction, true ); rGridParentRules.DataSource = parentRules; rGridParentRules.DataBind(); } }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDelete_Click( object sender, EventArgs e ) { int? parentGroupId = null; // NOTE: Very similar code in GroupList.gGroups_Delete RockTransactionScope.WrapTransaction( () => { GroupService groupService = new GroupService(); AuthService authService = new AuthService(); Group group = groupService.Get( int.Parse( hfGroupId.Value ) ); if ( group != null ) { parentGroupId = group.ParentGroupId; string errorMessage; if ( !groupService.CanDelete( group, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } bool isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ); if ( isSecurityRoleGroup ) { Rock.Security.Role.Flush( group.Id ); foreach ( var auth in authService.Queryable().Where( a => a.GroupId.Equals( group.Id ) ).ToList() ) { authService.Delete( auth, CurrentPersonId ); authService.Save( auth, CurrentPersonId ); } } groupService.Delete( group, CurrentPersonId ); groupService.Save( group, CurrentPersonId ); if ( isSecurityRoleGroup ) { Rock.Security.Authorization.Flush(); } } } ); // reload page, selecting the deleted group's parent var qryParams = new Dictionary<string, string>(); if ( parentGroupId != null ) { qryParams["groupId"] = parentGroupId.ToString(); } NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Updates the bulk update security. /// </summary> private static void UpdateBulkUpdateSecurity() { var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); var bulkUpdateBlockType = BlockTypeCache.Get(Rock.SystemGuid.BlockType.BULK_UPDATE.AsGuid()); var bulkUpdateBlocks = new BlockService(rockContext).Queryable().Where(a => a.BlockTypeId == bulkUpdateBlockType.Id).ToList(); foreach (var bulkUpdateBlock in bulkUpdateBlocks) { var alreadyUpdated = authService.Queryable().Where(a => (a.Action == "EditConnectionStatus" || a.Action == "EditRecordStatus") && a.EntityTypeId == bulkUpdateBlock.TypeId && a.EntityId == bulkUpdateBlock.Id).Any(); if (alreadyUpdated) { // EditConnectionStatus and/or EditRecordStatus has already been set, so don't copy VIEW auth to it continue; } var groupIdAuthRules = new HashSet <int>(); var personIdAuthRules = new HashSet <int>(); var specialRoleAuthRules = new HashSet <SpecialRole>(); var authRulesToAdd = new List <AuthRule>(); Dictionary <ISecured, List <AuthRule> > parentAuthRulesList = new Dictionary <ISecured, List <AuthRule> >(); ISecured secured = bulkUpdateBlock; while (secured != null) { var entityType = secured.TypeId; List <AuthRule> authRules = Authorization.AuthRules(secured.TypeId, secured.Id, Authorization.VIEW).OrderBy(a => a.Order).ToList(); foreach (var rule in authRules) { if (rule.GroupId.HasValue) { if (!groupIdAuthRules.Contains(rule.GroupId.Value)) { groupIdAuthRules.Add(rule.GroupId.Value); authRulesToAdd.Add(rule); } } else if (rule.PersonId.HasValue) { if (!personIdAuthRules.Contains(rule.PersonId.Value)) { personIdAuthRules.Add(rule.PersonId.Value); authRulesToAdd.Add(rule); } } else if (rule.SpecialRole != SpecialRole.None) { if (!specialRoleAuthRules.Contains(rule.SpecialRole)) { specialRoleAuthRules.Add(rule.SpecialRole); authRulesToAdd.Add(rule); } } } secured = secured.ParentAuthority; } List <Auth> authsToAdd = new List <Auth>(); foreach (var auth in authRulesToAdd) { authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditConnectionStatus")); authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditRecordStatus")); } int authOrder = 0; authsToAdd.ForEach(a => a.Order = authOrder++); authService.AddRange(authsToAdd); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditConnectionStatus"); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditRecordStatus"); } rockContext.SaveChanges(); }
/// <summary> /// Handles the Click event of the lbAddRole control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbAddRole_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var authService = new AuthService( rockContext ); foreach ( ListItem li in cblRoleActionList.Items ) { if ( li.Selected ) { Rock.Model.SpecialRole specialRole = Rock.Model.SpecialRole.None; int? groupId = ddlRoles.SelectedValue.AsIntegerOrNull(); switch ( groupId ) { case -1: specialRole = Rock.Model.SpecialRole.AllUsers; break; case -2: specialRole = Rock.Model.SpecialRole.AllAuthenticatedUsers; break; case -3: specialRole = Rock.Model.SpecialRole.AllUnAuthenticatedUsers; break; default: specialRole = Rock.Model.SpecialRole.None; break; } if ( groupId < 0 ) { groupId = null; } var existingAuths = authService.GetAuths( iSecured.TypeId, iSecured.Id, li.Text ).ToList(); if ( !existingAuths.Any( a => a.SpecialRole == specialRole && a.GroupId.Equals( groupId ) ) ) { int order = existingAuths.Count > 0 ? existingAuths.Last().Order + 1 : 0; Rock.Model.Auth auth = new Rock.Model.Auth(); auth.EntityTypeId = iSecured.TypeId; auth.EntityId = iSecured.Id; auth.Action = li.Text; auth.AllowOrDeny = "A"; auth.SpecialRole = specialRole; auth.GroupId = groupId; auth.Order = order; authService.Add( auth ); rockContext.SaveChanges(); Authorization.ReloadAction( iSecured.TypeId, iSecured.Id, li.Text ); } } } } pnlAddRole.Visible = false; phList.Visible = true; BindGrid(); }
/// <summary> /// Deletes the family's addresses, phone numbers, photos, viewed records, and people. /// TODO: delete attendance codes for attendance data that's about to be deleted when /// we delete the person record. /// </summary> /// <param name="families">The families.</param> /// <param name="rockContext">The rock context.</param> private void DeleteExistingFamilyData( XElement families, RockContext rockContext ) { PersonService personService = new PersonService( rockContext ); PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext ); PersonViewedService personViewedService = new PersonViewedService( rockContext ); PageViewService pageViewService = new PageViewService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); PersonAliasService personAliasService = new PersonAliasService( rockContext ); PersonDuplicateService personDuplicateService = new PersonDuplicateService( rockContext ); NoteService noteService = new NoteService( rockContext ); AuthService authService = new AuthService( rockContext ); CommunicationService communicationService = new CommunicationService( rockContext ); CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService( rockContext ); FinancialBatchService financialBatchService = new FinancialBatchService( rockContext ); FinancialTransactionService financialTransactionService = new FinancialTransactionService( rockContext ); PersonPreviousNameService personPreviousNameService = new PersonPreviousNameService( rockContext ); ConnectionRequestService connectionRequestService = new ConnectionRequestService( rockContext ); ConnectionRequestActivityService connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); // delete the batch data List<int> imageIds = new List<int>(); foreach ( var batch in financialBatchService.Queryable().Where( b => b.Name.StartsWith( "SampleData" ) ) ) { imageIds.AddRange( batch.Transactions.SelectMany( t => t.Images ).Select( i => i.BinaryFileId ).ToList() ); financialTransactionService.DeleteRange( batch.Transactions ); financialBatchService.Delete( batch ); } // delete all transaction images foreach ( var image in binaryFileService.GetByIds( imageIds ) ) { binaryFileService.Delete( image ); } foreach ( var elemFamily in families.Elements( "family" ) ) { Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid(); GroupService groupService = new GroupService( rockContext ); Group family = groupService.Get( guid ); if ( family != null ) { var groupMemberService = new GroupMemberService( rockContext ); var members = groupMemberService.GetByGroupId( family.Id, true ); // delete the people records string errorMessage; List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList(); foreach ( var person in members.Select( m => m.Person ) ) { person.GivingGroup = null; person.GivingGroupId = null; person.PhotoId = null; // delete phone numbers foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) ) { if ( phone != null ) { phoneNumberService.Delete( phone ); } } // delete communication recipient foreach ( var recipient in communicationRecipientService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { communicationRecipientService.Delete( recipient ); } // delete communication foreach ( var communication in communicationService.Queryable().Where( c => c.SenderPersonAliasId == person.PrimaryAlias.Id ) ) { communicationService.Delete( communication ); } // delete person viewed records foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) ) { personViewedService.Delete( view ); } // delete page viewed records foreach ( var view in pageViewService.GetByPersonId( person.Id ) ) { pageViewService.Delete( view ); } // delete notes created by them or on their record. foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) ) { noteService.Delete( note ); } // delete previous names on their records foreach ( var previousName in personPreviousNameService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { personPreviousNameService.Delete( previousName ); } // delete any GroupMember records they have foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) ) { groupMemberService.Delete( groupMember ); } //// delete any Authorization data //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) ) //{ // authService.Delete( auth ); //} // delete their aliases foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) ) { foreach ( var duplicate in personDuplicateService.Queryable().Where( d => d.DuplicatePersonAliasId == alias.Id ) ) { personDuplicateService.Delete( duplicate ); } personAliasService.Delete( alias ); } // delete any connection requests tied to them foreach ( var request in connectionRequestService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id || r.ConnectorPersonAlias.PersonId == person.Id ) ) { connectionRequestActivityService.DeleteRange( request.ConnectionRequestActivities ); connectionRequestService.Delete( request ); } // Save these changes so the CanDelete passes the check... //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); if ( personService.CanDelete( person, out errorMessage ) ) { personService.Delete( person ); //rockContext.ChangeTracker.DetectChanges(); //rockContext.SaveChanges( disablePrePostProcessing: true ); } else { throw new Exception( string.Format( "Trying to delete {0}, but: {1}", person.FullName, errorMessage ) ); } } //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); // delete all member photos foreach ( var photo in binaryFileService.GetByIds( photoIds ) ) { binaryFileService.Delete( photo ); } DeleteGroupAndMemberData( family, rockContext ); } } }
/// <summary> /// Copies the specified connection type. /// </summary> /// <param name="connectionTypeId">The connection type identifier.</param> /// <returns> /// Return the new ConnectionType ID /// </returns> public int Copy(int connectionTypeId) { var connectionType = this.Get(connectionTypeId); var rockContext = ( RockContext )Context; var attributeService = new AttributeService(rockContext); var authService = new AuthService(rockContext); int newConnectionTypeId = 0; // Get current Opportunity attributes var opportunityAttributes = attributeService .GetByEntityTypeId(new ConnectionOpportunity().TypeId, true).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString())) .OrderBy(a => a.Order) .ThenBy(a => a.Name) .ToList(); var newConnectionType = new ConnectionType(); rockContext.WrapTransaction(() => { newConnectionType = connectionType.CloneWithoutIdentity(); newConnectionType.Name = connectionType.Name + " - Copy"; this.Add(newConnectionType); rockContext.SaveChanges(); newConnectionTypeId = newConnectionType.Id; foreach (var connectionActivityTypeState in connectionType.ConnectionActivityTypes) { var newConnectionActivityType = connectionActivityTypeState.CloneWithoutIdentity(); newConnectionType.ConnectionActivityTypes.Add(newConnectionActivityType); } foreach (var connectionStatusState in connectionType.ConnectionStatuses) { var newConnectionStatus = connectionStatusState.CloneWithoutIdentity(); newConnectionType.ConnectionStatuses.Add(newConnectionStatus); newConnectionStatus.ConnectionTypeId = newConnectionType.Id; } foreach (ConnectionWorkflow connectionWorkflowState in connectionType.ConnectionWorkflows) { var newConnectionWorkflow = connectionWorkflowState.CloneWithoutIdentity(); newConnectionType.ConnectionWorkflows.Add(newConnectionWorkflow); newConnectionWorkflow.ConnectionTypeId = newConnectionType.Id; } rockContext.SaveChanges(); // Clone the Opportunity attributes List <Attribute> newAttributesState = new List <Attribute>(); foreach (var attribute in opportunityAttributes) { var newAttribute = attribute.CloneWithoutIdentity(); newAttribute.IsSystem = false; newAttributesState.Add(newAttribute); foreach (var qualifier in attribute.AttributeQualifiers) { var newQualifier = qualifier.Clone(false); newQualifier.Id = 0; newQualifier.Guid = Guid.NewGuid(); newQualifier.IsSystem = false; newAttribute.AttributeQualifiers.Add(qualifier); } } // Save Attributes string qualifierValue = newConnectionType.Id.ToString(); Rock.Attribute.Helper.SaveAttributeEdits(newAttributesState, new ConnectionOpportunity().TypeId, "ConnectionTypeId", qualifierValue, rockContext); // Copy Security Rock.Security.Authorization.CopyAuthorization(connectionType, newConnectionType, rockContext); }); CopyConnectionOpportunities(connectionType, newConnectionType); ConnectionWorkflowService.RemoveCachedTriggers(); return(newConnectionTypeId); }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnDelete_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { EventCalendarService eventCalendarService = new EventCalendarService( rockContext ); AuthService authService = new AuthService( rockContext ); EventCalendar eventCalendar = eventCalendarService.Get( int.Parse( hfEventCalendarId.Value ) ); if ( eventCalendar != null ) { bool adminAllowed = UserCanAdministrate || eventCalendar.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); if ( !adminAllowed ) { mdDeleteWarning.Show( "You are not authorized to delete this calendar.", ModalAlertType.Information ); return; } string errorMessage; if ( !eventCalendarService.CanDelete( eventCalendar, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } eventCalendarService.Delete( eventCalendar ); rockContext.SaveChanges(); } } NavigateToParentPage(); }
/// <summary> /// Handles the SelectedIndexChanged event of the rblAllowDeny control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void rblAllowDeny_SelectedIndexChanged( object sender, EventArgs e ) { RadioButtonList rblAllowDeny = (RadioButtonList)sender; GridViewRow selectedRow = rblAllowDeny.NamingContainer as GridViewRow; if ( selectedRow != null ) { int id = (int)rGrid.DataKeys[selectedRow.RowIndex]["Id"]; var rockContext = new RockContext(); var authService = new Rock.Model.AuthService( rockContext ); Rock.Model.Auth auth = authService.Get( id ); if ( auth != null ) { auth.AllowOrDeny = rblAllowDeny.SelectedValue; rockContext.SaveChanges(); Authorization.ReloadAction( iSecured.TypeId, iSecured.Id, CurrentAction ); } } BindGrid(); }
/// <summary> /// Makes the entity private for the selected action and person /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="rockContext">The rock context.</param> private static void MyMakePrivate( ISecured entity, string action, Person person, RockContext rockContext ) { if ( !IsPrivate( entity, action, person ) ) { if ( person != null ) { var personAlias = new PersonAliasService( rockContext ).GetPrimaryAlias( person.Id ); if ( personAlias != null ) { var authService = new AuthService( rockContext ); // Delete any existing rules in database foreach ( Auth auth in authService .GetAuths( entity.TypeId, entity.Id, action ) ) { authService.Delete( auth ); } rockContext.SaveChanges(); // Create the rules in the database Auth auth1 = new Auth(); auth1.EntityTypeId = entity.TypeId; auth1.EntityId = entity.Id; auth1.Order = 0; auth1.Action = action; auth1.AllowOrDeny = "A"; auth1.SpecialRole = SpecialRole.None; auth1.PersonAlias = personAlias; auth1.PersonAliasId = personAlias.Id; authService.Add( auth1 ); Auth auth2 = new Auth(); auth2.EntityTypeId = entity.TypeId; auth2.EntityId = entity.Id; auth2.Order = 1; auth2.Action = action; auth2.AllowOrDeny = "D"; auth2.SpecialRole = SpecialRole.AllUsers; authService.Add( auth2 ); rockContext.SaveChanges(); // Reload the static dictionary for this action ReloadAction( entity.TypeId, entity.Id, action, rockContext ); } } } }
/// <summary> /// Handles the Delete event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); var authService = new Rock.Model.AuthService( rockContext ); Rock.Model.Auth auth = authService.Get( e.RowKeyId ); if ( auth != null ) { authService.Delete( auth ); rockContext.SaveChanges(); Authorization.ReloadAction( iSecured.TypeId, iSecured.Id, CurrentAction ); } BindGrid(); }
/// <summary> /// Creates authorization rules to make the entity private to selected person /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="group">The group.</param> /// <param name="specialRole">The special role.</param> /// <param name="rockContext">The rock context.</param> private static void MyAllow( ISecured entity, string action, Person person = null, Group group = null, SpecialRole specialRole = SpecialRole.None, RockContext rockContext = null ) { rockContext = rockContext ?? new RockContext(); PersonAlias personAlias = null; if ( person != null ) { personAlias = new PersonAliasService( rockContext ).GetPrimaryAlias( person.Id ); } if ( personAlias != null || group != null || specialRole != SpecialRole.None ) { var authService = new AuthService( rockContext ); // Update the order for any existing rules in database int order = 1; foreach ( Auth existingAuth in authService .GetAuths( entity.TypeId, entity.Id, action ) ) { existingAuth.Order = order++; } // Add the new auth (with order of zero) Auth auth = new Auth(); auth.EntityTypeId = entity.TypeId; auth.EntityId = entity.Id; auth.Order = 0; auth.Action = action; auth.AllowOrDeny = "A"; auth.SpecialRole = specialRole; if ( personAlias != null ) { auth.PersonAlias = personAlias; auth.PersonAliasId = personAlias.Id; } if ( group != null ) { auth.Group = group; auth.GroupId = group.Id; } authService.Add( auth ); rockContext.SaveChanges(); // Reload the static dictionary for this action ReloadAction( entity.TypeId, entity.Id, action, rockContext ); } }
/// <summary> /// Handles the GridReorder event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> protected void rGrid_GridReorder( object sender, GridReorderEventArgs e ) { int entityTypeId = iSecured.TypeId; var rockContext = new RockContext(); var authService = new Rock.Model.AuthService( rockContext ); List<Rock.Model.Auth> rules = authService.GetAuths( iSecured.TypeId, iSecured.Id, CurrentAction ).ToList(); authService.Reorder( rules, e.OldIndex, e.NewIndex ); rockContext.SaveChanges(); Authorization.ReloadAction( iSecured.TypeId, iSecured.Id, CurrentAction ); BindGrid(); }
/// <summary> /// Handles the Click event of the lbAddUser control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbAddUser_Click( object sender, EventArgs e ) { if ( ppUser.PersonId.HasValue ) { int? personAliasId = ppUser.PersonAliasId; if ( personAliasId.HasValue ) { using ( var rockContext = new RockContext() ) { var authService = new Rock.Model.AuthService( rockContext ); var existingAuths = authService.GetAuths( iSecured.TypeId, iSecured.Id, CurrentAction ).ToList(); if ( !existingAuths.Any( a => a.PersonAliasId.HasValue && a.PersonAliasId.Value == personAliasId.Value ) ) { int order = existingAuths.Count > 0 ? existingAuths.Last().Order + 1 : 0; Rock.Model.Auth auth = new Rock.Model.Auth(); auth.EntityTypeId = iSecured.TypeId; auth.EntityId = iSecured.Id; auth.Action = CurrentAction; auth.AllowOrDeny = "A"; auth.SpecialRole = Rock.Model.SpecialRole.None; auth.PersonAliasId = personAliasId; auth.Order = order; authService.Add( auth ); rockContext.SaveChanges(); Authorization.ReloadAction( iSecured.TypeId, iSecured.Id, CurrentAction ); } } } } pnlAddUser.Visible = false; phList.Visible = true; BindGrid(); }
/// <summary> /// If the entity is currently private for selected person, removes all the rules /// </summary> /// <param name="entity">The entity.</param> /// <param name="action">The action.</param> /// <param name="person">The person.</param> /// <param name="rockContext">The rock context.</param> private static void MyMakeUnPrivate( ISecured entity, string action, Person person, RockContext rockContext ) { if ( IsPrivate( entity, action, person ) ) { var authService = new AuthService( rockContext ); // Delete any existing rules in database foreach ( Auth auth in authService .GetAuths( entity.TypeId, entity.Id, action ) ) { authService.Delete( auth ); } // Reload the static dictionary for this action ReloadAction( entity.TypeId, entity.Id, action, rockContext ); } }