Пример #1
0
        /// <summary>
        /// Handles the OnFormatDataValue event of the CallbackField control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="CallbackField.CallbackEventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void FormatGridDataValue(object sender, CallbackField.CallbackEventArgs e)
        {
            var fakePerson = new Rock.Model.Person();

            fakePerson.GraduationYear = e.DataValue as int?;
            e.FormattedValue          = fakePerson.GradeFormatted;
        }
Пример #2
0
        /// <summary>
        /// Binds the attribute to attribute value container
        /// </summary>
        private void BindAttribute(Rock.Model.Person person)
        {
            var adultCategoryGuid = GetAttributeValue(AttributeKey.AdultAttributeCategory).AsGuidOrNull();
            var childCategoryGuid = GetAttributeValue(AttributeKey.ChildAttributeCategory).AsGuidOrNull();
            var isAdult           = person.AgeClassification == AgeClassification.Adult || person.AgeClassification == AgeClassification.Unknown;
            var isChild           = person.AgeClassification == AgeClassification.Child || person.AgeClassification == AgeClassification.Unknown;

            pnlAdultFields.Visible = false;
            pnlChildFields.Visible = false;
            if (isAdult && adultCategoryGuid.HasValue)
            {
                avcAdultAttributes.IncludedCategoryNames = new string[] { CategoryCache.Get(adultCategoryGuid.Value).Name };
                avcAdultAttributes.AddDisplayControls(person);

                pnlAdultFields.Visible = avcAdultAttributes.GetDisplayedAttributes().Any();
            }

            if (isChild && childCategoryGuid.HasValue)
            {
                avcChildAttributes.IncludedCategoryNames = new string[] { CategoryCache.Get(childCategoryGuid.Value).Name };
                avcChildAttributes.AddDisplayControls(person);

                pnlChildFields.Visible = avcChildAttributes.GetDisplayedAttributes().Any();
            }
        }
Пример #3
0
        /// <summary>
        /// Gets the related person URL.
        /// </summary>
        private string GetRelatedPersonUrl(Rock.Model.Person currentPerson, Guid relatedPersonGuid, int relatedPersonId)
        {
            var queryParams = new Dictionary <string, string>();

            queryParams.Add(PageParameterKey.PersonGuid, relatedPersonGuid.ToString());

            return(LinkedPageUrl(AttributeKey.PersonProfilePage, queryParams));
        }
Пример #4
0
        /// <summary>
        /// Gets the grid field.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override System.Web.UI.WebControls.DataControlField GetGridField(Type entityType, string selection)
        {
            Guid?phoneType         = null;
            bool enableOrigination = false;

            if (_currentPerson == null)
            {
                if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CurrentPerson"))
                {
                    _currentPerson = HttpContext.Current.Items["CurrentPerson"] as Rock.Model.Person;
                }
            }

            var selectionParts = selection.Split('|');

            if (selectionParts.Length > 0)
            {
                phoneType = selectionParts[0].AsGuidOrNull();
            }

            if (selectionParts.Length > 1)
            {
                enableOrigination = selectionParts[1].AsBoolean();
            }

            var callbackField = new CallbackField();

            callbackField.OnFormatDataValue += (sender, e) =>
            {
                var phoneNumber = e.DataValue as PhoneNumber;
                if (phoneNumber != null)
                {
                    if (enableOrigination)
                    {
                        if (_currentPerson == null)
                        {
                            e.FormattedValue = phoneNumber.NumberFormatted;
                            return;
                        }

                        var jsScript = string.Format("javascript: Rock.controls.pbx.originate('{0}', '{1}', '{2}','{3}','{4}');", _currentPerson.Guid, phoneNumber.Number, _currentPerson.FullName, "", phoneNumber.ToString());

                        e.FormattedValue = string.Format("<a class='originate-call js-originate-call' href=\"{0}\">{1}</a>", jsScript, phoneNumber.NumberFormatted);
                    }
                    else
                    {
                        e.FormattedValue = phoneNumber.NumberFormatted;
                    }
                }
                else
                {
                    e.FormattedValue = string.Empty;
                    return;
                }
            };

            return(callbackField);
        }
