/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var service = new RestControllerService(new RockContext()); var sortProperty = gControllers.SortProperty; var qry = service.Queryable().Select(c => new RestControllerModel { Id = c.Id, Name = c.Name, ClassName = c.ClassName, Actions = c.Actions.Count(), ActionsWithPublicCachingHeaders = c.Actions.Count(a => a.CacheControlHeaderSettings != null && a.CacheControlHeaderSettings != "" && a.CacheControlHeaderSettings.Contains("\"RockCacheablityType\":0")) }); if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderBy(c => c.Name); } gControllers.EntityTypeId = EntityTypeCache.Get <RestController>().Id; gControllers.DataSource = qry.ToList(); gControllers.DataBind(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var service = new RestControllerService(new RockContext()); var sortProperty = gControllers.SortProperty; var qry = service.Queryable().Select(c => new { c.Id, c.Name, c.ClassName, Actions = c.Actions.Count() }); if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderBy(c => c.Name); } gControllers.EntityTypeId = EntityTypeCache.Get <RestController>().Id; gControllers.DataSource = qry.ToList(); gControllers.DataBind(); }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs /// </summary> /// <param name="pageReference">The page reference.</param> /// <returns></returns> public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference) { var breadCrumbs = new List <BreadCrumb>(); int controllerId = int.MinValue; if (int.TryParse(PageParameter("Controller"), out controllerId)) { var controller = new RestControllerService(new RockContext()).Get(controllerId); if (controller != null) { string name = controller.Name.SplitCase(); var controllerType = Reflection.FindTypes(typeof(Rock.Rest.ApiControllerBase)) .Where(a => a.Key.Equals(controller.ClassName)).Select(a => a.Value).FirstOrDefault(); if (controllerType != null) { var obsoleteAttribute = controllerType.GetCustomAttribute <System.ObsoleteAttribute>(); if (obsoleteAttribute != null) { hlblWarning.Text = string.Format("Obsolete: {1}", controller.Name.SplitCase(), obsoleteAttribute.Message); } } lControllerName.Text = name + " Controller"; breadCrumbs.Add(new BreadCrumb(name, pageReference)); } } return(breadCrumbs); }
/// <summary> /// Installs the version. /// </summary> /// <returns></returns> /// <exception cref="Rock.Update.Exceptions.PackageNotFoundException">Target Release ${targetRelease} was not found.</exception> public RockRelease InstallVersion() { VersionValidationHelper.ValidateVersionInstall(_targetVersion); var releases = _rockUpdateService.GetReleasesList(_installedVersion); var targetRelease = releases?.Where(r => r.SemanticVersion == _targetVersion.ToString()).FirstOrDefault(); if (targetRelease == null) { throw new PackageNotFoundException($"Target Release ${targetRelease} was not found."); } var targetPackagePath = DownloadPackage(targetRelease); InstallPackage(targetPackagePath); // Record the current version to the database Web.SystemSettings.SetValue(Rock.SystemKey.SystemSetting.ROCK_INSTANCE_ID, _targetVersion.ToString()); // register any new REST controllers try { RestControllerService.RegisterControllers(); } catch (Exception ex) { ExceptionLogService.LogException(ex); } return(targetRelease); }
/// <summary> /// Updates an existing Rock package to the given version and returns true if successful. /// </summary> /// <returns>true if the update was successful; false if errors were encountered</returns> protected bool UpdateRockPackage(string version) { IEnumerable <string> errors = Enumerable.Empty <string>(); try { var update = NuGetService.SourceRepository.FindPackage(_rockPackageId, (version != null) ? SemanticVersion.Parse(version) : null, false, false); var installed = NuGetService.GetInstalledPackage(_rockPackageId); if (installed == null) { errors = NuGetService.InstallPackage(update); } else { errors = NuGetService.UpdatePackage(update); } CheckForManualFileMoves(version); nbSuccess.Text = ConvertToHtmlLiWrappedUl(update.ReleaseNotes).ConvertCrLfToHtmlBr(); lSuccessVersion.Text = update.Title; // Record the current version to the database Rock.Web.SystemSettings.SetValue(SystemSettingKeys.ROCK_INSTANCE_ID, version); // register any new REST controllers try { RestControllerService.RegisterControllers(); } catch (Exception ex) { errors = errors.Concat(new[] { string.Format("The update was installed but there was a problem registering any new REST controllers. ({0})", ex.Message) }); LogException(ex); } } catch (InvalidOperationException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}: {1}", version, ex.Message) }); LogException(ex); } if (errors != null && errors.Count() > 0) { pnlError.Visible = true; nbErrors.Text = errors.Aggregate(new StringBuilder("<ul class='list-padded'>"), (sb, s) => sb.AppendFormat("<li>{0}</li>", s)).Append("</ul>").ToString(); return(false); } else { pnlUpdateSuccess.Visible = true; rptPackageVersions.Visible = false; return(true); } }
private static int LoadByGuid2(Guid guid, RockContext rockContext) { var RestControllerService = new RestControllerService(rockContext); return(RestControllerService .Queryable().AsNoTracking() .Where(c => c.Guid.Equals(guid)) .Select(c => c.Id) .FirstOrDefault()); }
private static int LoadByName2(string className, RockContext rockContext) { var RestControllerService = new RestControllerService(rockContext); return(RestControllerService .Queryable().AsNoTracking() .Where(a => a.ClassName == className) .Select(c => c.Id) .FirstOrDefault()); }
private static RestControllerCache LoadById2(int id, RockContext rockContext) { var RestControllerService = new RestControllerService(rockContext); var RestControllerModel = RestControllerService.Get(id); if (RestControllerModel != null) { return(new RestControllerCache(RestControllerModel)); } return(null); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (!Page.IsPostBack) { var service = new RestControllerService(new RockContext()); if (!service.Queryable().Any()) { RefreshControllerList(); } BindGrid(); } base.OnLoad(e); }
/// <summary> /// Queries the database by id with context. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private static RestControllerCache QueryDbByClassNameWithContext(string className, RockContext rockContext) { var service = new RestControllerService(rockContext); var entity = service.Queryable().AsNoTracking() .FirstOrDefault(a => a.ClassName == className); if (entity == null) { return(null); } var value = new RestControllerCache(); value.SetFromEntity(entity); return(value); }
/// <summary> /// Occurs after the action method is invoked. /// </summary> /// <param name="actionExecutedContext">The action executed context.</param> public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { base.OnActionExecuted(actionExecutedContext); var reflectedHttpActionDescriptor = ( ReflectedHttpActionDescriptor )actionExecutedContext.ActionContext.ActionDescriptor; var actionMethod = actionExecutedContext.Request.Method.Method; var controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor; var apiId = RestControllerService.GetApiId(reflectedHttpActionDescriptor.MethodInfo, actionMethod, controller.ControllerName); var restActionCache = RestActionCache.Get(apiId); if (restActionCache != null && restActionCache.CacheControlHeader.IsNotNullOrWhiteSpace()) { actionExecutedContext.Response.Headers.Add("Cache-Control", restActionCache.CacheControlHeader); } }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs /// </summary> /// <param name="pageReference">The page reference.</param> /// <returns></returns> public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference) { var breadCrumbs = new List <BreadCrumb>(); int controllerId = int.MinValue; if (int.TryParse(PageParameter("controller"), out controllerId)) { var controller = new RestControllerService(new RockContext()).Get(controllerId); if (controller != null) { string name = controller.Name.SplitCase(); lControllerName.Text = name + " Controller"; breadCrumbs.Add(new BreadCrumb(name, pageReference)); } } return(breadCrumbs); }
/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { RestControllerService.RegisterControllers(); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting(HttpActionContext actionContext) { var reflectedHttpActionDescriptor = ( ReflectedHttpActionDescriptor )actionContext.ActionDescriptor; var controller = actionContext.ActionDescriptor.ControllerDescriptor; string controllerClassName = controller.ControllerType.FullName; string actionMethod = actionContext.Request.Method.Method; var apiId = RestControllerService.GetApiId(reflectedHttpActionDescriptor.MethodInfo, actionMethod, controller.ControllerName); ISecured item = RestActionCache.Get(apiId); if (item == null) { // if there isn't a RestAction in the database, use the Controller as the secured item item = RestControllerCache.Get(controllerClassName); if (item == null) { item = new RestController(); } } Person person = null; if (actionContext.Request.Properties.Keys.Contains("Person")) { person = actionContext.Request.Properties["Person"] as Person; } else { var principal = actionContext.Request.GetUserPrincipal(); if (principal != null && principal.Identity != null) { using (var rockContext = new RockContext()) { string userName = principal.Identity.Name; UserLogin userLogin = null; if (userName.StartsWith("rckipid=")) { Rock.Model.PersonService personService = new Model.PersonService(rockContext); Rock.Model.Person impersonatedPerson = personService.GetByImpersonationToken(userName.Substring(8)); if (impersonatedPerson != null) { userLogin = impersonatedPerson.GetImpersonatedUser(); } } else { var userLoginService = new Rock.Model.UserLoginService(rockContext); userLogin = userLoginService.GetByUserName(userName); } if (userLogin != null) { person = userLogin.Person; actionContext.Request.Properties.Add("Person", person); /* 12/12/2019 BJW * * Setting this current person item was only done in put, post, and patch in the ApiController * class. Set it here so that it is always set for all methods, including delete. This enhances * history logging done in the pre and post save model hooks (when the pre-save event is called * we can access DbContext.GetCurrentPersonAlias and log who deleted the record). * * Task: https://app.asana.com/0/1120115219297347/1153140643799337/f */ System.Web.HttpContext.Current.AddOrReplaceItem("CurrentPerson", person); } } } } string action = actionMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) ? Rock.Security.Authorization.VIEW : Rock.Security.Authorization.EDIT; if (!item.IsAuthorized(action, person)) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } }
/// <summary> /// Updates an existing Rock package to the given version and returns true if successful. /// </summary> /// <returns>true if the update was successful; false if errors were encountered</returns> protected bool UpdateRockPackage(string version) { IEnumerable <string> errors = Enumerable.Empty <string>(); try { var update = NuGetService.SourceRepository.FindPackage(_rockPackageId, (version != null) ? SemanticVersion.Parse(version) : null, false, false); var installed = NuGetService.GetInstalledPackage(_rockPackageId); if (installed == null) { errors = NuGetService.InstallPackage(update); } else { errors = NuGetService.UpdatePackageAndBackup(update, installed); } CheckForManualFileMoves(version); nbSuccess.Text = ConvertToHtmlLiWrappedUl(update.ReleaseNotes).ConvertCrLfToHtmlBr(); lSuccessVersion.Text = update.Title; // Record the current version to the database Rock.Web.SystemSettings.SetValue(SystemSettingKeys.ROCK_INSTANCE_ID, version); // register any new REST controllers try { RestControllerService.RegisterControllers(); } catch (Exception ex) { LogException(ex); } } catch (OutOfMemoryException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. It looks like your website ran out of memory. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#outofmemory'>this page for some assistance</a>", version) }); LogException(ex); } catch (System.Xml.XmlException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. It looks one of the standard XML files ({1}) may have been customized which prevented us from updating it. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#customizedxml'>this page for some assistance</a>", version, ex.Message) }); LogException(ex); } catch (System.IO.IOException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. We were not able to replace an important file ({1}) after the update. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#unabletoreplacefile'>this page for some assistance</a>", version, ex.Message) }); LogException(ex); } catch (Exception ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}: {1}", version, ex.Message) }); LogException(ex); } if (errors != null && errors.Count() > 0) { pnlError.Visible = true; nbErrors.Text = errors.Aggregate(new StringBuilder("<ul class='list-padded'>"), (sb, s) => sb.AppendFormat("<li>{0}</li>", s)).Append("</ul>").ToString(); return(false); } else { pnlUpdateSuccess.Visible = true; rptPackageVersions.Visible = false; return(true); } }
public bool EnsureRestControllers() { RestControllerService.RegisterControllers(); return(true); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting(HttpActionContext actionContext) { var principal = actionContext.Request.GetUserPrincipal(); Person person = null; if (principal != null && principal.Identity != null) { using (var rockContext = new RockContext()) { string userName = principal.Identity.Name; UserLogin userLogin = null; if (userName.StartsWith("rckipid=")) { var personService = new PersonService(rockContext); var impersonatedPerson = personService.GetByImpersonationToken(userName.Substring(8)); if (impersonatedPerson != null) { userLogin = impersonatedPerson.GetImpersonatedUser(); } } else { var userLoginService = new UserLoginService(rockContext); userLogin = userLoginService.GetByUserName(userName); } if (userLogin != null) { person = userLogin.Person; var pinAuthentication = AuthenticationContainer.GetComponent(typeof(Security.Authentication.PINAuthentication).FullName); // Don't allow PIN authentications. if (userLogin.EntityTypeId != null) { var userLoginEntityType = EntityTypeCache.Get(userLogin.EntityTypeId.Value); if (userLoginEntityType != null && userLoginEntityType.Id == pinAuthentication.EntityType.Id) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); return; } } } } } var reflectedHttpActionDescriptor = ( ReflectedHttpActionDescriptor )actionContext.ActionDescriptor; var controller = actionContext.ActionDescriptor.ControllerDescriptor; var controllerClassName = controller.ControllerType.FullName; var actionMethod = actionContext.Request.Method.Method; var apiId = RestControllerService.GetApiId(reflectedHttpActionDescriptor.MethodInfo, actionMethod, controller.ControllerName); ISecured item = RestActionCache.Get(apiId); if (item == null) { // if there isn't a RestAction in the database, use the Controller as the secured item item = RestControllerCache.Get(controllerClassName); if (item == null) { item = new RestController(); } } if (actionContext.Request.Properties.Keys.Contains("Person")) { person = actionContext.Request.Properties["Person"] as Person; } else { actionContext.Request.Properties.Add("Person", person); /* 12/12/2019 BJW * * Setting this current person item was only done in put, post, and patch in the ApiController * class. Set it here so that it is always set for all methods, including delete. This enhances * history logging done in the pre and post save model hooks (when the pre-save event is called * we can access DbContext.GetCurrentPersonAlias and log who deleted the record). * * Task: https://app.asana.com/0/1120115219297347/1153140643799337/f */ System.Web.HttpContext.Current.AddOrReplaceItem("CurrentPerson", person); } string action = actionMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) ? Security.Authorization.VIEW : Security.Authorization.EDIT; bool authorized = false; if (item.IsAuthorized(action, person)) { authorized = true; } else if (actionContext.Request.Headers.Contains("X-Rock-App-Id") && actionContext.Request.Headers.Contains("X-Rock-Mobile-Api-Key")) { // Normal authorization failed, but this is a Mobile App request so check // if the application itself has been given permission. var appId = actionContext.Request.Headers.GetValues("X-Rock-App-Id").First().AsIntegerOrNull(); var mobileApiKey = actionContext.Request.Headers.GetValues("X-Rock-Mobile-Api-Key").First(); if (appId.HasValue) { using (var rockContext = new RockContext()) { var appUser = Mobile.MobileHelper.GetMobileApplicationUser(appId.Value, mobileApiKey, rockContext); if (appUser != null && item.IsAuthorized(action, appUser.Person)) { authorized = true; } } } } if (!authorized) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } }
private void RefreshControllerList() { RestControllerService.RegisterControllers(); }
/// <summary> /// Updates an existing Rock package to the given version and returns true if successful. /// </summary> /// <returns>true if the update was successful; false if errors were encountered</returns> protected bool UpdateRockPackage(IPackage update) { IEnumerable <string> errors = Enumerable.Empty <string>(); string version = update.Version.ToString(); try { var field = NuGetService.GetType().GetField("_projectManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); IProjectManager projectManager = ( IProjectManager )field.GetValue(NuGetService); projectManager.UpdatePackageReference(update, false, false); CheckForManualFileMoves(version); lSuccessVersion.Text = GetRockVersion(update.Version); // Record the current version to the database Rock.Web.SystemSettings.SetValue(SystemSettingKeys.ROCK_INSTANCE_ID, version); // register any new REST controllers try { RestControllerService.RegisterControllers(); } catch (Exception ex) { LogException(ex); } } catch (OutOfMemoryException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. It looks like your website ran out of memory. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#outofmemory'>this page for some assistance</a>", version) }); LogException(ex); } catch (System.Xml.XmlException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. It looks one of the standard XML files ({1}) may have been customized which prevented us from updating it. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#customizedxml'>this page for some assistance</a>", version, ex.Message) }); LogException(ex); } catch (System.IO.IOException ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}. We were not able to replace an important file ({1}) after the update. Check out <a href='http://www.rockrms.com/Rock/UpdateIssues#unabletoreplacefile'>this page for some assistance</a>", version, ex.Message) }); LogException(ex); } catch (Exception ex) { errors = errors.Concat(new[] { string.Format("There is a problem installing v{0}: {1}", version, ex.Message) }); LogException(ex); } if (errors != null && errors.Count() > 0) { pnlError.Visible = true; nbErrors.Text = errors.Aggregate(new StringBuilder("<ul class='list-padded'>"), (sb, s) => sb.AppendFormat("<li>{0}</li>", s)).Append("</ul>").ToString(); return(false); } else { pnlUpload.Visible = false; pnlUpdateSuccess.Visible = true; return(true); } }
/// <summary> /// Executes this instance. /// </summary> public void Execute() { RestControllerService.RegisterControllers(); }