GetByUserName() публичный Метод

GetsRock.Model.UserLogin by User Name
public GetByUserName ( string userName ) : UserLogin
userName string A representing the UserName to search for.
Результат UserLogin
Пример #1
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" );
        }
Пример #2
0
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser(bool userIsOnline)
        {
            string userName = UserLogin.GetCurrentUserName();

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

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

                    return(user);
                }
            }

            return(null);
        }
Пример #3
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());
                }
            }
        }
Пример #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 (!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());
                }
            }
        }
Пример #5
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 message = new UpdateUserLastActivity.Message
                        {
                            UserId           = user.Id,
                            LastActivityDate = RockDateTime.Now,
                        };

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

                            message.Send();
                        }
                        else
                        {
                            message.IsOnline = false;
                            message.Send();

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

                    return(user);
                }
            }

            return(null);
        }
Пример #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());
                }
            }
        }
        /// <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" );
            }
        }
Пример #8
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);
        }
Пример #9
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 );
            }
        }
Пример #10
0
        /// <summary>
        /// Updates the last login.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public static void UpdateLastLogin(string userName)
        {
            if (!string.IsNullOrWhiteSpace(userName) && !userName.StartsWith("rckipid="))
            {
                using (var rockContext = new RockContext())
                {
                    var userLoginService = new UserLoginService(rockContext);

                    var userLogin = userLoginService.GetByUserName(userName);
                    if (userLogin != null)
                    {
                        userLogin.LastLoginDateTime = RockDateTime.Now;

                        if (userLogin.PersonId.HasValue)
                        {
                            var summary = new System.Text.StringBuilder();
                            summary.AppendFormat("User logged in with <span class='field-name'>{0}</span> username", userLogin.UserName);
                            if (HttpContext.Current != null && HttpContext.Current.Request != null)
                            {
                                summary.AppendFormat(", to <span class='field-value'>{0}</span>, from <span class='field-value'>{1}</span>",
                                                     HttpContext.Current.Request.Url.AbsoluteUri, HttpContext.Current.Request.UserHostAddress);
                            }
                            summary.Append(".");

                            var historyService     = new HistoryService(rockContext);
                            var personEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
                            var activityCategoryId = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext).Id;

                            historyService.Add(new History
                            {
                                EntityTypeId = personEntityTypeId,
                                CategoryId   = activityCategoryId,
                                EntityId     = userLogin.PersonId.Value,
                                Summary      = summary.ToString(),
                                Verb         = "LOGIN"
                            });
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
Пример #11
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" ); 
        }
Пример #12
0
        /// <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;
        }
Пример #13
0
        /// <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);
        }
Пример #14
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);
        }
