Data Access/Service class for Rock.Model.UserLogin entities.
Example #1
0
        /// <summary>
        /// Handles the Click event of the btnUserInfoNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnUserInfoNext_Click(object sender, EventArgs e)
        {
            Password = tbPassword.Text;

            if (Page.IsValid)
            {
                if (!IsOldEnough())
                {
                    ShowErrorMessage(
                        string.Format("We are sorry, you must be at least {0} years old to create an account.",
                                      GetAttributeValue(AttributeKeys.MinimumAge))
                        );
                    return;
                }

                if (UserLoginService.IsPasswordValid(tbPassword.Text))
                {
                    var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                    var userLogin        = userLoginService.GetByUserName(tbUserName.Text);

                    if (userLogin == null)
                    {
                        DisplayDuplicates(Direction.Forward);
                    }
                    else
                    {
                        ShowErrorMessage("Username already exists");
                    }
                }
                else
                {
                    ShowErrorMessage(UserLoginService.FriendlyPasswordRules());
                }
            }
        }
Example #2
0
        /// <summary>
        /// Handles the Click event of the btnDuplicatesNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            int personId = Request.Form["DuplicatePerson"].AsInteger();

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                var userLogins       = userLoginService.GetByPersonId(personId)
                                       .Where(l => l.IsLockedOut != true)
                                       .ToList();

                if (userLogins.Any(ul => !AuthenticationContainer.GetComponent(ul.EntityType.Name).RequiresRemoteAuthentication))
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
Example #3
0
        /// <summary>
        /// Handles the Click event of the btnChange control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnChange_Click( object sender, EventArgs e )
        {
            var userLoginService = new UserLoginService();
            var userLogin = userLoginService.GetByUserName( tbUserName.Text );
            if ( userLogin != null )
            {
                if ( UserLoginService.IsPasswordValid( tbPassword.Text ) )
                {
                    if ( userLoginService.ChangePassword( userLogin, tbOldPassword.Text, tbPassword.Text ) )
                    {
                        userLoginService.Save( userLogin, CurrentPersonId );

                        lSuccess.Text = GetAttributeValue( "SuccessCaption" );
                        pnlEntry.Visible = false;
                        pnlSuccess.Visible = true;
                    }
                    else
                        DisplayError( "InvalidPasswordCaption" );
                }
                else
                {
                    InvalidPassword();
                }
            }
            else
                DisplayError( "InvalidUserNameCaption" );
        }
Example #4
0
        /// <summary>
        /// Handles the Click event of the btnUserInfoNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnUserInfoNext_Click(object sender, EventArgs e)
        {
            Password = tbPassword.Text;

            if (Page.IsValid)
            {
                if (UserLoginService.IsPasswordValid(tbPassword.Text))
                {
                    var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                    var userLogin        = userLoginService.GetByUserName(tbUserName.Text);

                    if (userLogin == null)
                    {
                        DisplayDuplicates(Direction.Forward);
                    }
                    else
                    {
                        ShowErrorMessage("Username already exists");
                    }
                }
                else
                {
                    ShowErrorMessage(UserLoginService.FriendlyPasswordRules());
                }
            }
        }
Example #5
0
        private Rock.Model.UserLogin CreateUser(Person person, bool confirmed)
        {
            var userLoginService = new Rock.Model.UserLoginService();

            return(userLoginService.Create(person, Rock.Model.AuthenticationServiceType.Internal,
                                           EntityTypeCache.Read(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                           tbUserName.Text, Password, confirmed, CurrentPersonId));
        }
Example #6
0
        /// <summary>
        /// Handles the Click event of the btnUserInfoNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnUserInfoNext_Click(object sender, EventArgs e)
        {
            Password = tbPassword.Text;

            if (Page.IsValid)
            {
                if (!IsOldEnough())
                {
                    ShowErrorMessage(
                        string.Format(
                            "We are sorry, you must be at least {0} years old to create an account.",
                            GetAttributeValue(AttributeKey.MinimumAge)));

                    return;
                }

                if (ValidateUsernameAsEmail)
                {
                    var match = System.Text.RegularExpressions.Regex.Match(tbUserName.Text, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                    if (!match.Success)
                    {
                        ShowErrorMessage("User name must be a valid email address.");
                        return;
                    }
                }
                else
                {
                    var regexString = Rock.Web.Cache.GlobalAttributesCache.Get().GetValue("core.ValidUsernameRegularExpression");
                    var match       = System.Text.RegularExpressions.Regex.Match(tbUserName.Text, regexString);
                    if (!match.Success)
                    {
                        ShowErrorMessage(GetAttributeValue(AttributeKey.UsernameFieldLabel) + " is not valid. " + Rock.Web.Cache.GlobalAttributesCache.Get().GetValue("core.ValidUsernameCaption"));
                        return;
                    }
                }

                if (UserLoginService.IsPasswordValid(tbPassword.Text))
                {
                    var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                    var userLogin        = userLoginService.GetByUserName(tbUserName.Text);

                    if (userLogin == null)
                    {
                        DisplayDuplicates(Direction.Forward);
                    }
                    else
                    {
                        ShowErrorMessage("That " + GetAttributeValue(AttributeKey.UsernameFieldLabel) + " is already taken.");
                    }
                }
                else
                {
                    ShowErrorMessage(UserLoginService.FriendlyPasswordRules());
                }
            }
        }
Example #7
0
        protected void btnSend_Click( object sender, EventArgs e )
        {
            var mergeObjects = new Dictionary<string, object>();

            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );

            var personDictionaries = new List<IDictionary<string, object>>();

            var personService = new PersonService();
            var userLoginService = new UserLoginService();

            foreach ( Person person in personService.GetByEmail( tbEmail.Text ) )
            {
                var users = new List<IDictionary<string,object>>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            users.Add( user.ToDictionary() );
                        }
                    }
                }

                if (users.Count > 0)
                {
                    IDictionary<string,object> personDictionary = person.ToDictionary();
                    personDictionary.Add("Users", users.ToArray());
                    personDictionaries.Add( personDictionary );
                }
            }

            if ( personDictionaries.Count > 0 )
            {
                mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                var recipients = new Dictionary<string, Dictionary<string, object>>();
                recipients.Add( tbEmail.Text, mergeObjects );

                Email email = new Email( GetAttributeValue( "EmailTemplate" ) );
                email.Send( recipients );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
                pnlWarning.Visible = true;
        }
        /// <summary>
        /// Handles the Click event of the btnSend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSend_Click( object sender, EventArgs e )
        {
            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }

            var mergeObjects = GlobalAttributesCache.GetMergeFields( CurrentPerson );
            mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );
            var results = new List<IDictionary<string, object>>();

            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );

            foreach ( Person person in personService.GetByEmail( tbEmail.Text )
                .Where( p => p.Users.Any()))
            {
                var users = new List<UserLogin>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( !component.RequiresRemoteAuthentication )
                        {
                            users.Add( user );
                        }
                    }
                }

                var resultsDictionary = new Dictionary<string, object>();
                resultsDictionary.Add( "Person", person);
                resultsDictionary.Add( "Users", users );
                results.Add( resultsDictionary );
            }

            if ( results.Count > 0 )
            {
                mergeObjects.Add( "Results", results.ToArray() );
                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( tbEmail.Text, mergeObjects ) );

                Email.Send( GetAttributeValue( "EmailTemplate" ).AsGuid(), recipients, ResolveRockUrlIncludeRoot( "~/" ), ResolveRockUrlIncludeRoot( "~~/" ) );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else
            {
                pnlWarning.Visible = true;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnChange control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnChange_Click( object sender, EventArgs e )
        {
            RockContext rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );
            var userLogin = userLoginService.GetByUserName( tbUserName.Text );

            if ( userLogin != null )
            {
                if ( UserLoginService.IsPasswordValid( tbPassword.Text ) )
                {
                    var component = Rock.Security.AuthenticationContainer.GetComponent( userLogin.EntityType.Name );

                    if ( component.SupportsChangePassword )
                    {

                        string warningMessage;
                        if ( component.ChangePassword( userLogin, tbOldPassword.Text, tbPassword.Text, out warningMessage ) )
                        {
                            rockContext.SaveChanges();

                            lSuccess.Text = GetAttributeValue( "SuccessCaption" );
                            pnlEntry.Visible = false;
                            pnlSuccess.Visible = true;
                        }
                        else
                        {
                            if ( string.IsNullOrWhiteSpace( warningMessage ) )
                            {
                                DisplayErrorFromAttribute( "InvalidPasswordCaption" );
                            }
                            else
                            {
                                DisplayErrorText( warningMessage );
                            }
                        }
                    }
                    else
                    {
                        // shouldn't happen, but just in case
                        DisplayErrorFromAttribute( "ChangePasswordNotSupportedCaption" );
                        pnlChangePassword.Visible = false;
                    }
                }
                else
                {
                    InvalidPassword();
                }
            }
            else
            {
                DisplayErrorFromAttribute( "InvalidUserNameCaption" );
            }
        }