Пример #5
0
        /// <summary>
        /// Gets the related person URL.
        /// </summary>
        private string GetRelatedPersonUrl(Rock.Model.Person currentPerson, Guid relatedPersonGuid, int relatedPersonId)
        {
            var template         = "{0}={1}";
            var relatedPersonUrl = Request.UrlProxySafe().ToString()
                                   .ReplaceCaseInsensitive(string.Format(template, PageParameterKey.PersonGuid, currentPerson.Guid), string.Format(template, PageParameterKey.PersonGuid, relatedPersonGuid))
                                   .ReplaceCaseInsensitive(string.Format(template, PageParameterKey.PersonId, currentPerson.Id), string.Format(template, PageParameterKey.PersonId, relatedPersonId));

            return(relatedPersonUrl);
        }
Пример #6
0
 /// <summary>
 /// Sets the value.
 /// </summary>
 /// <param name="person">The person.</param>
 public void SetValue(Rock.Model.Person person)
 {
     if (person != null)
     {
         PersonId   = person.Id;
         PersonName = person.FullName;
     }
     else
     {
         PersonId   = Rock.Constants.None.Id;
         PersonName = Rock.Constants.None.TextHtml;
     }
 }
Пример #7
0
        /// <summary>
        ///   <c>true</c> or <c>false</c> value of whether the page can be displayed in a navigation menu
        /// based on the <see cref="DisplayInNavWhen" /> property value and the security of the currently logged in user
        /// </summary>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public bool DisplayInNav(Rock.Model.Person person)
        {
            switch (this.DisplayInNavWhen)
            {
            case Model.DisplayInNavWhen.Always:
                return(true);

            case Model.DisplayInNavWhen.WhenAllowed:
                return(this.IsAuthorized("View", person));

            default:
                return(false);
            }
        }
Пример #8
0
        private XElement MenuXmlElement(int levelsDeep, Rock.Model.Person person)
        {
            if (levelsDeep >= 0 && this.DisplayInNav(person))
            {
                string iconUrl = string.Empty;
                if (this.IconFileId.HasValue)
                {
                    iconUrl = string.Format("{0}/image.ashx?{1}",
                                            HttpContext.Current.Request.ApplicationPath,
                                            this.IconFileId.Value);
                }

                XElement pageElement = new XElement("page",
                                                    new XAttribute("id", this.Id),
                                                    new XAttribute("title", this.Title ?? this.Name),
                                                    new XAttribute("url", this.Url),
                                                    new XAttribute("display-description", this.MenuDisplayDescription.ToString().ToLower()),
                                                    new XAttribute("display-icon", this.MenuDisplayIcon.ToString().ToLower()),
                                                    new XAttribute("display-child-pages", this.MenuDisplayChildPages.ToString().ToLower()),
                                                    new XElement("description", this.Description ?? ""),
                                                    new XElement("icon-url", iconUrl));

                XElement childPagesElement = new XElement("pages");

                pageElement.Add(childPagesElement);

                if (levelsDeep > 0 && this.MenuDisplayChildPages)
                {
                    foreach (PageCache page in Pages)
                    {
                        XElement childPageElement = page.MenuXmlElement(levelsDeep - 1, person);
                        if (childPageElement != null)
                        {
                            childPagesElement.Add(childPageElement);
                        }
                    }
                }

                return(pageElement);
            }
            else
            {
                return(null);
            }
        }
Пример #9
0
        /// <summary>
        /// Returns the Person sending the SMS communication.
        /// Will use the Response Recipient if one exists otherwise the Current Person.
        /// </summary>
        /// <returns></returns>
        public Rock.Model.Person GetSMSFromPerson()
        {
            // Try to get a from person
            Rock.Model.Person person = CurrentPerson;

            // If the response recipient exists use it
            var fromPersonAliasGuid = FromNumber.GetAttributeValue("ResponseRecipient").AsGuidOrNull();

            if (fromPersonAliasGuid.HasValue)
            {
                person = new Rock.Model.PersonAliasService(new Data.RockContext())
                         .Queryable()
                         .AsNoTracking()
                         .Where(p => p.Guid.Equals(fromPersonAliasGuid.Value))
                         .Select(p => p.Person)
                         .FirstOrDefault();
            }

            return(person);
        }