Пример #15
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 );
            }
        }
    /// <summary>
    /// Get Method for pulling a user profile
    /// </summary>
    /// <returns></returns>
    public HttpResponseMessage Get()
    {
        //verify the token passed from the app is valid. Just an extra security measure tp make sure they're hitting from the app.
        var isAuthed = MobileAppAPIHelper.ValidateAppToken(Request);

        //if this check fails, return Unauthorized
        if (!isAuthed)
            return Request.CreateResponse(HttpStatusCode.Unauthorized);

        //get the authenticated user (cookie should have been passed in header, the [Authorize] makes sure it's valid.)
        //make sure we can pull what we need from it, and find it by the username
        var rockContext = new RockContext();
        var u = new UserLoginService(rockContext);
        var userProfileController = new MobileAppProfileController();

        var p = userProfileController.User;
        if (p == null)
            return Request.CreateResponse(HttpStatusCode.Unauthorized);

        var user = u.GetByUserName(p.Identity.Name);

        if (user == null)
            return Request.CreateResponse(HttpStatusCode.NotFound);

        //if we got here, we can build the return object.
        var m = new UserProfileGet();
        try
        {
            m.Id = user.Person.Id;

            m.FirstName = user.Person.FirstName;
            m.LastName = user.Person.LastName;
            m.MiddleName = user.Person.MiddleName;
            m.Email = user.Person.Email;
            m.EmailPreference = user.Person.EmailPreference.ConvertToInt();
            m.AnniversaryDate = user.Person.AnniversaryDate.HasValue ? user.Person.AnniversaryDate.Value.ToShortDateString() : "";
            m.BirthDay = user.Person.BirthDay.HasValue ? user.Person.BirthDay.Value.ToStringSafe() : "";
            m.BirthMonth = user.Person.BirthMonth.HasValue ? user.Person.BirthMonth.Value.ToStringSafe() : "";
            m.BirthYear = user.Person.BirthYear.HasValue ? user.Person.BirthYear.Value.ToStringSafe() : "";
            m.GraduationYear = user.Person.GraduationYear.HasValue ? user.Person.GraduationYear.Value.ToStringSafe() : "";
            m.Gender = user.Person.Gender.ConvertToInt();
            m.EncodedUrl = user.Person.UrlEncodedKey;

            //and return ok.
            return Request.CreateResponse(HttpStatusCode.OK, m);
        }
        catch (Exception ex)
        {
            //todo: log the error somewhere.
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }
Пример #17
0
        /// <summary>
        /// Handles the Click event of the lbLogin 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 lbLogin_Click( object sender, EventArgs e )
        {
            ManagerLoggedIn = false;
            var pinAuth = AuthenticationContainer.GetComponent( typeof( Rock.Security.Authentication.PINAuthentication ).FullName );
            var rockContext = new Rock.Data.RockContext();
            var userLoginService = new UserLoginService( rockContext );
            var userLogin = userLoginService.GetByUserName( tbPIN.Text );
            if ( userLogin != null && userLogin.EntityTypeId.HasValue )
            {
                // make sure this is a PIN auth user login
                var userLoginEntityType = EntityTypeCache.Read( userLogin.EntityTypeId.Value );
                if ( userLoginEntityType != null && userLoginEntityType.Id == pinAuth.EntityType.Id )
                {
                    if ( pinAuth != null && pinAuth.IsActive )
                    {
                        // should always return true, but just in case
                        if ( pinAuth.Authenticate( userLogin, null ) )
                        {
                            if ( !( userLogin.IsConfirmed ?? true ) )
                            {
                                maWarning.Show( "Sorry, account needs to be confirmed.", Rock.Web.UI.Controls.ModalAlertType.Warning );
                            }
                            else if ( ( userLogin.IsLockedOut ?? false ) )
                            {
                                maWarning.Show( "Sorry, account is locked-out.", Rock.Web.UI.Controls.ModalAlertType.Warning );
                            }
                            else
                            {
                                ManagerLoggedIn = true;
                                ShowManagementDetails();
                                return;
                            }
                        }
                    }
                }
            }

            maWarning.Show( "Sorry, we couldn't find an account matching that PIN.", Rock.Web.UI.Controls.ModalAlertType.Warning );
        }
Пример #18
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();
            }
        }
Пример #19
0
        /// <summary>
        /// Gets the name of the Twitter user.
        /// </summary>
        /// <param name="twitterUser">The Twitter user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetTwitterUser( dynamic twitterUser, string accessToken = "" )
        {
            string username = string.Empty;
            string twitterId = twitterUser.id_str;
            string twitterLink = "https://twitter.com/" + twitterUser.screen_name;

            string userName = "******" + twitterId;
            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 and email from twitterUser object and then split the name
                    string fullName = twitterUser.name;
                    string firstName = null;
                    string lastName = null;
                    var personService = new PersonService( rockContext );
                    personService.SplitName( fullName, out firstName, out lastName );
                    string email = string.Empty;
                    try { email = twitterUser.email; }
                    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 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 not an existing person, create a new one
                        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;
                            person.Gender = Gender.Unknown;
                            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, "Twitter", 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 )
                        {
                            string twitterImageUrl = twitterUser.profile_image_url;
                            bool twitterImageDefault = twitterUser.default_profile_image;
                            twitterImageUrl = twitterImageUrl.Replace( "_normal", "" );
                            // If person does not have a photo, use their Twitter photo if it exists
                            if ( !person.PhotoId.HasValue && !twitterImageDefault && !string.IsNullOrWhiteSpace( twitterImageUrl ) )
                            {
                                // Download the photo from the url provided
                                var restClient = new RestClient( twitterImageUrl );
                                var restRequest = new RestRequest( Method.GET );
                                var 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 Twitter social media link
                            var twitterAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_TWITTER.AsGuid() );
                            if ( twitterAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( twitterAttribute.Key, twitterLink );
                                person.SaveAttributeValues( rockContext );
                            }
                        }

                    }
                }

                return username;
            }
        }