Example #10
0
        protected virtual Rock.Model.UserLogin CurrentUser()
        {
            var principal = ControllerContext.Request.GetUserPrincipal();

            if (principal != null && principal.Identity != null)
            {
                var userLoginService = new Rock.Model.UserLoginService();
                var userLogin        = userLoginService.GetByUserName(principal.Identity.Name);

                if (userLogin != null)
                {
                    return(userLogin);
                }
            }

            return(null);
        }
Example #11
0
        /// <summary>
        /// Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting( HttpActionContext actionContext )
        {
            string controllerClassName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
            string actionMethod = actionContext.Request.Method.Method;
            string actionPath = actionContext.Request.GetRouteData().Route.RouteTemplate;

            ISecured item = Rock.Web.Cache.RestActionCache.Read( actionMethod + actionPath );
            if ( item == null )
            {
                item = Rock.Web.Cache.RestControllerCache.Read( 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 )
                {
                    var userLoginService = new Rock.Model.UserLoginService( new RockContext() );
                    var userLogin = userLoginService.GetByUserName( principal.Identity.Name );
                    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 );
            }
        }
Example #12
0
        /// <summary>
        /// Authenticates the specified user name and password
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public override bool Authenticate( UserLogin user, string password )
        {
            var passwordIsCorrect = CheckF1Password( user.UserName, password );

            if ( passwordIsCorrect )
            {
                using ( var rockContext = new RockContext() )
                {
                    var userLoginService = new UserLoginService( rockContext );
                    var userFromService = userLoginService.Get( user.Id );
                    var databaseGuid = Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid();
                    userFromService.EntityTypeId = EntityTypeCache.Read( databaseGuid ).Id;
                    userLoginService.SetPassword( userFromService, password );
                    rockContext.SaveChanges();
                }
            }

            return passwordIsCorrect;
        }
        /// <summary>
        /// Handles the Delete event of the gRestKeyList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gRestKeyList_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );
            var restUser = personService.Get( e.RowKeyId );
            if ( restUser != null )
            {
                restUser.RecordStatusValueId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id;

                // remove all user logins for key
                foreach ( var login in restUser.Users.ToList() )
                {
                    userLoginService.Delete( login );
                }
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Example #14
0
        public override void OnAuthorization( HttpActionContext actionContext )
        {
            // See if user is logged in
            var principal = System.Threading.Thread.CurrentPrincipal;
            if ( principal != null && principal.Identity != null && !String.IsNullOrWhiteSpace(principal.Identity.Name))
            {
                var userLoginService = new UserLoginService();
                var user = userLoginService.GetByUserName(principal.Identity.Name);
                if ( user != null )
                {
                    actionContext.Request.SetUserPrincipal( principal );
                    return;
                }
            }

            // If not, see if there's a valid token
            string authToken = null;
            if (actionContext.Request.Headers.Contains("Authorization-Token"))
                authToken = actionContext.Request.Headers.GetValues( "Authorization-Token" ).FirstOrDefault();
            if ( String.IsNullOrWhiteSpace( authToken ) )
            {
                string queryString = actionContext.Request.RequestUri.Query;
                authToken = System.Web.HttpUtility.ParseQueryString(queryString).Get("apikey");
            }

            if (! String.IsNullOrWhiteSpace( authToken ) )
            {
                var userLoginService = new UserLoginService();
                var userLogin = userLoginService.Queryable().Where( u => u.ApiKey == authToken ).FirstOrDefault();
                if ( userLogin != null )
                {
                    var identity = new GenericIdentity( userLogin.UserName );
                    principal = new GenericPrincipal(identity, null);
                    actionContext.Request.SetUserPrincipal( principal );
                    return;
                }
            }
            actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.Unauthorized, "The Rock API requires that requests include either an Authorization-Token, and ApiKey querystring parameter, or are made by a logged-in user" ); 
        }
Example #15
0
        /// <summary>
        /// Handles the Click event of the btnDuplicatesNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            if (tbRockFullName.Text.IsNotNullOrWhiteSpace())
            {
                /* 03/22/2021 MDP
                 *
                 * see https://app.asana.com/0/1121505495628584/1200018171012738/f on why this is done
                 *
                 */

                nbRockFullName.Visible             = true;
                nbRockFullName.NotificationBoxType = NotificationBoxType.Validation;
                nbRockFullName.Text = "Invalid Form Value";
                return;
            }

            int personId = Request.Form["DuplicatePerson"].AsInteger();

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                var userLogins       = userLoginService.GetByPersonId(personId)
                                       .Where(l => l.IsLockedOut != true)
                                       .ToList();

                if (userLogins.Any(ul => !AuthenticationContainer.GetComponent(ul.EntityType.Name).RequiresRemoteAuthentication))
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
Example #16
0
        protected void btnDuplicatesNext_Click(object sender, EventArgs e)
        {
            int personId = Int32.Parse(Request.Form["DuplicatePerson"]);

            if (personId > 0)
            {
                var userLoginService = new Rock.Model.UserLoginService();
                var userLogins       = userLoginService.GetByPersonId(personId).ToList();
                if (userLogins.Count > 0)
                {
                    DisplaySendLogin(personId, Direction.Forward);
                }
                else
                {
                    DisplayConfirmation(personId);
                }
            }
            else
            {
                DisplaySuccess(CreateUser(CreatePerson(), true));
            }
        }
