Implementing OAuth (or how I seemed to remember it, “Olaf”)

You may be thinking of a friendly little snowman who loves summer. But I must disappoint and inform you that this post is about implementing OAuth within a rails application. I, myself, am new in the world of software development, so this post will be from the perspective of a student. I won’t be including a code snippets or commands verbatim.

Once your basic rails application has been generated on your machine and you have implemented functionality for a user, you must make some design decisions. I might ask myself, “do I want my users to login on the dashboard of my app or would I like a third party to handle this responsibility?” I recently implemented the second option using Twitter and will tell you how. First, you will need to register your app with Twitter. This action will yield important data that will need later. Secondly, install the gem “omniauth-twitter” within your Gemfile and run “bundle.” After bundling, you must then create a file in the initializers directory titled “omniauth.rb.” Inside this file, you will need to set up your api keys provided when you registered your application with Twitter. Code samples can be found at Twitter’s developer website. From my understanding, the material covered above is the needed material for a handshake between your application and Twitter.

In order to use this functionality, we must first add two custom routes to our routes file. The first route will have a prefix of “twitter_login,” the verb “get” and the route “/auth/twitter.” The second route will have the verb “get” and a path “/auth/twitter/callback” that points to the action “create” within the sessions controller. The first route is designed to send the user to a Twitter URL where they can enter their credentials and submit. The second route is designed to send the Twitter data to our “create” action within the sessions controller.

The data being sent back to our app from Twitter must be stored within the user table. You will need to generate a migration to account for all of the data that you wish to store. Once stored, this data will then be mapped to current user attributes within your app. This method will be placed inside your user model. By doing this, we have all the information we need to build out the create action inside the sessions controller. Both the create action and the user method will rely on attributes/methods provided by the “omniauth” gem.

From this point forward, you will need to build out the remaining restful routes and handle the current user state but this included the heavy lifting for implementing OAuth for Twitter. If you have further inquiries, I would suggest visiting the Twitter developer website.

I understand this is a very brief overview, not a roadmap to a fully functioning OAuth. I simply wanted to write this post to solidify my interaction with this topic.