Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoadAttributesOptions"/> class.
 /// </summary>
 /// <param name="loadAttributesEnabled">if set to <c>true</c> [load attributes enabled].</param>
 /// <param name="serializeInSimpleMode">if set to <c>true</c> [serialize in simple mode].</param>
 /// <param name="limitToAttributeKeyList">The limit to attribute key list.</param>
 /// <param name="person">The person.</param>
 public LoadAttributesOptions(bool loadAttributesEnabled, bool serializeInSimpleMode, string[] limitToAttributeKeyList, Rock.Model.Person person)
 {
     LoadAttributesEnabled   = loadAttributesEnabled;
     SerializeInSimpleMode   = serializeInSimpleMode;
     LimitToAttributeKeyList = limitToAttributeKeyList ?? new string[0];
     Person = person;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Determines whether person is authorized for the EntityType
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        public virtual bool IsAuthorized(string action, Rock.Model.Person person)
        {
            if (this.IsSecured)
            {
                object entity = null;
                try
                {
                    var type = EntityTypeCache.Get(this).GetEntityType();
                    entity = System.Activator.CreateInstance(type);
                }
                catch
                {
                    // unable to create the entity, so return false since we can't do anything with it
                    return(false);
                }

                if (entity is Rock.Security.ISecured)
                {
                    Rock.Security.ISecured iSecured = (Rock.Security.ISecured)entity;
                    return(iSecured.IsAuthorized(action, person));
                }
            }

            return(true);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>
        /// Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" />.
        /// </returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            var    qryParams      = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query);
            string loadAttributes = qryParams["LoadAttributes"] ?? string.Empty;

            string[] limitToAttributeKeyList = qryParams["AttributeKeys"]?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim()).ToArray();

            // if "simple" or True is specified in the LoadAttributes param, tell the formatter to serialize in Simple mode
            bool serializeInSimpleMode = loadAttributes.Equals("simple", StringComparison.OrdinalIgnoreCase) || (loadAttributes.AsBooleanOrNull() ?? false);

            // if either "simple", "expanded", or True is specified in the LoadAttributes param, tell the formatter to load the attributes on the way out
            bool loadAttributesEnabled = serializeInSimpleMode || loadAttributes.Equals("expanded", StringComparison.OrdinalIgnoreCase);

            Rock.Model.Person person = null;

            // NOTE: request.Properties["Person"] gets set in Rock.Rest.Filters.SecurityAttribute.OnActionExecuting
            if (loadAttributesEnabled && request.Properties.ContainsKey("Person"))
            {
                person = request.Properties["Person"] as Rock.Model.Person;
            }

            // store the request options in HttpContext.Current.Items so they are thread safe, and only for this request
            var loadAttributesOptions = new LoadAttributesOptions(loadAttributesEnabled, serializeInSimpleMode, limitToAttributeKeyList, person);

            HttpContext.Current.Items[LoadAttributesOptions.ContextItemsKey] = loadAttributesOptions;

            return(base.GetPerRequestFormatterInstance(type, request, mediaType));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser(bool userIsOnline)
        {
            string userName = UserLogin.GetCurrentUserName();

            if (userName != string.Empty)
            {
                if (userName.StartsWith("rckipid="))
                {
                    Rock.Model.PersonService personService      = new Model.PersonService();
                    Rock.Model.Person        impersonatedPerson = personService.GetByEncryptedKey(userName.Substring(8));
                    if (impersonatedPerson != null)
                    {
                        return(impersonatedPerson.ImpersonatedUser);
                    }
                }
                else
                {
                    var       userLoginService = new UserLoginService();
                    UserLogin user             = userLoginService.GetByUserName(userName);

                    if (user != null && userIsOnline)
                    {
                        // Save last activity date
                        var transaction = new Rock.Transactions.UserLastActivityTransaction();
                        transaction.UserId           = user.Id;
                        transaction.LastActivityDate = DateTime.Now;
                        Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
                    }

                    return(user);
                }
            }

            return(null);
        }
Exemplo n.º 5
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var person_id     = pkrPerson.PersonId;
                var group_type_id = Int32.Parse(pkrGroupType.SelectedValue);

                if (person_id != null && group_type_id > 0)
                {
                    var personService        = new Rock.Model.PersonService(_ctx);
                    Rock.Model.Person person = personService.Get((int)person_id);

                    var groupTypeService           = new Rock.Model.GroupTypeService(_ctx);
                    Rock.Model.GroupType groupType = groupTypeService.Get(group_type_id);

                    GroupMatcher groupMatcher = new GroupMatcher(person, groupType, pkrDaysOfWeek.SelectedDaysOfWeek);

                    var matches = groupMatcher.GetMatches();

                    grdMatches.DataSource = matches;
                    grdMatches.DataBind();

                    pnlResults.Visible = true;
                }
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Creates a new <see cref="Rock.Model.UserLogin" />
 /// </summary>
 /// <param name="rockContext">The rock context.</param>
 /// <param name="person">The <see cref="Rock.Model.Person" /> that this <see cref="UserLogin" /> will be associated with.</param>
 /// <param name="serviceType">The <see cref="Rock.Model.AuthenticationServiceType" /> type of Login</param>
 /// <param name="entityTypeId">The entity type identifier.</param>
 /// <param name="username">A <see cref="System.String" /> containing the UserName.</param>
 /// <param name="password">A <see cref="System.String" /> containing the unhashed/unencrypted password.</param>
 /// <param name="isConfirmed">A <see cref="System.Boolean" /> flag indicating if the user has been confirmed.</param>
 /// <returns></returns>
 /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the Username already exists.</exception>
 /// <exception cref="System.ArgumentException">Thrown when the service does not exist or is not active.</exception>
 public static UserLogin Create(RockContext rockContext,
                                Rock.Model.Person person,
                                AuthenticationServiceType serviceType,
                                int entityTypeId,
                                string username,
                                string password,
                                bool isConfirmed)
 {
     return(UserLoginService.Create(rockContext, person, serviceType, entityTypeId, username, password, isConfirmed, false));
 }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> that this <see cref="UserLogin"/> will be associated with.</param>
        /// <param name="serviceType">The <see cref="Rock.Model.AuthenticationServiceType"/> type of Login</param>
        /// <param name="serviceName">A <see cref="System.String"/> representing the service class/type name of the authentication service</param>
        /// <param name="username">A <see cref="System.String"/> containing the UserName.</param>
        /// <param name="password">A <see cref="System.String"/> containing the unhashed/unencrypted password.</param>
        /// <param name="isConfirmed">A <see cref="System.Boolean"/> flag indicating if the user has been confirmed.</param>
        /// <param name="currentPersonId">A <see cref="System.Int32"/> representing the Id of the <see cref="Rock.Model.Person"/> creating the <see cref="Rock.Model.UserLogin"/></param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the Username already exists.</exception>
        /// <exception cref="System.ArgumentException">Thrown when the service does not exist or is not active.</exception>
        public UserLogin Create(Rock.Model.Person person,
                                AuthenticationServiceType serviceType,
                                int entityTypeId,
                                string username,
                                string password,
                                bool isConfirmed,
                                int?currentPersonId)
        {
            var entityType = EntityTypeCache.Read(entityTypeId);

            if (entityType != null)
            {
                UserLogin user = this.GetByUserName(username);
                if (user != null)
                {
                    throw new ArgumentOutOfRangeException("username", "Username already exists");
                }

                DateTime createDate = DateTime.Now;

                user = new UserLogin();
                user.EntityTypeId                = entityTypeId;
                user.UserName                    = username;
                user.IsConfirmed                 = isConfirmed;
                user.CreationDateTime            = createDate;
                user.LastPasswordChangedDateTime = createDate;
                if (person != null)
                {
                    user.PersonId = person.Id;
                }

                if (serviceType == AuthenticationServiceType.Internal)
                {
                    var authenticationComponent = AuthenticationContainer.GetComponent(entityType.Name);
                    if (authenticationComponent == null || !authenticationComponent.IsActive)
                    {
                        throw new ArgumentException(string.Format("'{0}' service does not exist, or is not active", entityType.FriendlyName), "entityTypeId");
                    }

                    user.Password = authenticationComponent.EncodePassword(user, password);
                }

                this.Add(user, currentPersonId);
                this.Save(user, currentPersonId);

                return(user);
            }
            else
            {
                throw new ArgumentException("Invalid EntityTypeId, entity does not exist", "entityTypeId");
            }
        }
Exemplo n.º 8
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;
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new user.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="serviceName">Name of the service.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="isConfirmed">if set to <c>true</c> [is confirmed].</param>
        /// <param name="currentPersonId">The current person id.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentOutOfRangeException">username;Username already exists</exception>
        /// <exception cref="System.ArgumentException">serviceName</exception>
        public UserLogin Create(Rock.Model.Person person,
                                AuthenticationServiceType serviceType,
                                string serviceName,
                                string username,
                                string password,
                                bool isConfirmed,
                                int?currentPersonId)
        {
            UserLogin user = this.GetByUserName(username);

            if (user != null)
            {
                throw new ArgumentOutOfRangeException("username", "Username already exists");
            }

            DateTime createDate = DateTime.Now;

            user                         = new UserLogin();
            user.ServiceType             = serviceType;
            user.ServiceName             = serviceName;
            user.UserName                = username;
            user.IsConfirmed             = isConfirmed;
            user.CreationDate            = createDate;
            user.LastPasswordChangedDate = createDate;
            if (person != null)
            {
                user.PersonId = person.Id;
            }

            if (serviceType == AuthenticationServiceType.Internal)
            {
                AuthenticationComponent authenticationComponent = GetComponent(serviceName);
                if (authenticationComponent == null)
                {
                    throw new ArgumentException(string.Format("'{0}' service does not exist, or is not active", serviceName), "serviceName");
                }

                user.Password = authenticationComponent.EncodePassword(user, password);
            }

            this.Add(user, currentPersonId);
            this.Save(user, currentPersonId);

            return(user);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" /> that can format a response for the given parameters.
        /// </summary>
        /// <param name="type">The type to format.</param>
        /// <param name="request">The request.</param>
        /// <param name="mediaType">The media type.</param>
        /// <returns>
        /// Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter" />.
        /// </returns>
        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, System.Net.Http.HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
        {
            var    qryParams      = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query);
            string loadAttributes = qryParams["LoadAttributes"] ?? string.Empty;

            // if "simple" or True is specified in the LoadAttributes param, tell the formatter to serialize in Simple mode
            SerializeInSimpleMode = loadAttributes.Equals("simple", StringComparison.OrdinalIgnoreCase) || (loadAttributes.AsBooleanOrNull() ?? false);

            // if either "simple", "expanded", or True is specified in the LoadAttributes param, tell the formatter to load the attributes on the way out
            LoadAttributes = SerializeInSimpleMode || loadAttributes.Equals("expanded", StringComparison.OrdinalIgnoreCase);

            // NOTE: request.Properties["Person"] gets set in Rock.Rest.Filters.SecurityAttribute.OnActionExecuting
            if (LoadAttributes && request.Properties.ContainsKey("Person"))
            {
                this.Person = request.Properties["Person"] as Rock.Model.Person;
            }

            return(base.GetPerRequestFormatterInstance(type, request, mediaType));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Returs 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);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Filters the attributes.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="items">The items.</param>
        /// <param name="person">The person.</param>
        private static void FilterAttributes(Data.RockContext rockContext, IEnumerable <Attribute.IHasAttributes> items, Rock.Model.Person person)
        {
            if (!items.Any())
            {
                return;
            }

            var itemType = items.First().GetType();

            var entityType = EntityTypeCache.Get(itemType);

            if (entityType == null)
            {
                // shouldn't happen
                return;
            }

            var entityAttributes = AttributeCache.GetByEntity(entityType.Id);

            // only return attributes that the person has VIEW auth to
            // NOTE: There are some Attributes that even Admin doesn't have VIEW auth so (For example, some of obsolete DISC attributes)
            foreach (var entityAttribute in entityAttributes)
            {
                foreach (var attributeId in entityAttribute.AttributeIds)
                {
                    var attribute = AttributeCache.Get(attributeId);
                    if (!attribute.IsAuthorized(Rock.Security.Authorization.VIEW, person))
                    {
                        foreach (var item in items)
                        {
                            if (item.AttributeValues.ContainsKey(attribute.Key))
                            {
                                item.AttributeValues.Remove(attribute.Key);
                            }

                            if (item.Attributes.ContainsKey(attribute.Key))
                            {
                                item.Attributes.Remove(attribute.Key);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Creates a new <see cref="Rock.Model.UserLogin" />
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The <see cref="Rock.Model.Person" /> that this <see cref="UserLogin" /> will be associated with.</param>
        /// <param name="serviceType">The <see cref="Rock.Model.AuthenticationServiceType" /> type of Login</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="username">A <see cref="System.String" /> containing the UserName.</param>
        /// <param name="password">A <see cref="System.String" /> containing the unhashed/unencrypted password.</param>
        /// <param name="isConfirmed">A <see cref="System.Boolean" /> flag indicating if the user has been confirmed.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the Username already exists.</exception>
        /// <exception cref="System.ArgumentException">Thrown when the service does not exist or is not active.</exception>
        public static UserLogin Create(RockContext rockContext,
                                       Rock.Model.Person person,
                                       AuthenticationServiceType serviceType,
                                       int entityTypeId,
                                       string username,
                                       string password,
                                       bool isConfirmed)
        {
            if (person != null)
            {
                var userLoginService = new UserLoginService(rockContext);

                var entityType = EntityTypeCache.Read(entityTypeId);
                if (entityType != null)
                {
                    UserLogin user = userLoginService.GetByUserName(username);
                    if (user != null)
                    {
                        throw new ArgumentOutOfRangeException("username", "Username already exists");
                    }

                    DateTime createDate = RockDateTime.Now;

                    user              = new UserLogin();
                    user.Guid         = Guid.NewGuid();
                    user.EntityTypeId = entityTypeId;
                    user.UserName     = username;
                    user.IsConfirmed  = isConfirmed;
                    user.LastPasswordChangedDateTime = createDate;
                    user.PersonId = person.Id;

                    if (serviceType == AuthenticationServiceType.Internal)
                    {
                        var authenticationComponent = AuthenticationContainer.GetComponent(entityType.Name);
                        if (authenticationComponent == null || !authenticationComponent.IsActive)
                        {
                            throw new ArgumentException(string.Format("'{0}' service does not exist, or is not active", entityType.FriendlyName), "entityTypeId");
                        }

                        user.Password = authenticationComponent.EncodePassword(user, password);
                    }

                    userLoginService.Add(user);
                    rockContext.SaveChanges();

                    var historyCategory = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext);
                    if (historyCategory != null)
                    {
                        var changes = new List <string>();
                        History.EvaluateChange(changes, "User Login", string.Empty, username);
                        HistoryService.SaveChanges(rockContext, typeof(Person), historyCategory.Guid, person.Id, changes);
                    }

                    return(user);
                }
                else
                {
                    throw new ArgumentException("Invalid EntityTypeId, entity does not exist", "entityTypeId");
                }
            }
            else
            {
                throw new ArgumentException("Invalid Person, person does not exist", "person");
            }
        }
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser(bool userIsOnline)
        {
            var rockContext = new RockContext();

            string userName = UserLogin.GetCurrentUserName();

            if (userName != string.Empty)
            {
                if (userName.StartsWith("rckipid="))
                {
                    Rock.Model.PersonService personService      = new Model.PersonService(rockContext);
                    Rock.Model.Person        impersonatedPerson = personService.GetByEncryptedKey(userName.Substring(8));
                    if (impersonatedPerson != null)
                    {
                        return(impersonatedPerson.GetImpersonatedUser());
                    }
                }
                else
                {
                    var       userLoginService = new UserLoginService(rockContext);
                    UserLogin user             = userLoginService.GetByUserName(userName);

                    if (user != null && userIsOnline)
                    {
                        // Save last activity date
                        var transaction = new Rock.Transactions.UserLastActivityTransaction();
                        transaction.UserId           = user.Id;
                        transaction.LastActivityDate = RockDateTime.Now;

                        if ((user.IsConfirmed ?? true) && !(user.IsLockedOut ?? false))
                        {
                            if (HttpContext.Current != null && HttpContext.Current.Session != null)
                            {
                                HttpContext.Current.Session["RockUserId"] = user.Id;
                            }

                            // see if there is already a LastActivitytransaction queued for this user, and just update its LastActivityDate instead of adding another to the queue
                            var userLastActivity = Rock.Transactions.RockQueue.TransactionQueue.ToArray().OfType <Rock.Transactions.UserLastActivityTransaction>()
                                                   .Where(a => a.UserId == transaction.UserId).FirstOrDefault();

                            if (userLastActivity != null)
                            {
                                userLastActivity.LastActivityDate = transaction.LastActivityDate;
                            }
                            else
                            {
                                Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
                            }
                        }
                        else
                        {
                            transaction.IsOnLine = false;
                            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);

                            FormsAuthentication.SignOut();
                            return(null);
                        }
                    }

                    return(user);
                }
            }

            return(null);
        }
Exemplo n.º 15
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(Security.Authorization.Authorized(this, action, person));
 }