Пример #20
0
        /// <summary>
        /// Gets the name of the Google user.
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetGoogleUser( GoogleUser googleUser, string accessToken = "" )
        {
            string username = string.Empty;
            string googleId = googleUser.id;
            string googleLink = googleUser.link;

            string userName = "******" + googleId;
            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 Google login
                    string lastName = googleUser.family_name.ToString();
                    string firstName = googleUser.given_name.ToString();
                    string email = string.Empty;
                    try { email = googleUser.email.ToString(); }
                    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 ( googleUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( googleUser.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(Google)).Id;
                            user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", 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);
                    }
                }

                return username;
            }
        }
Пример #21
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;
        }
Пример #22
0
        /// <summary>
        /// Updates the last login.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public static void UpdateLastLogin( string userName )
        {
            var rockContext = new RockContext();
            var userLoginService = new UserLoginService( rockContext );

            if ( !string.IsNullOrWhiteSpace( userName ) && !userName.StartsWith( "rckipid=" ) )
            {
                var userLogin = userLoginService.GetByUserName( userName );
                if ( userLogin != null )
                {
                    userLogin.LastLoginDateTime = RockDateTime.Now;
                    rockContext.SaveChanges();
                }
            }
        }
Пример #23
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);
            }
        }
Пример #24
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;
            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() );
                }
            }
        }
        /// <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");
            }
        }
Пример #26
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;
            }
        }
Пример #27
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();
            }
        }
Пример #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);
            }
        }
Пример #29
0
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser( bool userIsOnline )
        {
            string userName = UserLogin.GetCurrentUserName();
            if ( userName != string.Empty )
            {
                if ( userName.StartsWith( "rckipid=" ) )
                {
                    Rock.Model.PersonService personService = new Model.PersonService();
                    Rock.Model.Person impersonatedPerson = personService.GetByEncryptedKey( userName.Substring( 8 ) );
                    if ( impersonatedPerson != null )
                        return impersonatedPerson.ImpersonatedUser;
                }
                else
                {
                    var userLoginService = new UserLoginService();
                    UserLogin user = userLoginService.GetByUserName( userName );

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

                    return user;
                }
            }

            return null;
        }
Пример #30
0
        /// <summary>
        /// NOTE: This does much more then is sounds like! It returns the <see cref="Rock.Model.UserLogin"/> of the user who is currently logged in,
        /// but it also updates their last activity date, and will sign them out if they are not confirmed or are locked out.
        /// </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.IsNullOrWhiteSpace())
            {
                return(null);
            }

            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 message = new UpdateUserLastActivity.Message
                    {
                        UserId           = user.Id,
                        LastActivityDate = RockDateTime.Now,
                    };

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

                        message.SendIfNeeded();
                    }
                    else
                    {
                        // Even though we are in the userIsOnline == true condition,
                        // The user is either not confirmed or is locked out, so we'll mark them
                        // as offline and sign them out.

                        message.IsOnline = false;
                        message.SendIfNeeded();

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

                return(user);
            }

            return(null);
        }
Пример #31
0
        /// <summary>
        /// Adds any logins stored in the _peopleLoginsDictionary.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        private void AddPersonLogins( RockContext rockContext )
        {
            var password = tbPassword.Text.Trim();
            var userLoginService = new UserLoginService( rockContext );

            foreach ( var set in _peopleLoginsDictionary )
            {
                foreach ( var userName in set.Value )
                {
                    var userLogin = userLoginService.GetByUserName( userName );

                    // only create the login if the username is not already taken
                    if ( userLogin == null )
                    {
                        UserLoginService.Create(
                                            rockContext,
                                            set.Key,
                                            Rock.Model.AuthenticationServiceType.Internal,
                                            _authenticationDatabaseEntityTypeId,
                                            userName,
                                            password,
                                            isConfirmed: true );
                    }
                }
            }
        }