Пример #10
0
        private void UpdatePersonPhoto(Rock.Model.Person person, MemoryStream photoData)
        {
            RockContext   rockContext   = new RockContext();
            PersonService personService = new PersonService(rockContext);

            person = personService.Get(person.Id);


            var binaryFileType = new BinaryFileTypeService(rockContext).GetNoTracking(Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid());

            var fileName = person.FullName.RemoveSpaces().MakeValidFileName();

            if (fileName.IsNullOrWhiteSpace())
            {
                fileName = "PersonPhoto";
            }

            var binaryFile = new BinaryFile()
            {
                FileName         = fileName,
                MimeType         = "image/jpeg",
                BinaryFileTypeId = binaryFileType.Id,
                IsTemporary      = false
            };

            binaryFile.SetStorageEntityTypeId(binaryFileType.StorageEntityTypeId);

            byte[] photoDataBytes = photoData.ToArray();
            binaryFile.FileSize      = photoDataBytes.Length;
            binaryFile.ContentStream = new MemoryStream(photoDataBytes);

            var binaryFileService = new BinaryFileService(rockContext);

            binaryFileService.Add(binaryFile);
            rockContext.SaveChanges();

            person.PhotoId = binaryFile.Id;

            rockContext.SaveChanges();
        }
Пример #11
0
        public async Task <bool> UpdatePhoto(Rock.Model.Person person, BinaryFile binaryFile)
        {
            //Microsoft face doesn't do well with jumbo images
            //Send them a half size image instead
            bool isLargeImage = false;

            if (binaryFile.Width.HasValue && binaryFile.Width.Value > 2000)
            {
                isLargeImage = true;
            }
            //for debugging
            var url = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot")
                      .EnsureTrailingForwardslash()
                      + "/GetImage.ashx?Guid=" + binaryFile.Guid.ToString();

            if (isLargeImage)
            {
                url = url + "&w=" + (binaryFile.Width.Value / 2).ToString();
            }

            var detectedFace = await DetectFace(url);

            if (detectedFace == null)
            {
                return(false);
            }

            var stream = CropDetectedFace(detectedFace, binaryFile.ContentStream, isLargeImage);

            UpdatePersonPhoto(person, stream);

            stream.Dispose();


            return(true);
        }
Пример #12
0
        /// <summary>
        /// Gets the currently logged in Person
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        protected virtual Rock.Model.Person GetPerson(RockContext rockContext)
        {
            if (Request.Properties.Keys.Contains("Person"))
            {
                return(Request.Properties["Person"] as Person);
            }

            var principal = ControllerContext.Request.GetUserPrincipal();

            if (principal != null && principal.Identity != null)
            {
                if (principal.Identity.Name.StartsWith("rckipid="))
                {
                    var personService = new Model.PersonService(rockContext ?? new RockContext());
                    Rock.Model.Person impersonatedPerson = personService.GetByImpersonationToken(principal.Identity.Name.Substring(8), false, null);
                    if (impersonatedPerson != null)
                    {
                        return(impersonatedPerson);
                    }
                }
                else
                {
                    var userLoginService = new Rock.Model.UserLoginService(rockContext ?? new RockContext());
                    var userLogin        = userLoginService.GetByUserName(principal.Identity.Name);

                    if (userLogin != null)
                    {
                        var person = userLogin.Person;
                        Request.Properties.Add("Person", person);
                        return(userLogin.Person);
                    }
                }
            }

            return(null);
        }
Пример #13
0
 /// <summary>
 /// Handles the OnFormatDataValue event of the CallbackField control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="CallbackField.CallbackEventArgs"/> instance containing the event data.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 protected void FormatGridDataValue( object sender, CallbackField.CallbackEventArgs e )
 {
     var fakePerson = new Rock.Model.Person();
     fakePerson.GraduationYear = e.DataValue as int?;
     e.FormattedValue = fakePerson.GradeFormatted;
 }
