You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

Posts filed under 'Ruby on Rails'

OmniAuth for Facebook Apps

Been suffering a great deal of pain regarding authentication this fall due to the recent OAuth 2.0 and HTTPS migration at Facebook. As of October 1st, it has become a requirement to use OAuth2 authentication. And throughout the month of October, our recent migration from Authlogic to Devise has been funky.

On November 2nd, OmniAuth announced a major 1.0 release which should provide better support for Facebook authentication moving forward. And as of November 10th, Devise officially supports the new OmniAuth release. Unfortunately, the facebook strategy for OmniAuth 1.0 is still in the release candidate phase. The docs say that it will be officially release when OmniAuth 1.0 is released, but that was a week ago.

The upgrade went fairly easily but I still have to jump through hoops to get my facebook application to play nice. For example, if your users are playing at the library and require that one user logs out and another logs in you run into some trouble. The old session simply doesn’t clear out unless you take matters in to your own hands a log out the old session.

You can’t just clear_sesson! before you authenticate the new user, and sign_out @user doesn’t do the job either. I had to jump into the js and grab the session change event (auth.authResponseChange):


FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status == "connected") {
$.ajax({
url: "/members/sign_out"
});
}
});

In addition, I have to check whether this is a new install. A new install of the game means you’re going to get a permissions pop up that pops you out of the facebook iframe. So I’m making the assumption that if you are asking for a new permission, it isn’t likely that I need to sign you out of an old session which leads to pop out hell. But that assumption doesn’t hold up at the library.

Now, there’s a little param that I just happened upon that you can call in the devise initializer called :iframe => true:


onfig.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo', :client_options => {:ssl => {:ca_path => '/etc/ssl/certs'}, :iframe => true}

But I haven’t had much success using it. And two days ago I ran across this quote:

“I originally wrote in the functionality for “iframe => true” to break out of the iframe but I haven’t used it in quite a while and, considering v1.0, I don’t really know what it has evolved to.”

So, it’s still a work in progress. Things still mysteriously stop and start working which just convinces me that the FaceBook folks are still tweaking the API. I’m hoping that things will settle down now that we’re over a month out from this major FB change. Fingers crossed.

November 14th, 2011

Devise Edge Case

Long time no blog. Since RailsConf, I’ve been A) Working my tail off at my new job B) finding a new place to live C) reminding my children that they do have a mommy

A) Has been fun and incredibly challenging. But while working at home is amazing, it means I work a lot B) took a lot more time and effort than I ever could have imagined so that there hasn’t been much time for C). So all other endeavors have been on hold.

But now it’s fall and with the change of seasons comes a renewed passion for picking up old projects. I have better sense now than to attempt to watch and blog every single Railscasts episode (unless someone locks me in a closet for a week….which would be awesome). So instead I’m just gonna share a tidbit from work. Hopefully it’ll help someone out.

I recently ripped out Authlogic and implemented Devise at work. I used the Rails 3.0 app using Devise + Omniauth example on github as a guide. And thanks to StackOverflow, I came out relatively unscathed. But I did find one edge case that might interest someone.

We were getting this error:

