public override void OnAuthorization( HttpActionContext actionContext ) { // See if user is logged in var principal = System.Threading.Thread.CurrentPrincipal; if ( principal != null && principal.Identity != null && !String.IsNullOrWhiteSpace(principal.Identity.Name)) { var userLoginService = new UserLoginService(); var user = userLoginService.GetByUserName(principal.Identity.Name); if ( user != null ) { actionContext.Request.SetUserPrincipal( principal ); return; } } // If not, see if there's a valid token string authToken = null; if (actionContext.Request.Headers.Contains("Authorization-Token")) authToken = actionContext.Request.Headers.GetValues( "Authorization-Token" ).FirstOrDefault(); if ( String.IsNullOrWhiteSpace( authToken ) ) { string queryString = actionContext.Request.RequestUri.Query; authToken = System.Web.HttpUtility.ParseQueryString(queryString).Get("apikey"); } if (! String.IsNullOrWhiteSpace( authToken ) ) { var userLoginService = new UserLoginService(); var userLogin = userLoginService.Queryable().Where( u => u.ApiKey == authToken ).FirstOrDefault(); if ( userLogin != null ) { var identity = new GenericIdentity( userLogin.UserName ); principal = new GenericPrincipal(identity, null); actionContext.Request.SetUserPrincipal( principal ); return; } } actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.Unauthorized, "The Rock API requires that requests include either an Authorization-Token, and ApiKey querystring parameter, or are made by a logged-in user" ); }
public override void OnAuthorization( HttpActionContext actionContext ) { // See if user is logged in var principal = System.Threading.Thread.CurrentPrincipal; if ( principal != null && principal.Identity != null && !String.IsNullOrWhiteSpace(principal.Identity.Name)) { //var userLoginService = new UserLoginService(); //var user = userLoginService.GetByUserName(principal.Identity.Name); //if ( user != null ) //{ actionContext.Request.SetUserPrincipal( principal ); return; //} } // If not, see if there's a valid token string authToken = null; if (actionContext.Request.Headers.Contains("Authorization-Token")) authToken = actionContext.Request.Headers.GetValues( "Authorization-Token" ).FirstOrDefault(); if ( String.IsNullOrWhiteSpace( authToken ) ) { string queryString = actionContext.Request.RequestUri.Query; authToken = System.Web.HttpUtility.ParseQueryString(queryString).Get("apikey"); } if (! String.IsNullOrWhiteSpace( authToken ) ) { var userLoginService = new UserLoginService( new Rock.Data.RockContext() ); var userLogin = userLoginService.Queryable().Where( u => u.ApiKey == authToken ).FirstOrDefault(); if ( userLogin != null ) { var identity = new GenericIdentity( userLogin.UserName ); principal = new GenericPrincipal(identity, null); actionContext.Request.SetUserPrincipal( principal ); return; } } }
/// <summary> /// Generates the username. /// </summary> /// <param name="firstName">The first name.</param> /// <param name="lastName">The last name.</param> /// <param name="tryCount">The try count.</param> /// <returns></returns> public static string GenerateUsername( string firstName, string lastName, int tryCount = 0 ) { // create username string username = (firstName.Substring( 0, 1 ) + lastName).ToLower(); if ( tryCount != 0 ) { username = username + tryCount.ToString(); } // check if username exists UserLoginService userService = new UserLoginService( new RockContext() ); var loginExists = userService.Queryable().Where( l => l.UserName == username ).Any(); if ( !loginExists ) { return username; } else { return Database.GenerateUsername( firstName, lastName, tryCount + 1 ); } }
/// <summary> /// Handles the RowDataBound event of the gRestKeyList control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param> protected void gRestKeyList_RowDataBound( object sender, GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.DataRow ) { var rockContext = new RockContext(); var restUser = e.Row.DataItem as Person; var noteService = new NoteService( rockContext ); var description = noteService.Queryable().Where( a => a.EntityId == restUser.Id ).FirstOrDefault(); Label lblDescription = e.Row.FindControl( "lblDescription" ) as Label; if ( description != null ) { lblDescription.Text = description.Text; } var userLoginService = new UserLoginService( rockContext ); var userLogin = userLoginService.Queryable().Where( a => a.PersonId == restUser.Id ).FirstOrDefault(); Label lblKey = e.Row.FindControl( "lblKey" ) as Label; if ( userLogin != null ) { lblKey.Text = userLogin.ApiKey; } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="restUserId">The rest user identifier.</param> public void ShowDetail( int restUserId ) { var rockContext = new RockContext(); Person restUser = null; if ( !restUserId.Equals( 0 ) ) { restUser = new PersonService( rockContext ).Get( restUserId ); } if ( restUser == null ) { restUser = new Person { Id = 0 }; } bool editAllowed = restUser.IsAuthorized( Authorization.EDIT, CurrentPerson ); hfRestUserId.Value = restUser.Id.ToString(); lTitle.Text = ActionTitle.Edit( "REST Key" ).FormatAsHtmlTitle(); if ( restUser.Id > 0 ) { tbName.Text = restUser.LastName; cbActive.Checked = false; var activeStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id; if ( restUser.RecordStatusValueId == activeStatusId ) { cbActive.Checked = true; } var noteService = new NoteService( rockContext ); var description = noteService.Queryable().Where( a => a.EntityId == restUser.Id ).FirstOrDefault(); if ( description != null ) { tbDescription.Text = description.Text; } var userLoginService = new UserLoginService( rockContext ); var userLogin = userLoginService.Queryable().Where( a => a.PersonId == restUser.Id ).FirstOrDefault(); if ( userLogin != null ) { tbKey.Text = userLogin.ApiKey; } } }
/// <summary> /// Handles the Click event of the lbSave 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 lbSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var userLoginService = new UserLoginService( rockContext ); var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault(); if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) ) { // this key already exists in the database. Show the error and get out of here. nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. "; nbWarningMessage.Visible = true; return; } rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var restUser = new Person(); if ( int.Parse( hfRestUserId.Value ) != 0 ) { restUser = personService.Get( int.Parse( hfRestUserId.Value ) ); } else { personService.Add( restUser ); rockContext.SaveChanges(); restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } ); } // the rest user name gets saved as the last name on a person History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text ); restUser.LastName = tbName.Text; restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id; if ( cbActive.Checked ) { restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id; } else { restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id; } if ( restUser.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), restUser.Id, changes ); } } } // the description gets saved as a system note for the person var noteType = new NoteTypeService( rockContext ) .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() ); var noteService = new NoteService( rockContext ); var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault(); if ( note == null ) { note = new Note(); noteService.Add( note ); } note.NoteTypeId = noteType.Id; note.EntityId = restUser.Id; note.Text = tbDescription.Text; rockContext.SaveChanges(); // the key gets saved in the api key field of a user login (which you have to create if needed) var entityType = new EntityTypeService( rockContext ) .Get( "Rock.Security.Authentication.Database" ); userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault(); if ( userLogin == null ) { userLogin = new UserLogin(); userLoginService.Add( userLogin ); } if ( string.IsNullOrWhiteSpace( userLogin.UserName ) ) { userLogin.UserName = Guid.NewGuid().ToString(); } userLogin.IsConfirmed = true; userLogin.ApiKey = tbKey.Text; userLogin.PersonId = restUser.Id; userLogin.EntityTypeId = entityType.Id; rockContext.SaveChanges(); } ); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the lbGenerate 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 lbGenerate_Click( object sender, EventArgs e ) { // Generate a unique random 12 digit api key var rockContext = new RockContext(); var userLoginService = new UserLoginService( rockContext ); var key = string.Empty; var isGoodKey = false; while ( isGoodKey == false ) { key = GenerateKey(); var userLogins = userLoginService.Queryable().Where( a => a.ApiKey == key ); if ( userLogins.Count() == 0 ) { // no other user login has this key. isGoodKey = true; } } tbKey.Text = key; }
/// <summary> /// Executes this instance. /// </summary> public void Execute() { using ( var rockContext = new RockContext() ) { var relationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); if ( relationshipGroupType != null ) { var ownerRole = relationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .FirstOrDefault(); var friendRole = relationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_FACEBOOK_FRIEND.AsGuid() ) ) .FirstOrDefault(); if ( ownerRole != null && friendRole != null ) { var userLoginService = new UserLoginService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); // Convert list of facebook ids into list of usernames var friendUserNames = FacebookIds.Select( i => "FACEBOOK_" + i ).ToList(); // Get the list of person ids associated with friends usernames var friendPersonIds = userLoginService.Queryable() .Where( l => l.PersonId.HasValue && l.PersonId != PersonId && friendUserNames.Contains( l.UserName ) ) .Select( l => l.PersonId.Value ) .Distinct() .ToList(); // Get the person's group id var personGroup = groupMemberService.Queryable() .Where( m => m.PersonId == PersonId && m.GroupRoleId == ownerRole.Id && m.Group.GroupTypeId == relationshipGroupType.Id ) .Select( m => m.Group ) .FirstOrDefault(); // Verify that a 'known relationships' type group existed for the person, if not create it if ( personGroup == null ) { var groupMember = new GroupMember(); groupMember.PersonId = PersonId; groupMember.GroupRoleId = ownerRole.Id; personGroup = new Group(); personGroup.Name = relationshipGroupType.Name; personGroup.GroupTypeId = relationshipGroupType.Id; personGroup.Members.Add( groupMember ); var groupService = new GroupService( rockContext ); groupService.Add( personGroup ); rockContext.SaveChanges(); } // Get the person's relationship group id var personGroupId = personGroup.Id; // Get all of the friend's relationship group ids var friendGroupIds = groupMemberService.Queryable() .Where( m => m.Group.GroupTypeId == relationshipGroupType.Id && m.GroupRoleId == ownerRole.Id && friendPersonIds.Contains( m.PersonId ) ) .Select( m => m.GroupId ) .Distinct() .ToList(); // Find all the existing friend relationships in Rock ( both directions ) var existingFriends = groupMemberService.Queryable() .Where( m => m.Group.GroupTypeId == relationshipGroupType.Id && ( ( friendPersonIds.Contains( m.PersonId ) && m.GroupId == personGroupId ) || ( m.PersonId == PersonId && m.GroupId != personGroupId ) ) ) .ToList(); // Create temp group members for current Facebook friends var currentFriends = new List<GroupMember>(); // ( Person > Friend ) foreach ( int personId in friendPersonIds ) { var groupMember = new GroupMember(); groupMember.GroupId = personGroupId; groupMember.PersonId = personId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add( groupMember ); } // ( Friend > Person ) foreach ( int familyId in friendGroupIds ) { var groupMember = new GroupMember(); groupMember.GroupId = familyId; groupMember.PersonId = PersonId; groupMember.GroupRoleId = friendRole.Id; groupMember.GroupMemberStatus = GroupMemberStatus.Active; currentFriends.Add( groupMember ); } // Add any current friends that do not exist in Rock yet foreach ( var groupMember in currentFriends .Where( f => !existingFriends.Any( e => e.IsEqualTo( f ) ) ) ) { groupMemberService.Add( groupMember ); } // Delete any existing friends that are no longer facebook friends foreach ( var groupMember in existingFriends .Where( f => !currentFriends.Any( e => e.IsEqualTo( f ) ) ) ) { groupMemberService.Delete( groupMember ); } rockContext.SaveChanges(); } } } }
/// <summary> /// Adds the call back. /// </summary> private void MarkOnlineUsersOffline() { var rockContext = new RockContext(); var userLoginService = new UserLoginService( rockContext ); foreach ( var user in userLoginService.Queryable().Where( u => u.IsOnLine == true ) ) { user.IsOnLine = false; } rockContext.SaveChanges(); }
/// <summary> /// Adds the user login. /// </summary> /// <param name="authProviderEntityTypeId">The id of the auth provider entity type.</param> /// <param name="person">The person.</param> /// <param name="value">The value, probably an email.</param> protected static void AddUserLogin( int? authProviderEntityTypeId, Person person, string value ) { // Make sure we can create a valid userlogin if ( !authProviderEntityTypeId.HasValue || string.IsNullOrWhiteSpace( value ) ) { return; } var rockContext = new RockContext(); var userLoginService = new UserLoginService( rockContext ); // Check for an existing userlogin, must be unique for the DB if ( userLoginService.Queryable().Any( u => u.UserName == value ) ) { return; } var userLogin = new UserLogin(); userLogin.UserName = value.Trim(); userLogin.CreatedDateTime = ImportDateTime; userLogin.CreatedByPersonAliasId = ImportPersonAliasId; userLogin.EntityTypeId = authProviderEntityTypeId.Value; userLogin.PersonId = person.Id; rockContext.UserLogins.Add( userLogin ); rockContext.SaveChanges( DisableAuditing ); }
/// <summary> /// Maps the users. /// </summary> /// <param name="tableData">The table data.</param> public void MapUsers( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); var personService = new PersonService( lookupContext ); int rockAuthenticatedTypeId = EntityTypeCache.Read( "Rock.Security.Authentication.Database" ).Id; int staffGroupId = new GroupService( lookupContext ).GetByGuid( new Guid( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS ) ).Id; int memberGroupRoleId = new GroupTypeRoleService( lookupContext ).Queryable() .Where( r => r.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_SECURITY_GROUP_MEMBER ) ) ) .Select( r => r.Id ).FirstOrDefault(); var userLoginService = new UserLoginService( lookupContext ); var importedUserCount = userLoginService.Queryable().Count( u => u.ForeignId != null ); var allUsers = userLoginService.Queryable().AsNoTracking() .ToDictionary( t => t.UserName.ToLower().Trim(), t => t.PersonId ); var newUserLogins = new List<UserLogin>(); var newStaffMembers = new List<GroupMember>(); var updatedPersonList = new List<Person>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying user import ({0:N0} found, {1:N0} already exist).", totalRows, importedUserCount ) ); foreach ( var row in tableData.Where( r => r != null ) ) { int? individualId = row["LinkedIndividualID"] as int?; string userName = row["UserLogin"] as string; int? userId = row["UserID"] as int?; if ( userId != null && individualId != null && !string.IsNullOrWhiteSpace( userName ) && !allUsers.ContainsKey( userName.ToLower().Trim() ) ) { var personKeys = GetPersonKeys( individualId, null ); if ( personKeys != null ) { DateTime? createdDate = row["UserCreatedDate"] as DateTime?; string userEmail = row["UserEmail"] as string; string userTitle = row["UserTitle"] as string; string userPhone = row["UserPhone"] as string; bool? isEnabled = row["IsUserEnabled"] as bool?; Boolean? isStaff = row["IsStaff"] as Boolean?; bool isActive = isEnabled ?? false; var user = new UserLogin(); user.CreatedDateTime = createdDate; user.CreatedByPersonAliasId = ImportPersonAliasId; user.EntityTypeId = rockAuthenticatedTypeId; user.IsConfirmed = isEnabled; user.UserName = userName.Trim(); user.PersonId = personKeys.PersonId; user.ForeignKey = userId.ToString(); user.ForeignId = userId; if ( isStaff == true ) { // add this user to the staff group var staffMember = new GroupMember(); staffMember.GroupId = staffGroupId; staffMember.PersonId = personKeys.PersonId; staffMember.GroupRoleId = memberGroupRoleId; staffMember.CreatedDateTime = createdDate; staffMember.CreatedByPersonAliasId = ImportPersonAliasId; staffMember.GroupMemberStatus = isActive ? GroupMemberStatus.Active : GroupMemberStatus.Inactive; newStaffMembers.Add( staffMember ); } // set user login email to person's primary email if one isn't set if ( !string.IsNullOrWhiteSpace( userEmail ) && userEmail.IsEmail() ) { Person person = null; if ( !updatedPersonList.Any( p => p.Id == personKeys.PersonId ) ) { person = personService.Queryable( includeDeceased: true ).FirstOrDefault( p => p.Id == personKeys.PersonId ); } else { person = updatedPersonList.FirstOrDefault( p => p.Id == personKeys.PersonId ); } if ( person != null && string.IsNullOrWhiteSpace( person.Email ) ) { person.Email = userEmail.Left( 75 ); person.IsEmailActive = (bool)( isEnabled ?? true ); person.EmailPreference = EmailPreference.EmailAllowed; person.EmailNote = userTitle; lookupContext.SaveChanges( DisableAuditing ); updatedPersonList.Add( person ); } } // other Attributes to save? // UserBio // DepartmentName // IsPastor newUserLogins.Add( user ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} users imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { SaveUsers( newUserLogins, newStaffMembers ); updatedPersonList.Clear(); newUserLogins.Clear(); newStaffMembers.Clear(); ReportPartialProgress(); } } } else { LogException( "User Import", string.Format( "User: {0} - UserName: {1} is not linked to a person or already exists.", userId, userName ) ); } } if ( newUserLogins.Any() ) { SaveUsers( newUserLogins, newStaffMembers ); } ReportProgress( 100, string.Format( "Finished user import: {0:N0} users imported.", completed ) ); }
/// <summary> /// Job that executes routine Rock cleanup tasks /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute( IJobExecutionContext context ) { var rockContext = new Rock.Data.RockContext(); // get the job map JobDataMap dataMap = context.JobDetail.JobDataMap; // delete accounts that have not been confirmed in X hours int? userExpireHours = dataMap.GetString( "HoursKeepUnconfirmedAccounts" ).AsIntegerOrNull(); if ( userExpireHours.HasValue ) { DateTime userAccountExpireDate = RockDateTime.Now.Add( new TimeSpan( userExpireHours.Value * -1, 0, 0 ) ); var userLoginService = new UserLoginService(rockContext); foreach ( var user in userLoginService.Queryable().Where( u => u.IsConfirmed == false && ( u.CreatedDateTime ?? DateTime.MinValue ) < userAccountExpireDate ).ToList() ) { userLoginService.Delete( user ); } rockContext.SaveChanges(); } // purge exception log int? exceptionExpireDays = dataMap.GetString( "DaysKeepExceptions" ).AsIntegerOrNull(); if ( exceptionExpireDays.HasValue ) { DateTime exceptionExpireDate = RockDateTime.Now.Add( new TimeSpan( exceptionExpireDays.Value * -1, 0, 0, 0 ) ); ExceptionLogService exceptionLogService = new ExceptionLogService( rockContext ); foreach ( var exception in exceptionLogService.Queryable().Where( e => e.CreatedDateTime.HasValue && e.CreatedDateTime < exceptionExpireDate ).ToList() ) { exceptionLogService.Delete( exception ); } rockContext.SaveChanges(); } // purge audit log int? auditExpireDays = dataMap.GetString( "AuditLogExpirationDays" ).AsIntegerOrNull(); if ( auditExpireDays.HasValue ) { DateTime auditExpireDate = RockDateTime.Now.Add( new TimeSpan( auditExpireDays.Value * -1, 0, 0, 0 ) ); AuditService auditService = new AuditService(rockContext); foreach ( var audit in auditService.Queryable().Where( a => a.DateTime < auditExpireDate ).ToList() ) { auditService.Delete( audit ); } rockContext.SaveChanges(); } // clean the cached file directory // get the attributes string cacheDirectoryPath = dataMap.GetString( "BaseCacheDirectory" ); int? cacheExpirationDays = dataMap.GetString( "DaysKeepCachedFiles" ).AsIntegerOrNull(); if ( cacheExpirationDays.HasValue ) { DateTime cacheExpirationDate = RockDateTime.Now.Add( new TimeSpan( cacheExpirationDays.Value * -1, 0, 0, 0 ) ); // if job is being run by the IIS scheduler and path is not null if ( context.Scheduler.SchedulerName == "RockSchedulerIIS" && !string.IsNullOrEmpty( cacheDirectoryPath ) ) { // get the physical path of the cache directory cacheDirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath( cacheDirectoryPath ); } // if directory is not blank and cache expiration date not in the future if ( !string.IsNullOrEmpty( cacheDirectoryPath ) && cacheExpirationDate <= RockDateTime.Now ) { // Clean cache directory CleanCacheDirectory( cacheDirectoryPath, cacheExpirationDate ); } } // clean out any temporary binary files BinaryFileService binaryFileService = new BinaryFileService(rockContext); foreach ( var binaryFile in binaryFileService.Queryable().Where( bf => bf.IsTemporary == true ).ToList() ) { if ( binaryFile.ModifiedDateTime < RockDateTime.Now.AddDays( -1 ) ) { binaryFileService.Delete( binaryFile ); } } rockContext.SaveChanges(); // Add any missing person aliases PersonService personService = new PersonService(rockContext); foreach ( var person in personService.Queryable( "Aliases" ) .Where( p => !p.Aliases.Any() ) .Take( 300 ) ) { person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } ); } rockContext.SaveChanges(); // Add any missing metaphones int namesToProcess = dataMap.GetString( "MaxMetaphoneNames" ).AsInteger(); if ( namesToProcess > 0 ) { var firstNameQry = personService.Queryable().Select( p => p.FirstName ); var nickNameQry = personService.Queryable().Select( p => p.NickName ); var lastNameQry = personService.Queryable().Select( p => p.LastName ); var nameQry = firstNameQry.Union( nickNameQry.Union( lastNameQry ) ); var metaphones = rockContext.Metaphones; var existingNames = metaphones.Select( m => m.Name ).Distinct(); // Get the names that have not yet been processed var namesToUpdate = nameQry .Where( n => !existingNames.Contains( n ) ) .Take( namesToProcess ) .ToList(); foreach ( string name in namesToUpdate ) { string mp1 = string.Empty; string mp2 = string.Empty; Rock.Utility.DoubleMetaphone.doubleMetaphone( name, ref mp1, ref mp2 ); var metaphone = new Metaphone(); metaphone.Name = name; metaphone.Metaphone1 = mp1; metaphone.Metaphone2 = mp2; metaphones.Add( metaphone ); } rockContext.SaveChanges(); } }
/// <summary> /// Job that executes routine Rock cleanup tasks /// /// Called by the <see cref="IScheduler" /> when a /// <see cref="ITrigger" /> fires that is associated with /// the <see cref="IJob" />. /// </summary> public virtual void Execute(IJobExecutionContext context) { // get the job map JobDataMap dataMap = context.JobDetail.JobDataMap; // delete accounts that have not been confirmed in X hours int userExpireHours = Int32.Parse( dataMap.GetString( "HoursKeepUnconfirmedAccounts" ) ); DateTime userAccountExpireDate = DateTime.Now.Add( new TimeSpan( userExpireHours * -1,0,0 ) ); var userLoginService = new UserLoginService(); foreach (var user in userLoginService.Queryable().Where(u => u.IsConfirmed == false && u.CreationDateTime < userAccountExpireDate).ToList() ) { userLoginService.Delete( user, null ); userLoginService.Save( user, null ); } // purge exception log int exceptionExpireDays = Int32.Parse( dataMap.GetString( "DaysKeepExceptions" ) ); DateTime exceptionExpireDate = DateTime.Now.Add( new TimeSpan( exceptionExpireDays * -1, 0, 0, 0 ) ); ExceptionLogService exceptionLogService = new ExceptionLogService(); foreach ( var exception in exceptionLogService.Queryable().Where( e => e.ExceptionDateTime < exceptionExpireDate ).ToList() ) { exceptionLogService.Delete( exception, null ); exceptionLogService.Save( exception, null ); } // purge audit log int auditExpireDays = Int32.Parse( dataMap.GetString( "AuditLogExpirationDays" ) ); DateTime auditExpireDate = DateTime.Now.Add( new TimeSpan( auditExpireDays * -1, 0, 0, 0 ) ); AuditService auditService = new AuditService(); foreach( var audit in auditService.Queryable().Where( a => a.DateTime < auditExpireDate ).ToList() ) { auditService.Delete( audit, null ); auditService.Save( audit, null ); } // clean the cached file directory //get the attributes string cacheDirectoryPath = dataMap.GetString( "BaseCacheDirectory" ); int cacheExpirationDays = int.Parse( dataMap.GetString( "DaysKeepCachedFiles" ) ); DateTime cacheExpirationDate = DateTime.Now.Add( new TimeSpan( cacheExpirationDays * -1, 0, 0, 0 ) ); //if job is being run by the IIS scheduler and path is not null if ( context.Scheduler.SchedulerName == "RockSchedulerIIS" && !String.IsNullOrEmpty( cacheDirectoryPath ) ) { //get the physical path of the cache directory cacheDirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath( cacheDirectoryPath ); } //if directory is not blank and cache expiration date not in the future if ( !String.IsNullOrEmpty( cacheDirectoryPath ) && cacheExpirationDate <= DateTime.Now ) { //Clean cache directory CleanCacheDirectory( cacheDirectoryPath, cacheExpirationDate ); } // clean out any temporary binary files BinaryFileService binaryFileService = new BinaryFileService(); foreach( var binaryFile in binaryFileService.Queryable().Where( bf => bf.IsTemporary == true ).ToList() ) { if ( binaryFile.LastModifiedDateTime < DateTime.Now.AddDays(-1) ) { binaryFileService.Delete( binaryFile, null ); binaryFileService.Save( binaryFile, null ); } } }
/// <summary> /// This will pull the api key generated in rock. The name of it needs to be AppRestKey. /// It can be changed whenever from the website, this function will pull it based on the name in case the key becomes compromised /// if it can't find it, it will return empty string and the request will return unauthorized /// </summary> /// <returns></returns> public static string APIKey() { var rc = new RockContext(); var u = new PersonService(rc).GetByFullName("AppRestKey", false); var key = ""; if (u.Count() > 0) { var restUser = u.First(); var userLoginService = new UserLoginService(rc); var userLogin = userLoginService.Queryable().Where(a => a.PersonId == restUser.Id).FirstOrDefault(); if (userLogin != null) { key = userLogin.ApiKey; } } return key; }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> /// <exception cref="WebFaultException">Must be logged in</exception> public virtual void ProcessRequest( HttpContext context ) { if ( !context.User.Identity.IsAuthenticated ) { // If not, see if there's a valid token string authToken = context.Request.Headers["Authorization-Token"]; if ( string.IsNullOrWhiteSpace( authToken ) ) { authToken = context.Request.Params["apikey"]; } if (!string.IsNullOrWhiteSpace(authToken)) { var userLoginService = new UserLoginService( new Rock.Data.RockContext() ); var userLogin = userLoginService.Queryable().Where( u => u.ApiKey == authToken ).FirstOrDefault(); if ( userLogin != null ) { var identity = new GenericIdentity( userLogin.UserName ); var principal = new GenericPrincipal( identity, null ); context.User = principal; } } } var currentUser = UserLoginService.GetCurrentUser(); Person currentPerson = currentUser != null ? currentUser.Person : null; if ( !context.User.Identity.IsAuthenticated ) { throw new Rock.Web.FileUploadException( "Must be logged in", System.Net.HttpStatusCode.Forbidden ); } try { HttpFileCollection hfc = context.Request.Files; HttpPostedFile uploadedFile = hfc.AllKeys.Select( fk => hfc[fk] ).FirstOrDefault(); // No file or no data? No good. if ( uploadedFile == null || uploadedFile.ContentLength == 0 ) { throw new Rock.Web.FileUploadException( "No File Specified", System.Net.HttpStatusCode.BadRequest ); } // Check to see if this is a BinaryFileType/BinaryFile or just a plain content file bool isBinaryFile = context.Request.QueryString["isBinaryFile"].AsBoolean(); if ( isBinaryFile ) { ProcessBinaryFile( context, uploadedFile ); } else { ProcessContentFile( context, uploadedFile ); } } catch ( Rock.Web.FileUploadException fex ) { ExceptionLogService.LogException( fex, context ); context.Response.StatusCode = (int)fex.StatusCode; context.Response.Write( "error: " + fex.Detail ); } catch ( Exception ex ) { ExceptionLogService.LogException( ex, context ); context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; context.Response.Write( "error: " + ex.Message ); } }