Пример #14
0
 public static Group SaveNewFamily(RockContext rockContext, Person person, int?campusId, bool savePersonAttributes)
 {
     return(PersonService.SaveNewPerson(person, rockContext, campusId, savePersonAttributes));
 }
Пример #15
0
 public static bool Authorized(ISecured entity, string action, Rock.Model.Person person, RockContext rockContext)
 {
     return(Authorized(entity, action, person));
 }
Пример #16
0
        /// <summary>
        /// Returns XML for a page menu.
        /// </summary>
        /// <param name="levelsDeep">The page levels deep.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public XDocument MenuXml(int levelsDeep, Rock.Model.Person person)
        {
            XElement menuElement = MenuXmlElement(levelsDeep, person);

            return(new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), menuElement));
        }
Пример #17
0
 /// <summary>
 /// Converts the model to a view model.
 /// </summary>
 /// <param name="model">The entity.</param>
 /// <param name="currentPerson">The current person.</param>
 /// <param name="loadAttributes">if set to <c>true</c> [load attributes].</param>
 /// <returns></returns>
 public override Rock.ViewModel.InteractionDeviceTypeViewModel CreateViewModel(InteractionDeviceType model, Person currentPerson = null, bool loadAttributes = true)
 {
     if (model == null)
     {
         return(default);
Пример #18
0
 /// <summary>
 /// Converts the model to a view model.
 /// </summary>
 /// <param name="model">The entity.</param>
 /// <param name="currentPerson">The current person.</param>
 /// <param name="loadAttributes">if set to <c>true</c> [load attributes].</param>
 /// <returns></returns>
 public override Rock.ViewModel.GroupTypeViewModel CreateViewModel(GroupType model, Person currentPerson = null, bool loadAttributes = true)
 {
     if (model == null)
     {
         return(default);
        /// <summary>
        /// Gets the person control for this field's <see cref="PersonFieldType"/>
        /// </summary>
        /// <param name="setValue">if set to <c>true</c> [set value].</param>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="familyMemberSelected">if set to <c>true</c> [family member selected].</param>
        /// <param name="validationGroup">The validation group.</param>
        /// <returns></returns>
        public Control GetPersonControl(bool setValue, object fieldValue, bool familyMemberSelected, string validationGroup)
        {
            RegistrationTemplateFormField field = this;
            Control personFieldControl          = null;

            switch (field.PersonFieldType)
            {
            case RegistrationPersonFieldType.FirstName:
                var tbFirstName = new RockTextBox
                {
                    ID              = "tbFirstName",
                    Label           = "First Name",
                    Required        = field.IsRequired,
                    CssClass        = "js-first-name",
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbFirstName;
                break;

            case RegistrationPersonFieldType.LastName:
                var tbLastName = new RockTextBox
                {
                    ID              = "tbLastName",
                    Label           = "Last Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbLastName;
                break;

            case RegistrationPersonFieldType.MiddleName:
                var tbMiddleName = new RockTextBox
                {
                    ID              = "tbMiddleName",
                    Label           = "Middle Name",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Enabled         = !familyMemberSelected,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbMiddleName;
                break;

            case RegistrationPersonFieldType.Campus:
                var cpHomeCampus = new CampusPicker
                {
                    ID               = "cpHomeCampus",
                    Label            = "Campus",
                    Required         = field.IsRequired,
                    ValidationGroup  = validationGroup,
                    Campuses         = CampusCache.All(false),
                    SelectedCampusId = setValue && fieldValue != null?fieldValue.ToString().AsIntegerOrNull() : null
                };

                personFieldControl = cpHomeCampus;
                break;

            case RegistrationPersonFieldType.Address:
                var acAddress = new AddressControl
                {
                    ID    = "acAddress",
                    Label = "Address",
                    UseStateAbbreviation   = true,
                    UseCountryAbbreviation = false,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                if (setValue && fieldValue != null)
                {
                    acAddress.SetValues(fieldValue as Location);
                }

                personFieldControl = acAddress;
                break;

            case RegistrationPersonFieldType.Email:
                var tbEmail = new EmailBox
                {
                    ID              = "tbEmail",
                    Label           = "Email",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    Text            = setValue && fieldValue != null?fieldValue.ToString() : string.Empty
                };

                personFieldControl = tbEmail;
                break;

            case RegistrationPersonFieldType.Birthdate:
                var bpBirthday = new BirthdayPicker
                {
                    ID              = "bpBirthday",
                    Label           = "Birthday",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = bpBirthday;
                break;

            case RegistrationPersonFieldType.Grade:
                var gpGrade = new GradePicker
                {
                    ID                    = "gpGrade",
                    Label                 = "Grade",
                    Required              = field.IsRequired,
                    ValidationGroup       = validationGroup,
                    UseAbbreviation       = true,
                    UseGradeOffsetAsValue = true,
                    CssClass              = "input-width-md"
                };

                personFieldControl = gpGrade;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsIntegerOrNull();
                    gpGrade.SetValue(Person.GradeOffsetFromGraduationYear(value));
                }

                break;

            case RegistrationPersonFieldType.Gender:
                var ddlGender = new RockDropDownList
                {
                    ID              = "ddlGender",
                    Label           = "Gender",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                };

                ddlGender.BindToEnum <Gender>(true, new Gender[1] {
                    Gender.Unknown
                });

                personFieldControl = ddlGender;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().ConvertToEnumOrNull <Gender>() ?? Gender.Unknown;
                    ddlGender.SetValue(value.ConvertToInt());
                }

                break;

            case RegistrationPersonFieldType.MaritalStatus:
                var dvpMaritalStatus = new DefinedValuePicker
                {
                    ID              = "dvpMaritalStatus",
                    Label           = "Marital Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpMaritalStatus.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS.AsGuid()).Id;
                personFieldControl             = dvpMaritalStatus;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpMaritalStatus.SetValue(value);
                }

                break;

            case RegistrationPersonFieldType.AnniversaryDate:
                var dppAnniversaryDate = new DatePartsPicker
                {
                    ID              = "dppAnniversaryDate",
                    Label           = "Anniversary Date",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    SelectedDate    = setValue && fieldValue != null ? fieldValue as DateTime? : null
                };

                personFieldControl = dppAnniversaryDate;
                break;

            case RegistrationPersonFieldType.MobilePhone:
                var dvMobilePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                if (dvMobilePhone == null)
                {
                    break;
                }

                var ppMobile = new PhoneNumberBox
                {
                    ID              = "ppMobile",
                    Label           = dvMobilePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var mobilePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppMobile.CountryCode = mobilePhoneNumber != null ? mobilePhoneNumber.CountryCode : string.Empty;
                ppMobile.Number      = mobilePhoneNumber != null?mobilePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppMobile;
                break;

            case RegistrationPersonFieldType.HomePhone:
                var dvHomePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                if (dvHomePhone == null)
                {
                    break;
                }

                var ppHome = new PhoneNumberBox
                {
                    ID              = "ppHome",
                    Label           = dvHomePhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var homePhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppHome.CountryCode = homePhoneNumber != null ? homePhoneNumber.CountryCode : string.Empty;
                ppHome.Number      = homePhoneNumber != null?homePhoneNumber.ToString() : string.Empty;

                personFieldControl = ppHome;
                break;

            case RegistrationPersonFieldType.WorkPhone:
                var dvWorkPhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK);
                if (dvWorkPhone == null)
                {
                    break;
                }

                var ppWork = new PhoneNumberBox
                {
                    ID              = "ppWork",
                    Label           = dvWorkPhone.Value,
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup,
                    CountryCode     = PhoneNumber.DefaultCountryCode()
                };

                var workPhoneNumber = setValue && fieldValue != null ? fieldValue as PhoneNumber : null;
                ppWork.CountryCode = workPhoneNumber != null ? workPhoneNumber.CountryCode : string.Empty;
                ppWork.Number      = workPhoneNumber != null?workPhoneNumber.ToString() : string.Empty;

                personFieldControl = ppWork;
                break;

            case RegistrationPersonFieldType.ConnectionStatus:
                var dvpConnectionStatus = new DefinedValuePicker
                {
                    ID              = "dvpConnectionStatus",
                    Label           = "Connection Status",
                    Required        = field.IsRequired,
                    ValidationGroup = validationGroup
                };

                dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)).Id;

                if (setValue && fieldValue != null)
                {
                    var value = fieldValue.ToString().AsInteger();
                    dvpConnectionStatus.SetValue(value);
                }

                personFieldControl = dvpConnectionStatus;
                break;
            }

            return(personFieldControl);
        }
Пример #20
0
        /// <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);
            }
        }
Пример #21
0
        /// <summary>
        /// Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var    controller          = actionContext.ActionDescriptor.ControllerDescriptor;
            string controllerClassName = controller.ControllerType.FullName;
            string actionMethod        = actionContext.Request.Method.Method;
            string actionPath          = actionContext.Request.GetRouteData().Route.RouteTemplate.Replace("{controller}", controller.ControllerName);

            //// find any additional arguments that aren't part of the RouteTemplate that qualified the action method
            //// for example: ~/person/search?name={name}&includeHtml={includeHtml}&includeDetails={includeDetails}&includeBusinesses={includeBusinesses}
            //// is a different action method than ~/person/search?name={name}
            var routeQueryParams = actionContext.ActionArguments.Where(a => !actionPath.Contains("{" + a.Key + "}"));

            if (routeQueryParams.Any())
            {
                var actionPathQueryString = routeQueryParams.Select(a => string.Format("{0}={{{0}}}", a.Key)).ToList().AsDelimited("&");
                actionPath += "?" + actionPathQueryString;
            }

            ISecured item = RestActionCache.Get(actionMethod + actionPath);

            if (item == null)
            {
                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), false, null);
                            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);
                        }
                    }
                }
            }

            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);
            }
        }