Пример #32
0
        /// <summary>
        /// Authenticates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="username">The username.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl )
        {
            var fbClient = new FacebookClient();
            FacebookOAuthResult oAuthResult;

            if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess )
            {
                try
                {
                    var redirectUri = new Uri( GetRedirectUrl( request ) );

                    dynamic parameters = new ExpandoObject();
                    parameters.client_id = GetAttributeValue( "AppID" );
                    parameters.client_secret = GetAttributeValue( "AppSecret" );
                    parameters.redirect_uri = redirectUri.AbsoluteUri;
                    parameters.code = oAuthResult.Code;

                    dynamic result = fbClient.Post( "oauth/access_token", parameters );

                    string accessToken = result.access_token;

                    fbClient = new FacebookClient( accessToken );
                    dynamic me = fbClient.Get( "me" );
                    string facebookId = "FACEBOOK_" + me.id.ToString();

                    UserLogin user = null;

                    var rockContext = new RockContext();
                    rockContext.WrapTransaction( () =>
                    {
                        // query for matching id in the user table
                        var userLoginService = new UserLoginService( rockContext );
                        user = userLoginService.GetByUserName( facebookId );

                        // if no user was found see if we can find a match in the person table
                        if ( user == null )
                        {
                            try
                            {

                                var familyChanges = new List<string>();
                                var familyMemberChanges = new List<string>();
                                var PersonChanges = new List<string>();

                                // determine if we can find a match and if so add an user login record

                                // get properties from Facebook dynamic object
                                string lastName = me.last_name.ToString();
                                string firstName = me.first_name.ToString();
                                string email = me.email.ToString();

                                var personService = new PersonService( rockContext );
                                var person = personService.Queryable( "Aliases" ).FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email );

                                if ( person != null )
                                {
                                    // since we have the data enter the birthday from Facebook to the db if we don't have it yet
                                    DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() );

                                    if ( person.BirthDay == null )
                                    {
                                        History.EvaluateChange( PersonChanges, "Birth Date", person.BirthDate, person.BirthDate );
                                        person.BirthDate = birthdate;

                                        rockContext.SaveChanges();
                                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id, PersonChanges );
                                    }
                                }
                                else
                                {
                                    person = new Person();
                                    person.IsSystem = false;
                                    person.RecordTypeValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                                    person.RecordStatusValueId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;
                                    person.FirstName = me.first_name.ToString();
                                    person.LastName = me.last_name.ToString();
                                    person.Email = me.email.ToString();
                                    if ( me.gender.ToString() == "male" )
                                        person.Gender = Gender.Male;
                                    else if ( me.gender.ToString() == "female" )
                                        person.Gender = Gender.Female;
                                    else
                                        person.Gender = Gender.Unknown;
                                    person.BirthDate = Convert.ToDateTime( me.birthday.ToString() );
                                    person.EmailPreference = EmailPreference.EmailAllowed;

                                    GroupService.SaveNewFamily( rockContext, person, null, false );
                                }

                                user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true );

                            }
                            catch ( Exception ex )
                            {
                                string msg = ex.Message;
                                // TODO: probably should report something...
                            }
                        }
                        else
                        {
                            // TODO: Show label indicating inability to find user corresponding to facebook id
                        }
                    } );

                    if ( user != null )
                    {
                        username = user.UserName;
                        returnUrl = oAuthResult.State;
                        return true;
                    }
                    else
                    {
                        username = string.Empty;
                        returnUrl = string.Empty;
                        return false;
                    }

                }
                catch ( FacebookOAuthException oae )
                {
                    string msg = oae.Message;
                    // TODO: Add error handeling
                    // Error validating verification code. (usually from wrong return url very picky with formatting)
                    // Error validating client secret.
                    // Error validating application.
                }
            }

            username = null;
            returnUrl = null;
            return false;
        }
Пример #33
0
        /// <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 )
        {
            bool valid = false;

            if ( Page.IsValid )
            {
                var userLoginService = new UserLoginService();
                var userLogin = userLoginService.GetByUserName( tbUserName.Text );
                if ( userLogin != null && userLogin.EntityType != null)
                {
                    var component = AuthenticationContainer.GetComponent(userLogin.EntityType.Name);
                    if (component.IsActive && 
                        component.ServiceType == AuthenticationServiceType.Internal &&
                        !component.RequiresRemoteAuthentication)
                    {
                        if ( component.Authenticate( userLogin, tbPassword.Text ) )
                        {
                            valid = true;
                            string returnUrl = Request.QueryString["returnurl"];
                            LoginUser( tbUserName.Text, returnUrl, cbRememberMe.Checked );
                        }
                    }
                }
            }

            if ( !valid )
            {
                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 accout information</a>?", helpUrl) );
            }
        }
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser( bool userIsOnline )
        {
            var rockContext = new RockContext();

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

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

                        if ( ( user.IsConfirmed ?? true ) && !( user.IsLockedOut ?? false ) )
                        {
                            if ( HttpContext.Current != null && HttpContext.Current.Session != null )
                            {
                                if ( HttpContext.Current.Session["RockUserId"] != null )
                                {
                                    transaction.SessionUserId = (int)HttpContext.Current.Session["RockUserId"];
                                }
                                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 && a.SessionUserId == transaction.SessionUserId ).FirstOrDefault();

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

                            FormsAuthentication.SignOut();
                            return null;
                        }
                    }

                    return user;
                }
            }

            return null;
        }