Example #17
0
        public override void OnAuthorization( HttpActionContext actionContext )
        {
            // See if user is logged in
            var principal = System.Threading.Thread.CurrentPrincipal;
            if ( principal != null && principal.Identity != null && !String.IsNullOrWhiteSpace(principal.Identity.Name))
            {
                //var userLoginService = new UserLoginService();
                //var user = userLoginService.GetByUserName(principal.Identity.Name);
                //if ( user != null )
                //{
                    actionContext.Request.SetUserPrincipal( principal );
                    return;
                //}
            }

            // If not, see if there's a valid token
            string authToken = null;
            if (actionContext.Request.Headers.Contains("Authorization-Token"))
                authToken = actionContext.Request.Headers.GetValues( "Authorization-Token" ).FirstOrDefault();
            if ( String.IsNullOrWhiteSpace( authToken ) )
            {
                string queryString = actionContext.Request.RequestUri.Query;
                authToken = System.Web.HttpUtility.ParseQueryString(queryString).Get("apikey");
            }

            if (! String.IsNullOrWhiteSpace( authToken ) )
            {
                var userLoginService = new UserLoginService( new Rock.Data.RockContext() );
                var userLogin = userLoginService.Queryable().Where( u => u.ApiKey == authToken ).FirstOrDefault();
                if ( userLogin != null )
                {
                    var identity = new GenericIdentity( userLogin.UserName );
                    principal = new GenericPrincipal(identity, null);
                    actionContext.Request.SetUserPrincipal( principal );
                    return;
                }
            }
        }
        /// <summary>
        /// Gets the peron alias.
        /// </summary>
        /// <returns></returns>
        protected virtual Rock.Model.Person GetPerson()
        {
            if ( Request.Properties.Keys.Contains( "Person" ) )
            {
                return Request.Properties["Person"] as Person;
            }

            var principal = ControllerContext.Request.GetUserPrincipal();
            if ( principal != null && principal.Identity != null )
            {
                var userLoginService = new Rock.Model.UserLoginService( 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;
        }
Example #19
0
        public void Login( [FromBody]LoginParameters loginParameters )
        {
            bool valid = false;

            var userLoginService = new UserLoginService();
            var userLogin = userLoginService.GetByUserName( loginParameters.Username );
            if ( userLogin != null && userLogin.EntityType != null) 
            {
                var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                if ( component != null && component.IsActive)
                {
                    if ( component.Authenticate( userLogin, loginParameters.Password ) )
                    {
                        valid = true;
                        Rock.Security.Authorization.SetAuthCookie( loginParameters.Username, false, false );
                    }
                }
            }

            if ( !valid )
            {
                throw new HttpResponseException( HttpStatusCode.Unauthorized );
            }
        }
Example #20
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);
        }
        /// <summary>
        /// Handles the RowDataBound event of the gRestKeyList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void gRestKeyList_RowDataBound( object sender, GridViewRowEventArgs e )
        {
            if ( e.Row.RowType == DataControlRowType.DataRow )
            {
                var rockContext = new RockContext();
                var restUser = e.Row.DataItem as Person;
                var noteService = new NoteService( rockContext );
                var description = noteService.Queryable().Where( a => a.EntityId == restUser.Id ).FirstOrDefault();
                Label lblDescription = e.Row.FindControl( "lblDescription" ) as Label;
                if ( description != null )
                {
                    lblDescription.Text = description.Text;
                }

                var userLoginService = new UserLoginService( rockContext );
                var userLogin = userLoginService.Queryable().Where( a => a.PersonId == restUser.Id ).FirstOrDefault();
                Label lblKey = e.Row.FindControl( "lblKey" ) as Label;
                if ( userLogin != null )
                {
                    lblKey.Text = userLogin.ApiKey;
                }
            }
        }
Example #22
0
        /// <summary>
        /// Creates a new <see cref="Rock.Model.UserLogin" /> and saves it to the database.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="person">The person.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="entityTypeId">The EntityTypeId of the <see cref="Rock.Model.EntityType"/> for the authentication service that this UserLogin user will use.</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="isRequirePasswordChange">if set to <c>true</c> [is require password change].</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentOutOfRangeException">username;Username already exists</exception>
        /// <exception cref="System.ArgumentException">
        /// entityTypeId
        /// or
        /// Invalid EntityTypeId, entity does not exist;entityTypeId
        /// or
        /// Invalid Person, person does not exist;person
        /// </exception>
        public static UserLogin Create(RockContext rockContext,
                                       Rock.Model.Person person,
                                       AuthenticationServiceType serviceType,
                                       int entityTypeId,
                                       string username,
                                       string password,
                                       bool isConfirmed,
                                       bool isRequirePasswordChange)
        {
            if (person != null)
            {
                var userLoginService = new UserLoginService(rockContext);

                var entityType = EntityTypeCache.Get(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;
                    user.IsPasswordChangeRequired = isRequirePasswordChange;

                    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.Get(Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext);
                    if (historyCategory != null)
                    {
                        var changes = new History.HistoryChangeList();
                        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>
        /// Shows the detail.
        /// </summary>
        /// <param name="restUserId">The rest user identifier.</param>
        public void ShowDetail( int restUserId )
        {
            var rockContext = new RockContext();

            Person restUser = null;

            if ( !restUserId.Equals( 0 ) )
            {
                restUser = new PersonService( rockContext ).Get( restUserId );
            }

            if ( restUser == null )
            {
                restUser = new Person { Id = 0 };
            }

            bool editAllowed = restUser.IsAuthorized( Authorization.EDIT, CurrentPerson );

            hfRestUserId.Value = restUser.Id.ToString();
            lTitle.Text = ActionTitle.Edit( "REST Key" ).FormatAsHtmlTitle();
            if ( restUser.Id > 0 )
            {
                tbName.Text = restUser.LastName;
                cbActive.Checked = false;
                var activeStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                if ( restUser.RecordStatusValueId == activeStatusId )
                {
                    cbActive.Checked = true;
                }

                var noteService = new NoteService( rockContext );
                var description = noteService.Queryable().Where( a => a.EntityId == restUser.Id ).FirstOrDefault();
                if ( description != null )
                {
                    tbDescription.Text = description.Text;
                }

                var userLoginService = new UserLoginService( rockContext );
                var userLogin = userLoginService.Queryable().Where( a => a.PersonId == restUser.Id ).FirstOrDefault();
                if ( userLogin != null )
                {
                    tbKey.Text = userLogin.ApiKey;
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );

            var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault();
            if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) )
            {
                // this key already exists in the database. Show the error and get out of here.
                nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. ";
                nbWarningMessage.Visible = true;
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var restUser = new Person();
                if ( int.Parse( hfRestUserId.Value ) != 0 )
                {
                    restUser = personService.Get( int.Parse( hfRestUserId.Value ) );
                }
                else
                {
                    personService.Add( restUser );
                    rockContext.SaveChanges();
                    restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } );
                }

                // the rest user name gets saved as the last name on a person
                History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text );
                restUser.LastName = tbName.Text;
                restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id;
                if ( cbActive.Checked )
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;
                }
                else
                {
                    restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id;
                }

                if ( restUser.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                restUser.Id,
                                changes );
                        }
                    }
                }

                // the description gets saved as a system note for the person
                var noteType = new NoteTypeService( rockContext )
                    .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                var noteService = new NoteService( rockContext );
                var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault();
                if ( note == null )
                {
                    note = new Note();
                    noteService.Add( note );
                }

                note.NoteTypeId = noteType.Id;
                note.EntityId = restUser.Id;
                note.Text = tbDescription.Text;
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService( rockContext )
                    .Get( "Rock.Security.Authentication.Database" );
                userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault();
                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    userLoginService.Add( userLogin );
                }

                if ( string.IsNullOrWhiteSpace( userLogin.UserName ) )
                {
                    userLogin.UserName = Guid.NewGuid().ToString();
                }

                userLogin.IsConfirmed = true;
                userLogin.ApiKey = tbKey.Text;
                userLogin.PersonId = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();
            } );
            NavigateToParentPage();
        }
        /// <summary>
        /// Handles the Click event of the lbGenerate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbGenerate_Click( object sender, EventArgs e )
        {
            // Generate a unique random 12 digit api key
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );
            var key = string.Empty;
            var isGoodKey = false;
            while ( isGoodKey == false )
            {
                key = GenerateKey();
                var userLogins = userLoginService.Queryable().Where( a => a.ApiKey == key );
                if ( userLogins.Count() == 0 )
                {
                    // no other user login has this key.
                    isGoodKey = true;
                }
            }

            tbKey.Text = key;
        }