Пример #22
0
        /// <summary>
        /// Gets the navigation children.
        /// </summary>
        /// <param name="parentCategoryId">The parent category identifier.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="selectedCategoryGuids">The selected category guids.</param>
        /// <param name="checkSelected">if set to <c>true</c> [check selected].</param>
        /// <param name="includeAllChildren">if set to <c>true</c> [include all children].</param>
        /// <param name="currentPerson">The current person.</param>
        /// <returns></returns>
        private List <CategoryNavigationItem> GetNavigationChildren(int?parentCategoryId, IEnumerable <Category> categories, List <Guid> selectedCategoryGuids, bool checkSelected, bool includeAllChildren, Person currentPerson)
        {
            var items = new List <CategoryNavigationItem>();

            foreach (var category in categories
                     .Where(c =>
                            c.ParentCategoryId == parentCategoryId ||
                            (!c.ParentCategoryId.HasValue && !parentCategoryId.HasValue))
                     .OrderBy(c => c.Order)
                     .ThenBy(c => c.Name))
            {
                if (category.IsAuthorized(Rock.Security.Authorization.VIEW, currentPerson))
                {
                    bool includeCategory    = !checkSelected || selectedCategoryGuids.Contains(category.Guid);
                    bool checkChildSelected = checkSelected;

                    if (includeCategory)
                    {
                        if (checkSelected && includeAllChildren)
                        {
                            checkChildSelected = false;
                        }

                        var categoryItem = new CategoryNavigationItem(category);
                        items.Add(categoryItem);

                        // Recurse child categories
                        categoryItem.ChildCategories = GetNavigationChildren(category.Id, categories, selectedCategoryGuids, checkChildSelected, includeAllChildren, currentPerson);
                    }
                    else
                    {
                        foreach (var categoryItem in GetNavigationChildren(category.Id, categories, selectedCategoryGuids, checkChildSelected, includeAllChildren, currentPerson))
                        {
                            items.Add(categoryItem);
                        }
                    }
                }
            }

            return(items);
        }