Пример #35
0
        /// <summary>
        /// Authenticates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="username">The username.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns></returns>
        public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl )
        {
            var fbClient = new FacebookClient();
            FacebookOAuthResult oAuthResult;

            if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess )
            {
                try
                {
                    var redirectUri = new Uri( GetRedirectUrl( request ) );

                    dynamic parameters = new ExpandoObject();
                    parameters.client_id = GetAttributeValue( "AppID" );
                    parameters.client_secret = GetAttributeValue( "AppSecret" );
                    parameters.redirect_uri = redirectUri.AbsoluteUri; 
                    parameters.code = oAuthResult.Code;

                    dynamic result = fbClient.Post( "oauth/access_token", parameters );

                    string accessToken = result.access_token;

                    fbClient = new FacebookClient( accessToken );
                    dynamic me = fbClient.Get( "me" );
                    string facebookId = "FACEBOOK_" + me.id.ToString();

                    // query for matching id in the user table 
                    var userLoginService = new UserLoginService();
                    var user = userLoginService.GetByUserName( facebookId );

                    // if not user was found see if we can find a match in the person table
                    if ( user == null )
                    {
                        try
                        {
                            // determine if we can find a match and if so add an user login record

                            // get properties from Facebook dynamic object
                            string lastName = me.last_name.ToString();
                            string firstName = me.first_name.ToString();
                            string email = me.email.ToString();

                            var personService = new PersonService();
                            var person = personService.Queryable().FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email );

                            if ( person != null )
                            {
                                // since we have the data enter the birthday from Facebook to the db if we don't have it yet
                                DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() );

                                if ( person.BirthDay == null )
                                {
                                    person.BirthDate = birthdate;
                                    personService.Save( person, person.Id );
                                }

                            }
                            else
                            {

                                var dvService = new DefinedValueService();

                                person = new Person();
                                person.IsSystem = false;
                                person.RecordTypeValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) );
                                person.RecordStatusValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) );

                                person.FirstName = me.first_name.ToString();
                                person.LastName = me.last_name.ToString();
                                person.Email = me.email.ToString();

                                if ( me.gender.ToString() == "male" )
                                    person.Gender = Gender.Male;
                                else if ( me.gender.ToString() == "female" )
                                    person.Gender = Gender.Female;
                                else
                                    person.Gender = Gender.Unknown;

                                person.BirthDate = Convert.ToDateTime( me.birthday.ToString() );
                                person.DoNotEmail = false;

                                personService.Add( person, null );
                                personService.Save( person, null );
                            }

                            user = userLoginService.Create( person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true, person.Id );
                        }
                        catch ( Exception ex )
                        {
                            string msg = ex.Message;
                            // TODO: probably should report something...
                        }

                        // TODO: Show label indicating inability to find user corresponding to facebook id
                    }

                    username = user.UserName;
                    returnUrl = oAuthResult.State;
                    return true;

                }
                catch ( FacebookOAuthException oae )
                {
                    string msg = oae.Message;
                    // TODO: Add error handeling
                    // Error validating verification code. (usually from wrong return url very picky with formatting)
                    // Error validating client secret.
                    // Error validating application.
                }
            }

            username = null;
            returnUrl = null;
            return false;
        }
        /// <summary>
        /// Returns the <see cref="Rock.Model.UserLogin"/>
        /// </summary>
        /// <param name="userIsOnline">A <see cref="System.Boolean"/> value that returns the logged in user if <c>true</c>; otherwise can return the impersonated user</param>
        /// <returns>The current <see cref="Rock.Model.UserLogin"/></returns>
        public static UserLogin GetCurrentUser(bool userIsOnline)
        {
            var rockContext = new RockContext();

            string userName = UserLogin.GetCurrentUserName();

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

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

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

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

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

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

                    return(user);
                }
            }

            return(null);
        }
        /// <summary>
        /// Updates the last login.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        public static void UpdateLastLogin( string userName )
        {
            using ( var rockContext = new RockContext() )
            {
                var userLoginService = new UserLoginService( rockContext );
                var historyService = new HistoryService( rockContext );

                var personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
                var activityCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_ACTIVITY.AsGuid(), rockContext ).Id;

                if ( !string.IsNullOrWhiteSpace( userName ) && !userName.StartsWith( "rckipid=" ) )
                {
                    var userLogin = userLoginService.GetByUserName( userName );
                    if ( userLogin != null )
                    {
                        userLogin.LastLoginDateTime = RockDateTime.Now;

                        if ( userLogin.PersonId.HasValue )
                        {
                            var summary = new System.Text.StringBuilder();
                            summary.AppendFormat( "User logged in with <span class='field-name'>{0}</span> username", userLogin.UserName );
                            if ( HttpContext.Current != null && HttpContext.Current.Request != null )
                            {
                                summary.AppendFormat( ", to <span class='field-value'>{0}</span>, from <span class='field-value'>{1}</span>",
                                    HttpContext.Current.Request.Url.AbsoluteUri, HttpContext.Current.Request.UserHostAddress );
                            }
                            summary.Append( "." );

                            historyService.Add( new History
                            {
                                EntityTypeId = personEntityTypeId,
                                CategoryId = activityCategoryId,
                                EntityId = userLogin.PersonId.Value,
                                Summary = summary.ToString()
                            } );
                        }
                        rockContext.SaveChanges();
                    }
                }
            }
        }
