Beispiel #1
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;
        }
Beispiel #2
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;
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            var ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = HttpContext.Current.Request.UserHostAddress;
            }

            var username = tbUsername.Text;
            var personID = PortalLogin.Authenticate(username, tbPassword.Text, ipAddress, CurrentOrganization.OrganizationID);

            if (personID != -1)
            {
                var login = new Login(username);
                FormsAuthentication.SetAuthCookie(login.LoginID, false);
                HttpContext.Current.Response.Cookies["portalroles"].Value = string.Empty;

                try
                {
                    var person = new Person(personID);
                    var facebookUser = GetFacebookUser();
                    SavePersonAttribute(person, facebookUser["id"].ToString(), CurrentOrganization.OrganizationID);
                }
                catch (FacebookApiException ex)
                {
                    new ExceptionHistoryData().AddUpdate_Exception(ex, CurrentOrganization.OrganizationID,
                        "Cccev.Web", ArenaContext.Current.ServerUrl);
                }

                Redirect();
            }

            lblLoginError.Text = "Please enter a valid username and password.";
            lblLoginError.Visible = true;
        }
        private Person PopulatePerson(IDictionary<string, object> result, string createdBy)
        {
            DateTime facebookBirthdate;
            DateTime userSuppliedBirthdate;
            var lookupID = CurrentOrganization.Settings["CentralAZ.Web.FacebookRegistration.MembershipStatus"];

            if (!DateTime.TryParse(result["birthday"].ToString(), out facebookBirthdate))
            {
                facebookBirthdate = new DateTime(1900, 1, 1);
            }

            if (!DateTime.TryParse(tbBirthdate.Text, out userSuppliedBirthdate))
            {
                userSuppliedBirthdate = new DateTime(1900, 1, 1);
            }

            var person = new Person
                             {
                                 FirstName = result["first_name"].ToString(),
                                 LastName = result["last_name"].ToString(),
                                 RecordStatus = RecordStatus.Pending,
                                 MemberStatus = new Lookup(int.Parse(lookupID)),
                                 BirthDate = (facebookBirthdate != userSuppliedBirthdate && userSuppliedBirthdate != new DateTime(1900, 1, 1))
                                         ? userSuppliedBirthdate
                                         : facebookBirthdate
                             };

            // Create new person object, and register an Arena login for them.
            person.Save(CurrentOrganization.OrganizationID, createdBy, false);
            var email = new PersonEmail
                            {
                                Active = true,
                                AllowBulkMail = true,
                                Email = result["email"].ToString(),
                                PersonId = person.PersonID
                            };

            person.Emails.Add(email);
            return person;
        }
        private static void SavePersonAttribute(Person person, string facebookID, int orgID)
        {
            var attribute = new Arena.Core.Attribute(SystemGuids.FACEBOOK_USER_ID_ATTRIBUTE);
            var facebookSetting = new PersonAttribute
            {
                PersonID = person.PersonID,
                AttributeId = attribute.AttributeId,
                StringValue = facebookID
            };

            facebookSetting.Save(orgID, CREATED_BY);
        }