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

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

                    DateTime createDate = RockDateTime.Now;

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

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

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

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

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

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

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

                    DateTime createDate = RockDateTime.Now;

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

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

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

                    userLoginService.Add( user );

                    var historyCategory = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext );
                    rockContext.WrapTransaction( () =>
                    {
                        rockContext.SaveChanges();

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

                    return user;
                }
                else
                {
                    throw new ArgumentException( "Invalid EntityTypeId, entity does not exist", "entityTypeId" );
                }
            }
            else
            {
                throw new ArgumentException( "Invalid Person, person does not exist", "person" );
            }
        }
Exemple #5
0
        /// <summary>
        /// Handles the SaveClick event of the dlgDetails 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 dlgDetails_SaveClick( object sender, EventArgs e )
        {
            if ( _canEdit )
            {
                var rockContext = new RockContext();
                UserLogin userLogin = null;
                var service = new UserLoginService( rockContext );

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

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

                if ( userLogin == null )
                {
                    userLogin = new UserLogin();

                    if ( _personId.HasValue )
                    {
                        userLogin.PersonId = _personId;
                    }
                    else
                    {
                        nbErrorMessage.Title = "Invalid Situation";
                        nbErrorMessage.Text = "The person you are editing has no person Id.";
                        nbErrorMessage.Visible = true;
                        return;
                    }

                    if ( service.GetByUserName( tbUserName.Text.Trim() ) != null )
                    {
                        nbErrorMessage.Title = "Invalid User Name";
                        nbErrorMessage.Text = "The User Name you selected already exists.  Please select a different User Name.";
                        nbErrorMessage.Visible = true;
                        return;
                    }

                    service.Add( userLogin );
                }

                userLogin.UserName = tbUserName.Text.Trim();
                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 = RockDateTime.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;
                }

                rockContext.SaveChanges();

                HideDialog();
                BindGrid();
            }
        }
Exemple #6
0
        /// <summary>
        /// Handles the SaveClick event of the dlgDetails 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 dlgDetails_SaveClick( object sender, EventArgs e )
        {
            if ( _canEdit )
            {
                var rockContext = new RockContext();
                UserLogin userLogin = null;
                var service = new UserLoginService( rockContext );
                string newUserName = tbUserName.Text.Trim();

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

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

                // Check to see if there is a change to the username, and if so check that the new username does not exist.
                if ( userLogin == null || ( userLogin.UserName != newUserName ) )
                {
                    if ( service.GetByUserName( newUserName ) != null )
                    {
                        // keep looking until we find the next available one
                        int numericSuffix = 1;
                        string nextAvailableUserName = newUserName + numericSuffix.ToString();
                        while ( service.GetByUserName( nextAvailableUserName ) != null )
                        {
                            numericSuffix++;
                            nextAvailableUserName = newUserName + numericSuffix.ToString();
                        }

                        nbErrorMessage.NotificationBoxType = NotificationBoxType.Warning;
                        nbErrorMessage.Title = "Invalid User Name";
                        nbErrorMessage.Text = "The User Name you selected already exists. Next available username: "******"Invalid Situation";
                        nbErrorMessage.Text = "No person selected, or the person you are editing has no person Id.";
                        nbErrorMessage.Visible = true;
                        return;
                    }

                    service.Add( userLogin );
                }

                userLogin.UserName = newUserName;
                userLogin.IsConfirmed = cbIsConfirmed.Checked;
                userLogin.IsLockedOut = cbIsLockedOut.Checked;
                userLogin.IsPasswordChangeRequired = cbIsRequirePasswordChange.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 = RockDateTime.Now;
                                }
                                else
                                {
                                    nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;
                                    nbErrorMessage.Title = "Invalid Password";
                                    nbErrorMessage.Text = UserLoginService.FriendlyPasswordRules();
                                    nbErrorMessage.Visible = true;
                                    return;
                                }
                            }
                            else
                            {
                                nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;
                                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;
                }

                rockContext.SaveChanges();

                HideDialog();
                BindGrid();
            }
        }