Example #26
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            Guid?communicationGuid = context.Request.QueryString["c"].AsGuidOrNull();

            if (communicationGuid.HasValue)
            {
                var rockContext   = new RockContext();
                var communication = new CommunicationService(rockContext).Get(communicationGuid.Value);

                if (communication != null)
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Communication", communication);

                    Person person = null;

                    string encodedKey = context.Request.QueryString["p"];
                    if (!string.IsNullOrWhiteSpace(encodedKey))
                    {
                        // first try and see if we can use the new GetByPersonActionIdentifier() otherwise
                        // fall-back to the old GetByImpersonationToken method.
                        var personService = new PersonService(rockContext);
                        person = personService.GetByPersonActionIdentifier(encodedKey, "Unsubscribe");
                        if (person == null)
                        {
                            // TODO: Support for trying via impersonation token should be removed once we get to Rock v11
                            person = personService.GetByImpersonationToken(encodedKey, true, null);
                        }
                    }

                    if (person == null)
                    {
                        var principal = context.User;
                        if (principal != null && principal.Identity != null)
                        {
                            var userLoginService = new Rock.Model.UserLoginService(new RockContext());
                            var userLogin        = userLoginService.GetByUserName(principal.Identity.Name);

                            if (userLogin != null)
                            {
                                var currentPerson = userLogin.Person;
                                // if a person wasn't specified in the URL, then only show it if the current person has EDIT auth to the communication
                                if (communication.IsAuthorized(Authorization.EDIT, currentPerson))
                                {
                                    person = currentPerson;
                                }
                            }
                        }
                    }

                    if (person != null)
                    {
                        mergeFields.Add("Person", person);

                        var recipient = new CommunicationRecipientService(rockContext).Queryable()
                                        .Where(r =>
                                               r.CommunicationId == communication.Id &&
                                               r.PersonAlias != null &&
                                               r.PersonAlias.PersonId == person.Id)
                                        .FirstOrDefault();

                        if (recipient != null)
                        {
                            // Add any additional merge fields created through a report
                            foreach (var mergeField in recipient.AdditionalMergeValues)
                            {
                                if (!mergeFields.ContainsKey(mergeField.Key))
                                {
                                    mergeFields.Add(mergeField.Key, mergeField.Value);
                                }
                            }
                        }

                        context.Response.ContentType = "text/html";
                        context.Response.Write(GetHtmlPreview(communication, mergeFields));

                        if (recipient != null)
                        {
                            // write an 'opened' interaction
                            var interactionService = new InteractionService(rockContext);

                            InteractionComponent interactionComponent = new InteractionComponentService(rockContext)
                                                                        .GetComponentByEntityId(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid(),
                                                                                                communication.Id, communication.Subject);
                            rockContext.SaveChanges();

                            var ipAddress = Rock.Web.UI.RockPage.GetClientIpAddress();

                            var userAgent = context.Request.UserAgent ?? "";

                            UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(userAgent);
                            var clientOs      = client.OS.ToString();
                            var clientBrowser = client.UA.ToString();
                            var clientType    = InteractionDeviceType.GetClientType(userAgent);

                            interactionService.AddInteraction(interactionComponent.Id, recipient.Id, "Opened", "", recipient.PersonAliasId, RockDateTime.Now, clientBrowser, clientOs, clientType, userAgent, ipAddress, null);

                            rockContext.SaveChanges();
                        }

                        return;
                    }
                }
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("Sorry, the communication you requested does not exist, or you are not authorized to view it.");
            return;
        }
Example #27
0
        private UserLogin SetNewPassword( UserLogin user, string rawPassword )
        {
            string hash =  EncodeBcrypt( rawPassword );
            if ( hash == null )
            {
                throw new NotImplementedException( "Could not generate hash from password." );
            }

            using ( var context = new RockContext() )
            {
                var userService = new UserLoginService( context );
                var contextUser = userService.Get( user.Id );
                contextUser.Password = hash;
                context.SaveChanges();
                return contextUser;
            }
        }
Example #28
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);
            }
        }
Example #29
0
        /// <summary>
        /// Handles the Click event of the btnSend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSend_Click( object sender, EventArgs e )
        {
            var url = LinkedPageUrl( "ConfirmationPage" );
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                url = ResolveRockUrl( "~/ConfirmAccount" );
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );
            var results = new List<IDictionary<string, object>>();

            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );
            var userLoginService = new UserLoginService( rockContext );

            bool hasAccountWithPasswordResetAbility = false;
            List<string> accountTypes = new List<string>();

            foreach ( Person person in personService.GetByEmail( tbEmail.Text )
                .Where( p => p.Users.Any()))
            {
                var users = new List<UserLogin>();
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( !component.RequiresRemoteAuthentication )
                        {
                            users.Add( user );
                            hasAccountWithPasswordResetAbility = true;
                        }

                        accountTypes.Add( user.EntityType.FriendlyName );
                    }
                }

                var resultsDictionary = new Dictionary<string, object>();
                resultsDictionary.Add( "Person", person);
                resultsDictionary.Add( "Users", users );
                results.Add( resultsDictionary );
            }

            if ( results.Count > 0 && hasAccountWithPasswordResetAbility )
            {
                mergeFields.Add( "Results", results.ToArray() );
                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( tbEmail.Text, mergeFields ) );

                Email.Send( GetAttributeValue( "EmailTemplate" ).AsGuid(), recipients, ResolveRockUrlIncludeRoot( "~/" ), ResolveRockUrlIncludeRoot( "~~/" ), false );

                pnlEntry.Visible = false;
                pnlSuccess.Visible = true;
            }
            else if (results.Count > 0 )
            {
                // the person has user accounts but none of them are allowed to have their passwords reset (Facebook/Google/etc)

                lWarning.Text = string.Format( @"<p>We were able to find the following accounts for this email, but
                                                none of them are able to be reset from this website.</p> <p>Accounts:<br /> {0}</p>
                                                <p>To create a new account with a username and password please see our <a href='{1}'>New Account</a>
                                                page.</p>"
                                    , string.Join( ",", accountTypes )
                                    , ResolveRockUrl( "~/NewAccount" ) );
                pnlWarning.Visible = true;
            }
            else
            {
                pnlWarning.Visible = true;
            }
        }
Example #30
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit( int userLoginId )
        {
            UserLogin userLogin = null;
            if (userLoginId > 0)
            {
                userLogin = new UserLoginService().Get( userLoginId );
            }

            if (userLogin == null)
            { 
                userLogin = new UserLogin { Id = 0, IsConfirmed = true };
            }

            tbUserName.Text = userLogin.UserName;
            cbIsConfirmed.Checked = userLogin.IsConfirmed ?? false;
            cbIsLockedOut.Checked = userLogin.IsLockedOut ?? false;
            if ( userLogin.EntityType != null )
            {
                compProvider.SetValue( userLogin.EntityType.Guid.ToString() );
            }

            hfIdValue.Value = userLogin.Id.ToString();

            SetPasswordState();

            mdDetails.Show();
        }        