NoMethodError (undefined method `serialize_into_session' for Symbol:Class):

And after a little debugging came to realize that we had user_tokens with no matching user. (There’s database integrity for ya). Fortunately, it’s a quick fix in app/controllers/members/omniauth_callbacks_controller.rb. You just need to add authentication.user.present?.

authentication = UserToken.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication && authentication.user.present?
  flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => omniauth['provider']
  sign_in_and_redirect(:user, authentication.user)
  #sign_in_and_redirect(authentication.user, :event => :authentication)
else
  ...
end

2 comments September 29th, 2011

Why being one of 2.7% is awesome

So at the start of railsconf this year, I saw a bit of whining over the twitterz and heard many complaints about the number of women at the conference.

What a shame that there was only one woman speaking. Isn’t it a pity? Why couldn’t the sponsors do more? Blah, blah, blah.

Well personally, I’m glad. …I mean… I’m not exactly *glad*…. I do my part organizing Railsbridge events (time for another one in Boston, eh?) and putting together a bi-monthly study group and encouraging any woman who shows interest to pursue one of the best careers in the world.

But I’m happy to have been in the super minority at my very first railsconf this year. Know why? Because….

I STICK OUT

Ladies! You have a unique opportunity to stick out in a sea of men who are themselves fighting to differentiate themselves from each other.

And you get to see (and I’m stealing this from @sandimetz) the “Secret Life of Boys”. What they do when they are amongst themselves and let their hair down. Their truly geeky, silly, wonderful selves who are at their core more insecure than we are.

Yes, there should be more women at the conference. Yes, it would be a better world if tech were less male and more balanced. But instead of lamenting about the women who are not there, rejoice in the fact that YOU are there. And you STICK OUT.

I LOVE sticking out! I do it on purpose! I wear lipstick every day and I’m not afraid to introduce myself and start a conversation with anyone around me and I believe in myself and my technical abilities and I’m happy to talk honestly with you about it.

Sticking out makes me AWESOME. It’s only one of the reasons I am awesome but I am not ashamed to proclaim my awesomeness. I have worked hard for many years to become awesome.

This week, @coreyhaines said “You have to practice to be awesome”. So true. It takes practice.

Notice he didn’t say it takes mad development skillz to be awesome. Mad development skillz do not make you awesome.

No, really.

What I mean to say is, everybody is practicing to be awesome. And yes, it’s important to build your skillset to be taken seriously in this crowd. But don’t let your perceived lack of mad development skillz deter you from participating. It’s only through participating with others that you build on your skillset and become an awesome developer.

Sure, it helps to have contributed important work to open source at an event like this. But that’s not necessarily what distinguishes you in a crowd of people who are all mostly uber technical and trying to prove to anyone who will listen to them blather on and on about the importance of testing, how awesome they are.

Sticking out gets you noticed. It is awesome to be noticed because you end up making connections that you wouldn’t have otherwise. And ladies, even if you are not trying to… you stick out. Embrace that! Take advantage of that!

Guess what? The ruby on rails community is full of guys trying to be awesome. These guys want to see you succeed. Because that’s awesome!

Don’t be afraid to talk to them. They are more afraid of talking to you! And they want so desperately to talk to you. And to help you. And to support you. They really do. But they need you to make the first move.

It is NOT awesome to melt into the background.

It is NOT awesome to hang out only with your coworkers.

It IS awesome when you introduce yourself to the someone sitting next to you.

It IS awesome to venture over to bohconf and ask someone you don’t know a question.

(And that advice goes to some of you guys as well.)

Liana as an actor in NYC
At the same time, I need to give you some important advice that I learned in my youth as a professional actor in New York City.

TO BE AWESOME,
YOU NEED TO BE YOURSELF.

But you need to be the super you. Not the shy you but the happy you. The you that you are when you are relaxed with your closest friends. And guess what? That you is enough.

I spent years and years in New York trying to be what agents and casting directors and Broadway legends want me to be. That was FUCKED UP. Because to be a success in life, all I needed to be was myself.

If you decide to chuck coding and become a professional actor. This is the lesson you will hear time and time again:

You are ENOUGH

Please let that sink in a little as I shout that at you again.

YOU ARE ENOUGH

Just as you are right now, you are awesome. You are awesome if but for the mere fact that you are one of a mere 2.7% who came to railsconf and you stick out. THAT IS AWESOME!

4 comments May 20th, 2011

The Railscasts Project is #fail

Sadly, I did not complete all of Ryan Bates’ Railscast videos before Railsconf ’11. I didn’t even get close.

It was a great idea that I simply couldn’t complete. But that doesn’t mean it has to die.

Through the conference this year there was a definite theme. And I’m not talking about javascript. @benscofield gave an ignite talk where he said, the way to be awesome is to:

START LOTS OF STUFF

Now, I am awesome. And I am awesome at starting lots of great stuff. And sometimes I finish it too. Particularly, if there is the possibility that I may be fired if I don’t. But @benscofield also said:

QUIT ON STUFF

You have to Know Your Limits as @eliseworthy said. And since @briandoll pointed out that the ultimate productivity hack is having kids, I’ve decided to take this project in a new direction.

It’s no fun practicing being awesome alone. So I propose a monthly meet-up where we watch a Railscast screencast together and discuss it afterwards.

Who’s in?

1 comment May 20th, 2011

Post Railsconf Wrap Up

My first railsconf was a wild blur of code, sushi, new friends and t-shirts. You can check out my conference tweets here. But with the keynotes being livestreamed and the sessions being mostly hit or miss, the clear stand out for me was @bohconf.

If you can’t afford a ticket next year (and lord knows that it’ll take that long for me to pay off this year’s trip), then save your dough and just sign up for @bohconf. Really, you won’t regret it.

@bohconf was created by local Baltimore ruby group folk who created a space where devs could meet up and hack together with geek snacks and t-shirts readily available. This is where I hung out with @sandimetz, @BlueBoxRenee, and @narwen chit chatting about Sandi’s work on her new book and learning more about best practices than I would if I had attended some of the sessions I was missing.

It was a safe space where devs of all levels were sitting at tables learning new stuff and coding together in peace and harmony. And all the rockstars made an appearance at one point or another.

I complimented one on his oh-so-FAB yoda packpack before I realized it was @coreyhaines just practicing being awesome. …And while I was banging away at some mysterious problem installing mysql with homebrew, @wayneeseguin sat down beside me and hijacked my computer installing redis and mysql using his new project called BDSM. Beat that system into submission, baby!

I know there are some who will consider the lewd reference unfortunate. Get over yourself. You can’t get much sillier than a penguin in a corset and @wayneeseguin and I traded ridiculous innuendos while giggling like we were in jr. highschool.

And this is how I ended up going to dinner with the inventor of RVM, the organizer of MoutainWest RubyConf and a senior member of my favorite consulting company of which I am a major fangirl. Srsly, @bohconf rocks.

But since I had sacrificed a trip to the Bahamas with my girlfriends to afford my conference ticket, I felt an obligation to attend all the sessions on Testing, Scaling, Redis and Javascript to get my money’s worth. I came to railsconf specifically to level up my skills, so I decided to pass on the more visionary talks by the usual suspects.

I appreciate that you have strong opinions on the direction of our framework. And there are lots of folks who want to hear those opinions. But honestly, I just want to look at code. And I want you to explain that code to me with context and examples. So that when I’m alone with my laptop, I’m not googling for blog posts but rather I have enough exposure to a new concept that I can work it through myself.

So my favorite tutorial was the Rails Best Practices presentation. I realize that they were selling a new product that had been well polished before arriving at the conference, but this tutorial from Envy Labs was the best technical presentation I have ever attended. @greggpollack is a great speaker and I fully appreciated his vintage Atari game references. Check out railsbest.com to level up your Ruby on Rails best practices. Sure, you have to pay to play, but I promise it’s worth it.

And tied for favorite session are two talks that I saw on the last day back to back. Both were code heavy in a new technology for me but gave me a strong base to go off on my own and learn more.

Indexing Thousands of Writes Per Second with Redis from @pauldix will help bring me up to speed on something that I’m going to use this morning. I can’t tell you how much I appreciated that he took five minutes to go over the basics of Redis and what it does before talking about the advanced topics. Thank you, Paul. …And by the way, you look hot in a suit.

Building Pageless Apps with Rails and Backbone.js from@mkelly12 was hilarious and chock full of code. For example:

Javascript === Ke$ha

Javascript is a lot like Ke$ha. At first, you’re like WTF? But then you realize that:

function () {} === lambda {}

And Ke$ha is just a vessel for vomiting glitter and baby unicorns.

Honestly, this talk flew by me so fast that I felt like I was run over by those baby unicorns…. but if they could just circle back a couple of times then I think that I too could vomit glitter. I *really* hope that this talk ends up on the net somewhere.

But I wouldn’t be true to my #glee roots if I didn’t mention @aslpeenic (a gentleman and a funny bastard) and the music jam on Wednesday night where everyone participated at varying levels of musical talent. Honestly, I really wish I had contributed to the github setlist with a few Journey or Pat Benatar tunes. I did get a chance to wail on Proud Mary in the wrong key, but next year I’ll have more tunes in my backpocket.

So, I’m actually quite grateful to my delayed flight that has allowed me to finish up this blog post before returning back to real life. Srsly, I felt like I was 20 again in New York City with so many exciting things to experience and discover that you just can’t take it all in. Which is fun… but exhausting.

1 comment May 20th, 2011

Freaking IE

I’m working with very old versions of prototype and scriptaculous, and for the most part it’s not a problem. Our needs are simple. An autocomplete here, a drag and drop there. No biggie.

But I need to incorporate a drag and drop feature on an existing table. No problem! We got sortable ordered lists all over the app. Only, sorting an ordered list is a different thing than sorting table rows. Or is it?

Well, having fought with it for some time I was ready to give up when Google search revealed that there’s some sort of bug with scriptacuous sortable_element function and tables.

Well, poo!

I didn’t want to trhow in third party plugins like Tablekit and was instead just about to implement a link at the bottom of the table to a lightbox that would display the data in an ordered list. *sigh* Not a bad workaround, but it made me sad.

I was so sad, I decided to learn a little more about this sortable_element function. http://api.rubyonrails.org/classes/ActionView/Helpers/ScriptaculousHelper.html#method-i-sortable_element Unsurprisingly, the helper documentation doesn’t offer up much. I mean, now that I know that answer I understand the documentation. But it’s supposed to work the other way around, isn’t it?

So, my last effort was to see if I could find if this bug had been reported. I’ve had great luck finding workarounds and forming alternative ideas from conversations via lighthouse tickets and so my search brought me here:

The interesting bit about this ticket is that subimage provides a workaround that sounds a bit like intended behavior to me. Better yet, he provides examples that got me up and running.

So, below is a simplified version of my now working sortable table:

apps/views/files/tableofiles.rhtml


              <table>
                <thead>
                  <tr><th>Handle</th><th>Name</th><th>Date</th></tr>
                </thead>
                <tbody>
                   "row", :collection =&gt; @files) %&gt;
                </tbody>
              </table>
             { :action =&gt; "sort_my_table"},
                                 :tag =&gt; "TR",
                                 :handle =&gt; "TD.drag",
                                 :dropOnEmpty =&gt; true,
                                 :containment =&gt; ['sortable_body'],
                                 :ghosting =&gt; true,
                                 :constraint =&gt; :vertical) %&gt;

apps/views/files/_row.rhtml


                  &lt;tr id=&#039;file_'&gt;
                    <td class='drag'>[drag]</td>
                    <td></td>
                    <td></td>
                  </tr>


apps/controllers/files_controller.rb


  def sort_my_table
    priorities = params[:sortable_body].collect { |f| File.find(f)  }.reverse
    priorities.each_with_index{|f, index| f.update_attribute('priority', index + 1) unless f.priority == index+1}
    render :nothing =&gt; true
  end

So, it’s implemented, it works, it looks pretty… but wait. Was what that about a bug? … I go back to research for this blog post. In the documentation for Sortable.create:

Notes
Important: You can use Sortable.create on any container element that contains Block Elements, with the exception of TABLE, THEAD, TBODY and TR. This is a technical restriction with current browsers.

A sortable nested somewhere inside a table won’t work well under IE unless the table has a “position:relative” style. If you use the css display: table property, sortable lists will work a little, but doesn’t allow true drag and drop of the elements.

So, does my new feature work in IE? According to these docs, using tbody as container and TR as the sortables will work in IE6 (pc) and Firefox (mac/pc). But my clients are using IE7. Since it appears that the bug was reported in December 2009 and there has been no action on it, I’m going to guess no one cares. Freaking legacy code.

Back to my lightbox hack… Freaking IE. *sigh*

April 15th, 2011

New Ruby on Rails Study Group for Women

Come join us in our quest to hone our Ruby on Rails skills! Using Michael Hartl’s Ruby on Rails 3 Tutorial as our textbook, we will work chapter by chapter building our skills together.

Meetings will be held every-other-week on Wednesday evenings starting at 6:30 pm. and will last approximately 2 hrs. RBM Technologies has graciously donated meeting space. Attendees will chip in to buy a communal dinner. Non-alcoholic drinks will be provided, but feel free to bring your own beverage of choice.

The next meeting will be held at RBM Technologies on March 16th, 6:30 pm, 215 First Street, Cambridge, MA 02142 on the first floor across from the entrance to Technique. The information desk can assist if you have problems finding the office.

RBM Technogliges is a short walk from either the Lechmere or Kendall T-stations. On street parking is tight but sometimes you will get lucky. The Cambridgeside Galleria parking lot is closeby and very affordable after 5pm.

Attendees should have read/studied and completed Chapter 1 & 2 before the next meeting.  We will start with Chapter 3. Bring your laptop, a hard copy of the book if you own one, and your enthusiasm.

The Ruby on Rails Study Group for Women is being coordinated by Liana Leahy, liana@liana.org, and Susan McM. Tucker, smtucker@prettycoolsolutions.com

Feel free to forward this announcement to anyone who might be interested.

March 7th, 2011

An odd moment

I find myself with an odd moment to blog about episode #28. And I do in fact find this topic odd.

There isn’t much to say about it. I mean, in_groups_of *is* a handy little method that will transform your array into groups, as you might think. And this is useful for displaying tables as demonstrated by Ryan in the screencast.

But really? *yawn*

I think I’m done with starting from the beginning of the railscasts. My company is transitioning to Rails 3 and Ryan has been blogging about it since February.

Since I really need to catch up, I think it’s time to skip. I can always come back to the older posts later, right?

After all, I’m sure Julie didn’t do all of Julia’s recipes in order. Didn’t she save the canard à l’orange recipe till last?

So folks, where do you think I should skip TO? Does Episode 200: Rails 3 Beta and RVM seem like the most likely place to start?

December 1st, 2010

Holy Crap!

It’s Thanksgiving. I swear that September through January is always a god damn blur. Every now and again I’ll lift my head up, shout out some expletive and then get back to the business of getting through the holiday season.

At this rate, I’ve averaging one railscast per month. Considering that Ryan churns out at least one a week, my project doesn’t appear to be progressing as I’d hoped.

But hey, I have photos to make up for it.

Happy Halloween

1 comment November 24th, 2010

Our Little Secret

So wading through every single Railscast episode isn’t going as well as I had planned. Life keeps getting in the way. October is a very busy month. Halloween is very important to me and my family. And yes I do spend all month getting ready. Truthfully, I’ve been getting ready since August.

You do know that my brother is a horror filmmaker out in LA, right? Yup. Halloween is a busy time of year. And the theatrically of it all is just too hard for me to pass up.

In addition, it’s hard to stay focused on getting through these early episodes when more exciting things keep jumping out at me…. like the JQuery Conference this weekend. A whole lot of awesome.

But whether it takes a year or longer, I’ve made a commitment and I plan to stick to it. So, I’m combining three episodes once again into one blog post. They’re all related anyway. And I have a feeling that Ryan likely wrote this as one episode initially and then broke it out into three because he was busy as well. Shhh. It’s just our little secret, Ryan.

So, this threesome is more about security. Bottom line:

params  <-- don't trust it
cookies <-- don't trust it
session  <-- you can trust it

SQL INJECTION: Episode 25

When the dev places the user input directly into an SQL query, there is potential to really mess up the db.

This is BAD:

@tasks = Task.find(:all,:conditions=>"name LIKE ’%#{params[:query]}%’")

Input a quote and everything after that is considered pure SQL.

if params[:query] = " ' " + "DROP DATABASE"
YOU ARE F*CKED
end

There are easy ways to escape conditions.

tasks = Task.find(:all, :conditions=> [ "name LIKE ?", "%#{params[:query]}%" ]

This still looks dangerous to me but Rails will actually escape this for you. You only need to worry about escaping input in find methods if you’re using the :conditions parameter. If you’re using the dynamic find_by methods then Rails will automatically escape any input which will ensure that you’re safe from SQL injection.

So Ryan, you’re saying that the code below is safe?

tasks = Task.find_by_name(params[:query])

Really? Let’s try it out.

query = " ' " + "DROP DATABASE"
tasks = Task.find_by_name(query)

Whew! I still got my db. ;-)

MASS ASSIGNMENT: Episode 26

@user = User.new(params[:user])

Everything in the params[:user] hash is being sent to create the user record. Don’t ever trust the params hash. It could be anything.

One way to prevent problems is to set protection on your user model. attr_protected will disable mass assignment for the fields you want to protect.

So in Ryan’s example, he had a User model with a boolean field denoting whether or not a user is an admin. By setting attr_protected :admin in your user model, you’re preventing the admin field from being set.

Here’s another example:
stuff = {:login => "Hacker", :password => "hacked"}
@user = User.new(stuff)

When attr_protected :password is set, the code above will not update the password field. But this will:

@user.password = 'goodsecurity'

So, that’s good. But actually, its better practice to use attr_accessible to open the fields that you want to be set via mass assignment and automatically hide all the rest. This protects fields that can be set indirectly via associations.

CROSS SITE SCRIPTING: Episode 27

Allowing the user to input nastiness to the site directly is bad news. Adding data to a table directly from a view is fraught with issues. Ryan shows an awesome example of this. Try going to your favorite insecure website and type in any input text box:

I can haz hack? alert('i haz hakked u')

If you see an alert box, then this site is vulnerable to Cross Site Scripting. To avoid this problem, you need to escape user input. In older version of rails, you needed to use h method.

Really annoying to have to remember to add h to all your views. Another way to do this is to sanitize the input in the controller. Perhaps best to do it in both places. Or better yet, upgrade to Rails 3.

Rails 3 adds XSS protection by default. This means that you no longer have to manually escape user input with the h helper, because Rails will automatically escape it for you.

IT’S ABOUT TIME!!

But if you really wanna protect yourself, use html_safe. You can read up all about it and more on Yehuda’s blog: SafeBuffers and Rails 3.0.

Hey, let’s be careful out there.

October 20th, 2010

Next Posts Previous Posts


Pages

Tweets

Meta

Recent Posts