Getting oAuth1 access token and saving it in the DB (ruby)

Here is how I connected to an external API using oAuth, got access token and saved it in DB for future use. Each time I can now access the API with the saved access token as long as it doesn’t expire.
The flow of oAuth is: client(myapp) tries to get access to user’s service, and the service provider(SP) in the middle will handle the authentication and authorization. In our case, our app first connects to the SP, get the request token, use the request token to go to authorize url(or give that url to the user), where the user(in our case, we are also user in that SP) can log in and get the verification code, give it to SP, which generates a access token and return it to us for direct communication between us and the user data.

I am using oAuth(0.4.7) for this development. (https://rubygems.org/gems/oauth/versions/0.4.7). My code snippet below:

First will prepare the consumer object:

consumer_key = ‘thekeyyougetfromexternalapiparty’

consumer_secret = ‘thesecretyougetfromexternalapiparty'

base_url = ‘externalapiurl.com/’

request_token_path = base_url + ‘oauth/request-token'

access_token_path = base_url + 'oauth/access-token'

call_back_url = "oob"




consumer = OAuth::Consumer.new(consumer_key, consumer_secret, {
    
          :scheme => :header,
    
          :http_method => :post,
    
          :request_token_path => request_token_path,
    
          :access_token_path  => access_token_path,
    
          :oauth_callback => call_back_url,
    
          :signature_method   => 'HMAC-SHA1',
    
          :version => '1.0A'

Then, get the request token from the service provider.

request_token = consumer.get_request_token()

After I got the request token, I used the oauth_token from the request token and use it to construct the authorize url, which user can use to log-in in a browser and reads in the verification code from user:

auth_url = "#{base_url}#{request_token.authorize_url}"
verifier = STDIN.gets.strip

Once we have the verification code, we can now get access token:

access_token=request_token.get_access_token(:oauth_verifier => verifier)

This access token now can be used to access the API with the user’s info:

get_info_url = "theurltogetinfoapi"
response = access_token.get(get_info_url)
result = JSON.parse(response.body)

So, now I have the access token and I can access all the services SP gives for the user that logged in!

Sometimes, some SP allows you to use the access token for longer period of time, and you may want to save the access token in you environment or in DB. Here is how I did that:

act = AccessToken.create(token: access_token.token, secret: access_token.secret, expires_in: 10.days, is_expired: false )
act.save

Once this is saved in DB, here is how to rebuild it later:

db_access_token = AccessToken.find_by_is_expired(false)
token = db_access_token.token
secret = db_access_token.secret
access_token = OAuth::AccessToken.new(consumer)
access_token.token = token
access_token.secret = secret

Please note that, we are assuming there is a separate task to update is_expired in DB once the access token expires. Also, the consumer object is the same one we used in the beginning.

So, this is it! Now you have a full fledged oauth communication in ruby/rails!

code4startup Project!

Started a project in code4startup. Its a video tutorial to walk through the develop app like AirBnb. So far liking it. Only problem I found is its not very detail oriented. For example, when it asks to add you something to the code, it doesn’t explain the details. The tutor gives you a link to where to read the details. Other than that, its a good start for me to start coding. So far, I set up the project with bootstrap and an authentication system with Devise. My plan to build this project along with the tutorial this month. And then start my own project form December.

Rails 4 Way!

I started reading Rails 4 Way by Obie Fernandez, Kevin Faustino and Vitaly Kushner, as a part of my study to revisit ruby on rails, as I am not working for one and half years. I have finished one chapter today and so far very much liked the way it started and going. Its a bit advanced not like a beginner book. Its started with the most important thing that Rails offer: conventional over configuration. So, the first chapter mostly talked about bundler, gemfiles, all environment files, initializer, logs etc. This is a summary of the first chapter: some lines copied from the book:

  • bundle install will install all the gems and their dependencies found in Gemfile and update Gemfile.lock to lock whats installed. (Every time you install or update, Bundler calculates the dependency tree for your application and stores
    the results in a file named Gemfile.lock)
  • All the gems can be packaged by bundle in the vendor/cache directory inside the Rails application so that no need to connect to rubygems.com
  • There are three files involved in setting up the entire Rails stack:
    • boot.rb: sets up Bundler and load paths
    • application.rb: loads rails gems, gems for the specified Rail.env, and configures the application
    • environment.rb: runs all initializers
  • To speed up the boot time of starting a Rails server during development, code is no longer eager loaded. This behavior is governed by the config.eager_load setting:
    • config.eager_load = false
  • Caching is false in development mode
    • config.action_controller.perform_caching = false

This chapter has very detailed information on all different kind of configuration, also the one we can separate for each environments.

Lets be back!!

I was disappeared for a while, and I have some very valid reasons 🙂 I had two kids in last three years. My son is now 2 years old and my daughter is 3 months old 🙂 so, you can imagine the stress and all new responsibilities. I have my fun moments but so far its mostly a lot of work. So, I am stressed almost all the time! Things are getting better slowly.

I am not working for last one and half year to take care of the kids. But I am planning to go back to work soon, so started revisiting my old projects and building some new to refresh my memory. I will try to keep an update here from now on. With two its really hard to study, look for jobs and get the time to blog, but I will try. Hope I am motivated and manage the time to update!

Updating My Github Account :)

So far my github repo remained mostly empty. I have always worked at corporate companies and since I was mostly developing for the company I had very few projects of my own to share, except that I had some private projects and not visible in Github. I started looking for jobs recently and realized how important the Github link is to show some projects I have worked on. That’s why I build some new and updated some old private projects, pushed them to heroku and made the code public in Github.

Here is my Github page now:

https://github.com/techiegirl?

And these are the apps running in Heorku now:

5 projects in one month

To brush up my knowledge in RoR, also getting more comfortable with jQuery, javascript, HTML, CSS planning on doing 5 projects in one month starting today. I know new year is around the corner and we always tend to start afresh on January 1st, but I think for me there were so many tomorrows, January 2st, or June 1st or my birthday that I am not in a position to wait for a particular date. The only date I should follow is TODAY 🙂

Autocomplete in Rails App

Today, I added autocomplete to the search box I talked about in my last post. There are gems for doing it, but I found using jquery, its easier.

I made sure I have ‘jquery-rails‘ in my Gemfile, then I added ‘//= require jquery-ui‘ in application.js. Also, I downloaded the jquery ui css file, save it in ‘vendor/stylesheets/jquery-ui.css‘ and then added the line ‘ *= require jquery-ui.css’ in application.css

Then, I was ready to use autocomplete. For that, I created a route match ‘/autosearch’, to: “home#autosearch”, via: “get”.

Then created the method:

def autosearch
items = Item.search(params[:term])
render json: items.map(&:name)
end

Then, the jquery hookup in application.js:

$(function() {
$(“#search”).autocomplete({
source: ‘/autosearch’,
minLength: 2, delay: 500
});
});

Rails 4 and Basic Search Box with Ajax

Today, created a basic search page with rails 4 and Ajax.
Rails comes with ajax support. Adding remote => true to the action will make the action a ajax request instead of reloading the whole page.
This is what I did:
– In my home controller I have the index action, root points to index, so when index.html.erb renders I render the search box as follows:

<%= form_tag(‘/search’, remote: true) do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag “Search”, :name => nil %>

<% end %>

– Since my form action says remote: true, this action will act as a ajax call.
– Added a search method in Home controller and also the route in route file

match ‘/search’, to: “home#search”, via: “post”

– The search mehtod just return the searched results in a instance variable @item which is available to the js view search.js.erb

$(‘#items’).html(‘<%= escape_javascript(render(“items”)) %>’);
$(‘#items’).show();

– The partial is a basic partial to render the results of the @items

Voila! It worked smooth..
Next, I want to add autocomplete in that search box.
🙂

Maven issues

So, when mvn package failed for a file,  I downloaded the jar from online and the ran the following:

mvn install:install-file -Dfile=sqljdbc.jar -DgroupId=com.microsoft -DartifactId=sqljdbc -Dversion=3.0 -Dpackaging=jar

Then I did:

mvn clean

And then

mvn install

And finally

mvn package

Then it worked! Phew!

Some Helpful *ix Commands

Last few days ran into few linux commands which is very important in day today development, wanted to add it to my blog for later reference:

  • Match String and get line number and filename:
    grep -n STRING_TO_SEARCH * (* can be filename if you know the file to look into)
  • Remove first N lines from a file:
    sed -i '1,10d' filename
  • Run a shell script as background and have output into a log:
  • source filetorun.sh readfromit.txt > log.log 2>&1 &
  • Check all process by username:
    ps -uusername
  • Find number of files inside a folder:(cd into the folder and)
    ls -1 | wc -l
  • Check memory usage in MB:
    free -m
  • Machine’s uptime:
    uptime