Example #31
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);

            ISecured item = Rock.Web.Cache.RestActionCache.Read(actionMethod + actionPath);

            if (item == null)
            {
                item = Rock.Web.Cache.RestControllerCache.Read(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.GetByEncryptedKey(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);
                        }
                    }
                }
            }

            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>
        /// Displays the sent login.
        /// </summary>
        /// <param name="direction">The direction.</param>
        private void DisplaySentLogin( Direction direction )
        {
            var rockContext = new RockContext();
            PersonService personService = new PersonService( rockContext );
            Person person = personService.Get( hfSendPersonId.Value.AsInteger() ?? 0 );
            if ( person != null )
            {
                string url = LinkedPageUrl( "ConfirmationPage" );
                if ( string.IsNullOrWhiteSpace( url ) )
                {
                    url = ResolveRockUrl( "~/ConfirmAccount" );
                }

                var mergeObjects = new Dictionary<string, object>();
                mergeObjects.Add( "ConfirmAccountUrl", RootPath + url.TrimStart( new char[] { '/' } ) );

                var personDictionaries = new List<IDictionary<string, object>>();

                var users = new List<UserLogin>();
                var userLoginService = new UserLoginService( rockContext );
                foreach ( UserLogin user in userLoginService.GetByPersonId( person.Id ) )
                {
                    if ( user.EntityType != null )
                    {
                        var component = AuthenticationContainer.GetComponent( user.EntityType.Name );
                        if ( component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            users.Add( user );
                        }
                    }
                }

                if ( users.Count > 0 )
                {
                    var personDictionary = person.ToLiquid() as Dictionary<string, object>;
                    if ( personDictionary.Keys.Contains( "Users" ) )
                    {
                        personDictionary["Users"] = users;
                    }
                    else
                    {
                        personDictionary.Add( "Users", users );
                    }

                    personDictionaries.Add( personDictionary );
                }

                mergeObjects.Add( "Persons", personDictionaries.ToArray() );

                var recipients = new Dictionary<string, Dictionary<string, object>>();
                recipients.Add( person.Email, mergeObjects );

                Email.Send( GetAttributeValue( "ForgotUsernameTemplate" ).AsGuid(), recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
            }
            else
            {
                ShowErrorMessage( "Invalid Person" );
            }

            ShowPanel( 3 );
        }
        /// <summary>
        /// Handles the Click event of the btnUserInfoNext control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnUserInfoNext_Click( object sender, EventArgs e )
        {
            Password = tbPassword.Text;
            PasswordConfirm = tbPasswordConfirm.Text;

            if ( Page.IsValid )
            {
                if ( UserLoginService.IsPasswordValid( Password ) )
                {
                    var userLoginService = new Rock.Model.UserLoginService( new RockContext() );
                    var userLogin = userLoginService.GetByUserName( tbUserName.Text );

                    if ( userLogin == null )
                    {
                        DisplayDuplicates( Direction.Forward );
                    }
                    else
                    {
                        ShowErrorMessage( "Username already exists" );
                    }
                }
                else
                {
                    ShowErrorMessage( UserLoginService.FriendlyPasswordRules() );
                }
            }
        }
Example #34
0
        /// <summary>
        /// Updates the last login and writes to the person's history log
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public static void UpdateLastLogin(string userName)
        {
            if (!string.IsNullOrWhiteSpace(userName))
            {
                using (var rockContext = new RockContext())
                {
                    int? personId     = null;
                    bool impersonated = userName.StartsWith("rckipid=");

                    if (!impersonated)
                    {
                        var userLogin = new UserLoginService(rockContext).GetByUserName(userName);
                        if (userLogin != null)
                        {
                            userLogin.LastLoginDateTime = RockDateTime.Now;
                            personId = userLogin.PersonId;
                        }
                    }
                    else
                    {
                        var impersonationToken = userName.Substring(8);
                        personId = new PersonService(rockContext).GetByImpersonationToken(impersonationToken, false, null)?.Id;
                    }

                    if (personId.HasValue)
                    {
                        var relatedDataBuilder  = new System.Text.StringBuilder();
                        int?relatedEntityTypeId = null;
                        int?relatedEntityId     = null;

                        if (impersonated)
                        {
                            var impersonatedByUser = HttpContext.Current?.Session["ImpersonatedByUser"] as UserLogin;

                            relatedEntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>();
                            relatedEntityId     = impersonatedByUser?.PersonId;

                            if (impersonatedByUser != null)
                            {
                                relatedDataBuilder.Append($" impersonated by { impersonatedByUser.Person.FullName }");
                            }
                        }

                        if (HttpContext.Current != null && HttpContext.Current.Request != null)
                        {
                            string cleanUrl = PersonToken.ObfuscateRockMagicToken(HttpContext.Current.Request.Url.AbsoluteUri);

                            // obfuscate the url specified in the returnurl, just in case it contains any sensitive information (like a rckipid)
                            Regex returnurlRegEx = new Regex(@"returnurl=([^&]*)");
                            cleanUrl = returnurlRegEx.Replace(cleanUrl, "returnurl=XXXXXXXXXXXXXXXXXXXXXXXXXXXX");

                            relatedDataBuilder.AppendFormat(" to <span class='field-value'>{0}</span>, from <span class='field-value'>{1}</span>",
                                                            cleanUrl, HttpContext.Current.Request.UserHostAddress);
                        }

                        var historyChangeList = new History.HistoryChangeList();
                        var historyChange     = historyChangeList.AddChange(History.HistoryVerb.Login, History.HistoryChangeType.Record, userName);

                        if (relatedDataBuilder.Length > 0)
                        {
                            historyChange.SetRelatedData(relatedDataBuilder.ToString(), null, null);
                        }

                        HistoryService.SaveChanges(rockContext, typeof(Rock.Model.Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), personId.Value, historyChangeList, true);
                    }
                }
            }
        }
Example #35
0
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/> of the user who is currently logged in, and updates their last activity date if userIsOnline=true
        /// </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.PersonTokenService personTokenService = new Model.PersonTokenService(rockContext);
                    Rock.Model.PersonToken        personToken        = personTokenService.GetByImpersonationToken(userName.Substring(8));
                    if (personToken?.PersonAlias?.Person != null)
                    {
                        return(personToken.PersonAlias.Person.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);

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

                    return(user);
                }
            }

            return(null);
        }
