Authorization with dropbox in Ruby on Rails using dropbox-sdk

For Dropbox authorization we have a nice ruby gem “dropbox-sdk”. Which will provide a nice interface through which we can call the dropbox api in ruby on rails.

we have to create a dropbox application at https://www.dropbox.com/developers/apps.

You have to fill up a form to create an application , below is a sample data for the form

App Type : Core API
App Name: ImageUploader
Description:  Sample  application for image uploading.
Access:  Full Dropbox

After submitting the form you will get  App Key and App secret.

Add gem “dropbox-sdk” in Gemfile and bundle it.

Then create a file dropbox_config.rb in side the “application_name/config/initializer/”.

Add the below data  to dropbox_config.rb file and change the “XXXXXXX” with your app data .

# Get your app key and secret from the Dropbox developer website
DROPBOX_APP_KEY = "XXXXXXXXX"
DROPBOX_APP_KEY_SECRET = "XXXXXXXXX"
DROPBOX_APP_MODE = "dropbox" # if you have a single-directory app or "dropbox" if it has access to the whole dropbox

Now create the controller , here the name of the controller is “users” and the code for it is given below:-

class UsersController < ApplicationController

# @Params : None
# @Return : None
# @Purpose : To create new dropbox session for authorization
def authorize

dbsession = DropboxSession.new(DROPBOX_APP_KEY, DROPBOX_APP_KEY_SECRET)
#serialize and save this DropboxSession
session[:dropbox_session] = dbsession.serialize
#pass to get_authorize_url a callback url that will return the user here
redirect_to dbsession.get_authorize_url url_for(:action => 'dropbox_callback')

end

# @Params : None
# @Return : None
# @Purpose : To callback for dropbox authorization
def dropbox_callback

dbsession = DropboxSession.deserialize(session[:dropbox_session])
dbsession.get_access_token #we've been authorized, so now request an access_token
session[:dropbox_session] = dbsession.serialize
current_user.update_attributes(:dropbox_session => session[:dropbox_session])
session.delete :dropbox_session
flash[:success] = "You have successfully authorized with dropbox."

redirect_to root_path

end # end of dropbox_callback action

end # end of class

Now we are ready to do any thing that is possible with dropbox(eg:- upload ,  download ).

Lets try to upload a file to dropbox the code for it is below
dbsession = DropboxSession.deserialize(current_user.dropbox_session)
# create the dropbox client object
client = DropboxClient.new(dbsession, DROPBOX_APP_MODE)
data = File.read("/path/to/test.png")
client.put_file("test.png",data)

thanks for reading .

You can checkout my sample application at http://warm-badlands-9447.herokuapp.com/