Пример #38
0
        /// <summary>
        /// Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var reflectedHttpActionDescriptor = ( ReflectedHttpActionDescriptor )actionContext.ActionDescriptor;

            var    controller          = actionContext.ActionDescriptor.ControllerDescriptor;
            string controllerClassName = controller.ControllerType.FullName;
            string actionMethod        = actionContext.Request.Method.Method;

            var      apiId = RestControllerService.GetApiId(reflectedHttpActionDescriptor.MethodInfo, actionMethod, controller.ControllerName);
            ISecured item  = RestActionCache.Get(apiId);

            if (item == null)
            {
                // if there isn't a RestAction in the database, use the Controller as the secured item
                item = RestControllerCache.Get(controllerClassName);
                if (item == null)
                {
                    item = new RestController();
                }
            }

            Person person = null;

            if (actionContext.Request.Properties.Keys.Contains("Person"))
            {
                person = actionContext.Request.Properties["Person"] as Person;
            }
            else
            {
                var principal = actionContext.Request.GetUserPrincipal();
                if (principal != null && principal.Identity != null)
                {
                    using (var rockContext = new RockContext())
                    {
                        string    userName  = principal.Identity.Name;
                        UserLogin userLogin = null;
                        if (userName.StartsWith("rckipid="))
                        {
                            Rock.Model.PersonService personService      = new Model.PersonService(rockContext);
                            Rock.Model.Person        impersonatedPerson = personService.GetByImpersonationToken(userName.Substring(8));
                            if (impersonatedPerson != null)
                            {
                                userLogin = impersonatedPerson.GetImpersonatedUser();
                            }
                        }
                        else
                        {
                            var userLoginService = new Rock.Model.UserLoginService(rockContext);
                            userLogin = userLoginService.GetByUserName(userName);
                        }

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

                            /* 12/12/2019 BJW
                             *
                             * Setting this current person item was only done in put, post, and patch in the ApiController
                             * class. Set it here so that it is always set for all methods, including delete. This enhances
                             * history logging done in the pre and post save model hooks (when the pre-save event is called
                             * we can access DbContext.GetCurrentPersonAlias and log who deleted the record).
                             *
                             * Task: https://app.asana.com/0/1120115219297347/1153140643799337/f
                             */
                            System.Web.HttpContext.Current.AddOrReplaceItem("CurrentPerson", person);
                        }
                    }
                }
            }

            string action = actionMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) ?
                            Rock.Security.Authorization.VIEW : Rock.Security.Authorization.EDIT;

            if (!item.IsAuthorized(action, person))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
        /// <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" );
            }
        }
        /// <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) );
        }
Пример #41
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 = 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 );
            }
        }