Example #36
0
        /// <summary>
        /// Gets the name of the facebook user.
        /// </summary>
        /// <param name="facebookUser">The facebook user.</param>
        /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetFacebookUserName( FacebookUser facebookUser, bool syncFriends = false, string accessToken = "" )
        {
            string username = string.Empty;
            string facebookId = facebookUser.id;
            string facebookLink = facebookUser.link;

            string userName = "******" + facebookId;
            UserLogin user = null;

            using ( var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService( rockContext );
                user = userLoginService.GetByUserName( userName );

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                {
                    // Get name/email from Facebook login
                    string lastName = facebookUser.last_name.ToStringSafe();
                    string firstName = facebookUser.first_name.ToStringSafe();
                    string email = string.Empty;
                    try { email = facebookUser.email.ToStringSafe(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace( email ) )
                    {
                        var personService = new PersonService( rockContext );
                        var people = personService.GetByMatch( firstName, lastName, email );
                        if ( people.Count() == 1)
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;

                    rockContext.WrapTransaction( () =>
                    {
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            try
                            {
                                if ( facebookUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( facebookUser.gender.ToString() == "female" )
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if ( person != null )
                            {
                                PersonService.SaveNewPerson( person, rockContext, null, false );
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id;
                            user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true );
                        }

                    } );
                }

                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService( rockContext );
                        var person = personService.Get( user.PersonId.Value );
                        if ( person != null )
                        {
                            // If person does not have a photo, try to get their Facebook photo
                            if ( !person.PhotoId.HasValue )
                            {
                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId ) );
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );
                                var restResponse = restClient.Execute( restRequest );
                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    dynamic picData = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    bool isSilhouette = picData.data.is_silhouette;
                                    string url = picData.data.url;

                                    // If Facebook returned a photo url
                                    if ( !isSilhouette && !string.IsNullOrWhiteSpace( url ) )
                                    {
                                        // Download the photo from the url provided
                                        restClient = new RestClient( url );
                                        restRequest = new RestRequest( Method.GET );
                                        restResponse = restClient.Execute( restRequest );
                                        if ( restResponse.StatusCode == HttpStatusCode.OK )
                                        {
                                            var bytes = restResponse.RawBytes;

                                            // Create and save the image
                                            BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                            if ( fileType != null )
                                            {
                                                var binaryFileService = new BinaryFileService( rockContext );
                                                var binaryFile = new BinaryFile();
                                                binaryFileService.Add( binaryFile );
                                                binaryFile.IsTemporary = false;
                                                binaryFile.BinaryFileType = fileType;
                                                binaryFile.MimeType = "image/jpeg";
                                                binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg";
                                                binaryFile.ContentStream = new MemoryStream( bytes );

                                                rockContext.SaveChanges();

                                                person.PhotoId = binaryFile.Id;
                                                rockContext.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }

                            // Save the facebook social media link
                            var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() );
                            if ( facebookAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( facebookAttribute.Key, facebookLink );
                                person.SaveAttributeValues( rockContext );
                            }

                            if ( syncFriends && !string.IsNullOrWhiteSpace( accessToken ) )
                            {
                                // Get the friend list (only includes friends who have also authorized this app)
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.AddParameter( "access_token", accessToken );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );

                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/friends", facebookId ) );
                                var restResponse = restClient.Execute( restRequest );

                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    // Get a list of the facebook ids for each friend
                                    dynamic friends = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    var facebookIds = new List<string>();
                                    foreach ( var friend in friends.data )
                                    {
                                        facebookIds.Add( friend.id );
                                    }

                                    // Queue a transaction to add/remove friend relationships in Rock
                                    var transaction = new Rock.Transactions.UpdateFacebookFriends( person.Id, facebookIds );
                                    Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
                                }
                            }
                        }

                    }
                }

                return username;
            }
        }
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int? siteId = GetAttributeValue( "Site" ).AsIntegerOrNull();
            if (!siteId.HasValue)
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int? pageViewCount = GetAttributeValue( "PageViewCount" ).AsIntegerOrNull();
                if ( !pageViewCount.HasValue || pageViewCount.Value == 0 )
                {
                    pageViewCount = 1;
                }

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read( siteId.Value );
                lSiteName.Text = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue( "ShowSiteNameAsTitle" ).AsBoolean();

                lMessages.Text = string.Empty;

                using ( var rockContext = new RockContext() )
                {
                    IQueryable<PageView> pageViewQry = new PageViewService( rockContext ).Queryable( "Page" );

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService( rockContext ).Queryable( "Person" )
                        .Where( l =>
                            l.PersonId.HasValue &&
                            l.IsOnLine == true )
                        .OrderByDescending( l => l.LastActivityDateTime )
                        .Select( l => new
                        {
                            login = l,
                            pageViews = pageViewQry
                                .Where( v => v.PersonAlias.PersonId == l.PersonId )
                                .OrderByDescending( v => v.DateTimeViewed )
                                .Take( pageViewCount.Value )
                        } )
                        .Where( a =>
                            a.pageViews.Any() &&
                            a.pageViews.FirstOrDefault().SiteId == site.Id );

                    if ( CurrentUser != null )
                    {
                        activeLogins = activeLogins.Where( m => m.login.UserName != CurrentUser.UserName );
                    }

                    foreach ( var activeLogin in activeLogins )
                    {
                        var login = activeLogin.login;
                        var pageViews = activeLogin.pageViews.ToList();
                        Guid? latestSession = pageViews.FirstOrDefault().SessionId;

                        string pageViewsHtml = activeLogin.pageViews.ToList()
                                                .Where( v => v.SessionId == latestSession )
                                                .Select( v => HttpUtility.HtmlEncode( v.Page.PageTitle ) ).ToList().AsDelimited( "<br> " );

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract( login.LastActivityDateTime.Value ) : TimeSpan.MaxValue;
                        string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personLink = login.Person.FullName;

                        if ( GetAttributeValue( "PersonProfilePage" ) != null )
                        {
                            string personProfilePage = GetAttributeValue( "PersonProfilePage" );
                            var pageParams = new Dictionary<string, string>();
                            pageParams.Add( "PersonId", login.Person.Id.ToString() );
                            var pageReference = new Rock.Web.PageReference( personProfilePage, pageParams );
                            personLink = string.Format( @"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), login.Person.FullName );
                        }

                        // determine whether to show last page views
                        if ( GetAttributeValue( "PageViewCount" ).AsInteger() > 0 )
                        {
                            string format = @"
            <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";

                            sbUsers.Append( string.Format( format, className, personLink, pageViewsHtml ) );
                        }
                        else
                        {
                            string format = @"
            <li class='active-user {0}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            sbUsers.Append( string.Format( format, className, personLink ) );
                        }
                    }
                }

                if ( sbUsers.Length > 0 )
                {
                    lUsers.Text = string.Format( @"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString() );
                }
                else
                {
                    lMessages.Text = string.Format( "There are no logged in users on the {0} site.", site.Name );
                }
            }
        }