Пример #23
0
        /// <summary>
        /// Gets all of the categories that were selected and optionally all the child categories of the selected categories
        /// </summary>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="selectedCategoryGuids">The selected category guids.</param>
        /// <param name="includeAllChildren">if set to <c>true</c> will include all the child categories of any selected category.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <returns></returns>
        public List <CategoryNavigationItem> GetNavigationItems(int?entityTypeId, List <Guid> selectedCategoryGuids, bool includeAllChildren, Person currentPerson)
        {
            var allCategories = GetByEntityTypeId(entityTypeId).ToList();

            return(GetNavigationChildren(null, allCategories, selectedCategoryGuids, selectedCategoryGuids.Any(), includeAllChildren, currentPerson));
        }
Пример #24
0
        private Group SaveNewPerson(Rock.Model.Person person, Group existingFamily, int?defaultCampus, RockContext rockContext)
        {
            if (existingFamily == null)
            {
                return(PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus : ( int? )null), false));
            }
            else
            {
                person.FirstName  = person.FirstName.FixCase();
                person.NickName   = person.NickName.FixCase();
                person.MiddleName = person.MiddleName.FixCase();
                person.LastName   = person.LastName.FixCase();

                // Create/Save Known Relationship Group
                var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS);
                if (knownRelationshipGroupType != null)
                {
                    var ownerRole = knownRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = knownRelationshipGroupType.Name;
                        group.GroupTypeId = knownRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }

                // Create/Save Implied Relationship Group
                var impliedRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS);
                if (impliedRelationshipGroupType != null)
                {
                    var ownerRole = impliedRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = impliedRelationshipGroupType.Name;
                        group.GroupTypeId = impliedRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }
                var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                var adultRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                var childRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                var age = person.Age;

                var familyRole = age.HasValue && age < 18 ? childRole : adultRole;

                // Add to the existing family
                PersonService.AddPersonToFamily(person, true, existingFamily.Id, familyRole.Id, rockContext);
                return(existingFamily);
            }
        }