Example #38
0
        /// <summary>
        /// Maps the notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        public void MapNotes( IQueryable<Row> tableData )
        {
            var lookupContext = new RockContext();
            var categoryService = new CategoryService( lookupContext );
            var personService = new PersonService( lookupContext );

            var noteTypes = new NoteTypeService( lookupContext ).Queryable().AsNoTracking().ToList();
            var personalNoteType = noteTypes.FirstOrDefault( nt => nt.Guid == new Guid( Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE ) );

            var importedUsers = new UserLoginService( lookupContext ).Queryable().AsNoTracking()
                .Where( u => u.ForeignId != null )
                .ToDictionary( t => t.ForeignId, t => t.PersonId );

            var noteList = new List<Note>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying note import ({0:N0} found).", totalRows ) );
            foreach ( var row in tableData.Where( r => r != null ) )
            {
                string text = row["Note_Text"] as string;
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                var noteTypeActive = row["NoteTypeActive"] as Boolean?;

                bool noteArchived = false;
                if ( row.Columns.FirstOrDefault( v => v.Name.Equals( "IsInactive" ) ) != null )
                {
                    /* =====================================================================
                    *  the NoteArchived column *should* work, but OrcaMDF won't read it...
                    *  instead check for a manually added column: IsInactive int null
                    *       var noteActive = row["NoteArchived"] as Boolean?;
                    *       if ( noteActive == null ) throw new NullReferenceException();
                    /* ===================================================================== */
                    var rowInactiveValue = row["IsInactive"] as int?;
                    noteArchived = rowInactiveValue.Equals( 1 );
                }

                var personKeys = GetPersonKeys( individualId, householdId );
                if ( personKeys != null && !string.IsNullOrWhiteSpace( text ) && noteTypeActive == true && !noteArchived )
                {
                    DateTime? dateCreated = row["NoteCreated"] as DateTime?;
                    string noteType = row["Note_Type_Name"] as string;

                    var note = new Note();
                    note.CreatedDateTime = dateCreated;
                    note.EntityId = personKeys.PersonId;

                    // These replace methods don't like being chained together
                    text = Regex.Replace( text, @"\t|\&nbsp;", " " );
                    text = text.Replace( "&#45;", "-" );
                    text = text.Replace( "&lt;", "<" );
                    text = text.Replace( "&gt;", ">" );
                    text = text.Replace( "&amp;", "&" );
                    text = text.Replace( "&quot;", @"""" );
                    text = text.Replace( "&#x0D", string.Empty );

                    note.Text = text.Trim();

                    int? userId = row["NoteCreatedByUserID"] as int?;
                    if ( userId != null && importedUsers.ContainsKey( userId ) )
                    {
                        var userKeys = ImportedPeople.FirstOrDefault( p => p.PersonId == (int)importedUsers[userId] );
                        if ( userKeys != null )
                        {
                            note.CreatedByPersonAliasId = userKeys.PersonAliasId;
                        }
                    }

                    int? matchingNoteTypeId = null;
                    if ( !noteType.StartsWith( "General", StringComparison.InvariantCultureIgnoreCase ) )
                    {
                        matchingNoteTypeId = noteTypes.Where( nt => nt.Name == noteType ).Select( i => (int?)i.Id ).FirstOrDefault();
                    }
                    else
                    {
                        matchingNoteTypeId = personalNoteType.Id;
                    }

                    if ( matchingNoteTypeId != null )
                    {
                        note.NoteTypeId = (int)matchingNoteTypeId;
                    }
                    else
                    {
                        // create the note type
                        var newNoteType = new NoteType();
                        newNoteType.EntityTypeId = personalNoteType.EntityTypeId;
                        newNoteType.EntityTypeQualifierColumn = string.Empty;
                        newNoteType.EntityTypeQualifierValue = string.Empty;
                        newNoteType.UserSelectable = true;
                        newNoteType.IsSystem = false;
                        newNoteType.Name = noteType;
                        newNoteType.Order = 0;

                        lookupContext.NoteTypes.Add( newNoteType );
                        lookupContext.SaveChanges( DisableAuditing );

                        noteTypes.Add( newNoteType );
                        note.NoteTypeId = newNoteType.Id;
                    }

                    noteList.Add( note );
                    completed++;

                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} notes imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveNotes( noteList );
                        ReportPartialProgress();
                        noteList.Clear();
                    }
                }
            }

            if ( noteList.Any() )
            {
                SaveNotes( noteList );
            }

            ReportProgress( 100, string.Format( "Finished note import: {0:N0} notes imported.", completed ) );
        }
Example #39
0
        private Rock.Model.UserLogin CreateUser(Person person, bool confirmed)
        {
            var userLoginService = new Rock.Model.UserLoginService();

            return(userLoginService.Create(person, Rock.Model.AuthenticationServiceType.Internal, "Rock.Security.Authentication.Database", tbUserName.Text, Password, confirmed, CurrentPersonId));
        }
Example #40
0
        /// <summary>
        /// Generates the username.
        /// </summary>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="tryCount">The try count.</param>
        /// <returns></returns>
        public static string GenerateUsername( string firstName, string lastName, int tryCount = 0 )
        {
            // create username
            string username = (firstName.Substring( 0, 1 ) + lastName).ToLower();

            if ( tryCount != 0 )
            {
                username = username + tryCount.ToString();
            }

            // check if username exists
            UserLoginService userService = new UserLoginService( new RockContext() );
            var loginExists = userService.Queryable().Where( l => l.UserName == username ).Any();
            if ( !loginExists )
            {
                return username;
            }
            else
            {
                return Database.GenerateUsername( firstName, lastName, tryCount + 1 );
            }
        }
Example #41
0
        /// <summary>
        /// Handles the Delete event of the gUserLogins control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gUserLogins_Delete( object sender, RowEventArgs e )
        {
            if ( _canEdit )
            {
                var service = new UserLoginService();
                var userLogin = service.Get( (int)e.RowKeyValue );

                if ( userLogin != null )
                {
                    string errorMessage;
                    if ( !service.CanDelete( userLogin, out errorMessage ) )
                    {
                        maGridWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    service.Delete( userLogin, CurrentPersonId );
                    service.Save( userLogin, CurrentPersonId );

                }
            }
            BindGrid();
        }
 /// <summary>
 /// Handles the Click event of the btnDuplicatesNext control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected void btnDuplicatesNext_Click( object sender, EventArgs e )
 {
     int personId = Request.Form["DuplicatePerson"].AsInteger() ?? 0;
     if ( personId > 0 )
     {
         var userLoginService = new Rock.Model.UserLoginService( new RockContext() );
         var userLogins = userLoginService.GetByPersonId( personId ).ToList();
         if ( userLogins.Count > 0 )
         {
             DisplaySendLogin( personId, Direction.Forward );
         }
         else
         {
             DisplayConfirmation( personId );
         }
     }
     else
     {
         DisplaySuccess( CreateUser( CreatePerson(), true ) );
     }
 }
Example #43
0
        /// <summary>
        /// Handles the SaveClick event of the modalDetails control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void mdDetails_SaveClick( object sender, EventArgs e )
        {
            if ( _canEdit )
            {
                UserLogin userLogin = null;
                var service = new UserLoginService();

                int userLoginId = int.Parse( hfIdValue.Value );

                if ( userLoginId != 0 )
                {
                    userLogin = service.Get( userLoginId );
                }

                if ( userLogin == null )
                {
                    userLogin = new UserLogin();
                    service.Add( userLogin, CurrentPersonId );
                }

                userLogin.UserName = tbUserName.Text;
                userLogin.IsConfirmed = cbIsConfirmed.Checked;
                userLogin.IsLockedOut = cbIsLockedOut.Checked;

                var entityType = EntityTypeCache.Read( compProvider.SelectedValue.AsGuid() );
                if ( entityType != null )
                {
                    userLogin.EntityTypeId = entityType.Id;

                    if ( !string.IsNullOrWhiteSpace( tbPassword.Text ) )
                    {
                        var component = AuthenticationContainer.GetComponent( entityType.Name );
                        if ( component != null && component.ServiceType == AuthenticationServiceType.Internal )
                        {
                            if ( tbPassword.Text == tbPasswordConfirm.Text )
                            {
                                if ( UserLoginService.IsPasswordValid( tbPassword.Text ) )
                                {
                                    userLogin.Password = component.EncodePassword( userLogin, tbPassword.Text );
                                    userLogin.LastPasswordChangedDateTime = DateTime.Now;
                                }
                                else
                                {
                                    nbErrorMessage.Title = "Invalid Password";
                                    nbErrorMessage.Text = UserLoginService.FriendlyPasswordRules();
                                    nbErrorMessage.Visible = true;
                                    return;
                                }
                            }
                            else
                            {
                                nbErrorMessage.Title = "Invalid Password";
                                nbErrorMessage.Text = "Password and Confirmation do not match.";
                                nbErrorMessage.Visible = true;
                                return;
                            }
                        }
                    }
                }

                if ( !userLogin.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                RockTransactionScope.WrapTransaction( () =>
                {
                    service.Save( userLogin, CurrentPersonId );
                } );

                mdDetails.Hide();
                BindGrid();
            }
        }
 /// <summary>
 /// Creates the user.
 /// </summary>
 /// <param name="person">The person.</param>
 /// <param name="confirmed">if set to <c>true</c> [confirmed].</param>
 /// <returns></returns>
 private Rock.Model.UserLogin CreateUser( Person person, bool confirmed )
 {
     var rockContext = new RockContext();
     var userLoginService = new Rock.Model.UserLoginService( rockContext );
     return UserLoginService.Create(
         rockContext,
         person,
         Rock.Model.AuthenticationServiceType.Internal,
         EntityTypeCache.Read( Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid() ).Id,
         tbUserName.Text,
         Password,
         confirmed );
 }
Example #45
0
        private void BindGrid()
        {
            var qry = new UserLoginService().Queryable()
                .Where( l => !_personId.HasValue || l.PersonId == _personId.Value );

            // username filter
            string usernameFilter =  gfSettings.GetUserPreference( "Username" );
            if (!string.IsNullOrWhiteSpace(usernameFilter))
            {
                qry = qry.Where( l => l.UserName.StartsWith( usernameFilter ) );
            }

            // provider filter
            Guid guid = Guid.Empty;
            if (Guid.TryParse(gfSettings.GetUserPreference( "Authentication Provider" ), out guid))
            {
                qry = qry.Where( l => l.EntityType.Guid.Equals( guid ) );
            }

            // created filter
            var drp = new DateRangePicker();
            drp.DelimitedValues = gfSettings.GetUserPreference( "Created" );
            if ( drp.LowerValue.HasValue )
            {
                qry = qry.Where( l => l.CreationDateTime >= drp.LowerValue.Value );
            }
            if ( drp.UpperValue.HasValue )
            {
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( l => l.CreationDateTime < upperDate );
            }

            // last login filter
            var drp2 = new DateRangePicker();
            drp2.DelimitedValues = gfSettings.GetUserPreference( "Last Login" );
            if ( drp2.LowerValue.HasValue )
            {
                qry = qry.Where( l => l.LastLoginDateTime >= drp2.LowerValue.Value );
            }
            if ( drp2.UpperValue.HasValue )
            {
                DateTime upperDate = drp2.UpperValue.Value.Date.AddDays( 1 );
                qry = qry.Where( l => l.LastLoginDateTime < upperDate );
            }

            // Is Confirmed filter
            bool isConfirmed = false;
            if (bool.TryParse(gfSettings.GetUserPreference( "Is Confirmed" ), out isConfirmed))
            {
                qry = qry.Where( l => l.IsConfirmed == isConfirmed || ( !isConfirmed && l.IsConfirmed == null ) );
            }

            // is locked out filter
            bool isLockedOut = false;
            if ( bool.TryParse( gfSettings.GetUserPreference( "Is Locked Out" ), out isLockedOut ) )
            {
                qry = qry.Where( l => l.IsLockedOut == isLockedOut || ( !isLockedOut && l.IsLockedOut == null ) );
            }

            // Sort
            SortProperty sortProperty = gUserLogins.SortProperty;
            if ( sortProperty == null )
            {
                sortProperty = new SortProperty( new GridViewSortEventArgs( "UserName", SortDirection.Ascending ) );
            }

            gUserLogins.DataSource = qry.Sort( sortProperty )
                .Select( l => new
                    {
                        Id = l.Id,
                        UserName = l.UserName,
                        PersonId = l.PersonId,
                        PersonName = l.Person.LastName + ", " + l.Person.NickName,
                        ProviderName = l.EntityType.FriendlyName,
                        CreationDateTime = l.CreationDateTime,
                        LastLoginDateTime = l.LastLoginDateTime,
                        IsConfirmed = l.IsConfirmed,
                        IsLockedOut = l.IsLockedOut
                    }
                ).ToList();
            gUserLogins.DataBind();
        }
        /// <summary>
        /// Handles the Click event of the btnLogin control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnLogin_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var userLoginService = new UserLoginService(rockContext);
                var userLogin = userLoginService.GetByUserName( tbUserName.Text );
                if ( userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component.IsActive && !component.RequiresRemoteAuthentication)
                    {
                        if ( component.Authenticate( userLogin, tbPassword.Text ) )
                        {
                            if ( ( userLogin.IsConfirmed ?? true ) && !(userLogin.IsLockedOut ?? false ) )
                            {
                                string returnUrl = Request.QueryString["returnurl"];
                                LoginUser( tbUserName.Text, returnUrl, cbRememberMe.Checked );
                            }
                            else
                            {
                                var globalMergeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(null);

                                if ( userLogin.IsLockedOut ?? false )
                                {
                                    lLockedOutCaption.Text = GetAttributeValue( "LockedOutCaption" ).ResolveMergeFields( globalMergeFields );

                                    pnlLogin.Visible = false;
                                    pnlLockedOut.Visible = true;
                                }
                                else
                                {
                                    SendConfirmation( userLogin );

                                    lConfirmCaption.Text = GetAttributeValue( "ConfirmCaption" ).ResolveMergeFields( globalMergeFields );

                                    pnlLogin.Visible = false;
                                    pnlConfirmation.Visible = true;
                                }
                            }

                            return;
                        }
                    }
                }
            }

            string helpUrl = string.Empty;

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("HelpPage")))
            {
                helpUrl = LinkedPageUrl("HelpPage");
            }
            else
            {
                helpUrl = ResolveRockUrl("~/ForgotUserName");
            }

            DisplayError( string.Format("Sorry, we couldn't find an account matching that username/password. Can we help you <a href='{0}'>recover your account information</a>?", helpUrl) );
        }
Example #47
0
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context.  Takes
        /// care of logging any particular change history for user login.
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="entry"></param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, DbEntityEntry entry)
        {
            var rockContext = ( RockContext )dbContext;

            HistoryChanges = new History.HistoryChangeList();

            switch (entry.State)
            {
            case EntityState.Added:
            {
                // Get the authentication provider entity type
                var entityType = EntityTypeCache.Get(this.EntityTypeId ?? 0);
                var change     = HistoryChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Authentication Provider").SetNewValue(entityType?.FriendlyName);

                // Don't log Pin Authentication user names.
                var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false;

                if (isUserNameSensitive)
                {
                    change.SetCaption("User Account");
                }

                History.EvaluateChange(HistoryChanges, "User Login", string.Empty, UserName, isUserNameSensitive);
                History.EvaluateChange(HistoryChanges, "Is Confirmed", null, IsConfirmed);
                History.EvaluateChange(HistoryChanges, "Is Password Change Required", null, IsPasswordChangeRequired);
                History.EvaluateChange(HistoryChanges, "Is Locked Out", null, IsLockedOut);

                break;
            }

            case EntityState.Modified:
            {
                var entityType = EntityTypeCache.Get(this.EntityTypeId ?? 0);

                // Don't log Pin Authentication user names.
                var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false;

                History.EvaluateChange(HistoryChanges, "User Login", entry.OriginalValues["UserName"].ToStringSafe(), UserName, isUserNameSensitive);
                History.EvaluateChange(HistoryChanges, "Is Confirmed", entry.OriginalValues["IsConfirmed"].ToStringSafe().AsBooleanOrNull(), IsConfirmed);
                History.EvaluateChange(HistoryChanges, "Is Password Change Required", entry.OriginalValues["IsPasswordChangeRequired"].ToStringSafe().AsBooleanOrNull(), IsPasswordChangeRequired);
                History.EvaluateChange(HistoryChanges, "Is Locked Out", entry.OriginalValues["IsLockedOut"].ToStringSafe().AsBooleanOrNull(), IsLockedOut);
                History.EvaluateChange(HistoryChanges, "Password", entry.OriginalValues["Password"].ToStringSafe(), Password, true);

                // Did the provider type change?
                int?origEntityTypeId = entry.OriginalValues["EntityTypeId"].ToStringSafe().AsIntegerOrNull();
                int?entityTypeId     = EntityType != null ? EntityType.Id : EntityTypeId;
                if (!entityTypeId.Equals(origEntityTypeId))
                {
                    var origProviderType = EntityTypeCache.Get(origEntityTypeId ?? 0)?.FriendlyName;
                    var providerType     = EntityTypeCache.Get(this.EntityTypeId ?? 0)?.FriendlyName;
                    History.EvaluateChange(HistoryChanges, "User Login", origProviderType, providerType);
                }

                // Change the caption if this is a sensitive user account
                if (HistoryChanges.Count > 0 && isUserNameSensitive)
                {
                    var change = HistoryChanges.FirstOrDefault();
                    change.SetCaption("User Account");
                }

                break;
            }

            case EntityState.Deleted:
            {
                // By this point EF has stripped out some of the data we need to save history
                // Reload the data using a new context.
                RockContext newRockContext = new RockContext();
                var         userLogin      = new UserLoginService(newRockContext).Get(this.Id);
                if (userLogin != null && userLogin.PersonId != null)
                {
                    try
                    {
                        var entityType          = EntityTypeCache.Get(userLogin.EntityTypeId ?? 0);
                        var isUserNameSensitive = (entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid()) ? true : false;

                        if (!isUserNameSensitive)
                        {
                            HistoryChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "User Login").SetOldValue(userLogin.UserName);
                            HistoryService.SaveChanges(newRockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), userLogin.PersonId.Value, HistoryChanges, UserName, typeof(UserLogin), this.Id, true, userLogin.ModifiedByPersonAliasId, null);
                        }
                        else
                        {
                            HistoryChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Authentication Provider").SetOldValue(entityType?.FriendlyName).SetCaption("User Account");
                            HistoryService.SaveChanges(newRockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), userLogin.PersonId.Value, HistoryChanges, entityType?.FriendlyName, typeof(UserLogin), this.Id, true, userLogin.ModifiedByPersonAliasId, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Just log the problem and move on...
                        ExceptionLogService.LogException(ex);
                    }
                }

                HistoryChanges.Clear();
                return;
            }
            }

            base.PreSaveChanges(dbContext, entry);
        }