Пример #25
0
 /// <summary>
 /// Evaluates whether a selected person is allowed to perform the selected action on the selected
 /// entity.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <returns></returns>
 public static bool Authorized(ISecured entity, string action, Rock.Model.Person person)
 {
     return(ItemAuthorized(entity, action, person) ?? entity.IsAllowedByDefault(action));
 }
Пример #26
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var attribute = AttributeCache.Read(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Read(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Read(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Read(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }
                    }

                    // Save/update the phone number
                    if (!string.IsNullOrWhiteSpace(phone))
                    {
                        List <string> changes    = new List <string>();
                        var           numberType = DefinedValueCache.Read(GetAttributeValue(action, "DefaultPhoneNumberType").AsGuid());
                        if (numberType != null)
                        {
                            // gets value indicating if phone number is unlisted
                            string unlistedValue     = GetAttributeValue(action, "Unlisted");
                            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                            if (unlistedValueGuid.HasValue)
                            {
                                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
                            }
                            else
                            {
                                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool unlisted = unlistedValue.AsBoolean();

                            // gets value indicating if messaging should be enabled for phone number
                            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                            if (smsEnabledValueGuid.HasValue)
                            {
                                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
                            }
                            else
                            {
                                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool smsEnabled = smsEnabledValue.AsBoolean();


                            var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                            string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                            string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                            if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                            {
                                if (phoneModel == null)
                                {
                                    phoneModel = new PhoneNumber();
                                    person.PhoneNumbers.Add(phoneModel);
                                    phoneModel.NumberTypeValueId = numberType.Id;
                                }
                                else
                                {
                                    oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                }
                                phoneModel.Number             = newPhoneNumber;
                                phoneModel.IsUnlisted         = unlisted;
                                phoneModel.IsMessagingEnabled = smsEnabled;

                                History.EvaluateChange(
                                    changes,
                                    string.Format("{0} Phone", numberType.Value),
                                    oldPhoneNumber,
                                    phoneModel.NumberFormattedWithCountryCode);
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }

            return(true);
        }
Пример #27
0
 /// <summary>
 /// Returns XML for a page menu.  XML will be 1 level deep
 /// </summary>
 /// <param name="person">The person.</param>
 /// <returns></returns>
 public XDocument MenuXml(Rock.Model.Person person)
 {
     return(MenuXml(1, person));
 }
Пример #28
0
 /// <summary>
 /// Return <c>true</c> if the user is authorized to perform the selected action on this object.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <returns>
 ///   <c>true</c> if the specified action is authorized; otherwise, <c>false</c>.
 /// </returns>
 public virtual bool IsAuthorized(string action, Rock.Model.Person person)
 {
     return(Authorization.Authorized(this, action, person));
 }
Пример #29
0
        private static bool?ItemAuthorized(ISecured entity, string action, Rock.Model.Person person)
        {
            // If there's no Authorizations object, create it
            if (Authorizations == null)
            {
                Load();
            }

            var entityTypeId = entity.TypeId;

            // If there are entries in the Authorizations object for this entity type and entity instance, evaluate each
            // one to find the first one specific to the selected user or a role that the selected user belongs
            // to.  If a match is found return whether the user is allowed (true) or denied (false) access
            if (Authorizations.Keys.Contains(entityTypeId) &&
                Authorizations[entityTypeId].Keys.Contains(entity.Id) &&
                Authorizations[entityTypeId][entity.Id].Keys.Contains(action))
            {
                string userName = person != null?person.Guid.ToString() : string.Empty;

                foreach (AuthRule authRule in Authorizations[entityTypeId][entity.Id][action])
                {
                    // All Users
                    if (authRule.SpecialRole == SpecialRole.AllUsers)
                    {
                        return(authRule.AllowOrDeny == "A");
                    }

                    // All Authenticated Users
                    if (authRule.SpecialRole == SpecialRole.AllAuthenticatedUsers && userName.Trim() != string.Empty)
                    {
                        return(authRule.AllowOrDeny == "A");
                    }

                    // All Unauthenticated Users
                    if (authRule.SpecialRole == SpecialRole.AllUnAuthenticatedUsers && userName.Trim() == string.Empty)
                    {
                        return(authRule.AllowOrDeny == "A");
                    }

                    if (authRule.SpecialRole == SpecialRole.None && person != null)
                    {
                        // See if person has been authorized to entity
                        if (authRule.PersonId.HasValue &&
                            authRule.PersonId.Value == person.Id)
                        {
                            return(authRule.AllowOrDeny == "A");
                        }

                        // See if person is in role authorized
                        if (authRule.GroupId.HasValue)
                        {
                            Role role = Role.Read(authRule.GroupId.Value);
                            if (role != null && role.IsUserInRole(userName))
                            {
                                return(authRule.AllowOrDeny == "A");
                            }
                        }
                    }
                }
            }

            // If no match was found for the selected user on the current entity instance, check to see if the instance
            // has a parent authority defined and if so evaluate that entities authorization rules.  If there is no
            // parent authority return the defualt authorization
            bool?parentAuthorized = null;

            if (entity.ParentAuthorityPre != null)
            {
                parentAuthorized = ItemAuthorized(entity.ParentAuthorityPre, action, person);
            }

            if (!parentAuthorized.HasValue && entity.ParentAuthority != null)
            {
                parentAuthorized = ItemAuthorized(entity.ParentAuthority, action, person);
            }

            return(parentAuthorized);
        }
Пример #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RosterAttendee"/> class.
 /// </summary>
 /// <param name="person">The person.</param>
 public RosterAttendee(Rock.Model.Person person)
 {
     _person = person;
 }
Пример #31
0
 /// <summary>
 /// Return <c>true</c> if the user is authorized to perform the selected action on this object.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <returns>
 ///   <c>true</c> if the specified action is authorized; otherwise, <c>false</c>.
 /// </returns>
 public bool IsAuthorized(string action, Rock.Model.Person person)
 {
     return(Security.Authorization.Authorized(this, action, person));
 }