CSC/ECE 517 Fall 2013/oss E806 jlv: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(29 intermediate revisions by 2 users not shown)
Line 10: Line 10:
!Changes
!Changes
|- valign="top"
|- valign="top"
|09/24/2013
|10/30/2013
|Revised based on review comments:<br/>- Added OAuth 1.0a and 2.0 guides and comparison to '''[[#Further reading|Further reading]]'''<br/>- Added OAuth official Wiki to '''[[#Further reading|Further reading]]'''<br/>- Added an '''[[#Additional examples|additional example]]''' for Google APIs<br/>- Added a video explaining OAuth to '''[[#Further reading|Further reading]]'''<br/>- Added a few more terms to '''[[#Terminology|Terminology]]''' section<br/>- Using thumbnails instead of full size screenshots in '''[[#Creating an OAuth Provider|Creating an OAuth Provider]]''' and '''[[#Creating an OAuth Consumer|Creating an OAuth Provider]]'''<br>- Added '''[[#Conclusion|Conclusion]]'''
|Updated section on [[#Testing|testing]]:<br/>- Added link to '''[[#Testing|YouTube demo]]'''
|-
|- valign="top"
|09/18/2013
|10/29/2013
|Updated section on [[#Design & Implementation|design]]:<br/>- Added existing and new '''[[#Database|Database design]]'''<br/>- Added existing and new '''[[#Models|Models design]]'''<br/>
|- valign="top"
|10/28/2013
|Initial version
|Initial version
|}
|}
Line 22: Line 25:


===OSS Project===
===OSS Project===
====Classses====
====Classes====
* response_map.rb (94 lines)
* response_map.rb (94 lines)
* feedback_response_map.rb (29 lines)
* feedback_response_map.rb (29 lines)
Line 32: Line 35:
* response.rb (171 lines)  
* response.rb (171 lines)  
====What they do?====
====What they do?====
Responses (all kinds) are instances of filled-out rubrics.  When someone responds to a rubric, a response is created.  There are different kind of responses for different kinds of rubrics.  A response_map keeps track of who the reviewer and who the reviewee are.  ResponseMaps are in 1:1 correspondence with Responses.
Responses (all kinds) are instances of filled-out rubrics.  When someone responds to a rubric, a response is created.  There are different kind of responses for different kinds of rubrics.  A response_map keeps track of who is the reviewer and who is being reviewed.  ResponseMaps have a 1 to 1 correspondence with Responses.
====What we did?====
====What we did?====
The following activities were carried out as part of the project:
The following activities were carried out as part of the project:
; New data migration : Since Responses are in 1:1 correspondence with ResponseMaps, we migrated the data from <code>'''response_maps'''</code> table to <code>'''responses'''</code> table.
; New data migration : Since Responses have a 1 to 1 correspondence with ResponseMaps, we migrated the data from <code>'''response_maps'''</code> table to <code>'''responses'''</code> table.
; Removing table : After the above migration was complete, we removed the <code>'''response_maps'''</code> table from the database.
; Removing table : After the above migration was complete, we removed the <code>'''response_maps'''</code> table from the database.
; Refactoring : We had to refactor the above listed classes to ensure that they continue to operate as expected after removal of the <code>'''response_maps'''</code> table.
; Refactoring : We had to refactor the above listed classes to ensure that they continue to operate as expected after removal of the <code>'''response_maps'''</code> table.
Line 42: Line 45:


===Database===
===Database===
====Existing Design====
====Existing Design====
[[File:E806DBDesignBefore.png]]<br/><br/>
In the existing design, there are two tables <code>'''responses'''</code> and <code>'''response_maps'''</code>. However, there is no need to maintain a separate table called <code>'''response_maps'''</code> since there is a 1:1 mapping between a <code>'''responses'''</code> and <code>'''response_maps'''</code> table entry.
In the existing design, there are two tables <code>'''responses'''</code> and <code>'''response_maps'''</code>. However, there is no need to maintain a separate table called <code>'''response_maps'''</code> since there is a 1:1 mapping between a <code>'''responses'''</code> and <code>'''response_maps'''</code> table entry.
;<code>'''responses'''</code> : Maintains the version number, additional comment, created at, updated at and foreign key for <code>'''response_maps'''</code> table.
;<code>'''responses'''</code> : Maintains the version number, additional comment, created at, updated at and foreign key for <code>'''response_maps'''</code> table.
;<code>'''response_maps'''</code> : Maintains the mapping to reviewed object, reviewer and reviewee. It also maintains the type of the review - Feedback, Team Review, Meta Review, etc.
;<code>'''response_maps'''</code> : Maintains the mapping to reviewed object, reviewer and reviewee. It also maintains the type of the review - Feedback, Team Review, Meta Review, etc.
[[File:E806DBDesignBefore.png]]
<br/>
 
====New Design====
====New Design====
In the new design, there is only one table called <code>'''responses'''</code>. Each row in the <code>'''responses'''</code> table now contains the data from the corresponding row of the <code>'''response_maps'''</code> table.  
[[File:E806DBDesignAfter.png]]<br/><br/>
[[File:E806DBDesignAfter.png]]<br/>
In the new design, there is only one table called <code>'''responses'''</code>. Each row in the <code>'''responses'''</code> table now contains the data from the corresponding row of the <code>'''response_maps'''</code> table.<br/>
In order to achieve this, we wrote a data migration that does the following:
In order to achieve this, we wrote a data migration that does the following:
# Altered <code>'''responses'''</code> table to add the missing columns from <code>'''response_maps'''</code> table
# Altered <code>'''responses'''</code> table to add the missing columns from <code>'''response_maps'''</code> table
# Updated these new columns in the <code>'''responses'''</code> with data from <code>'''response_maps'''</code> table by performing a join on <code>'''responses.map_id'''</code> and <code>'''response_maps.id'''</code> fields.
# Updated these new columns in the <code>'''responses'''</code> with data from <code>'''response_maps'''</code> table by performing a join on <code>'''responses.map_id'''</code> and <code>'''response_maps.id'''</code> fields.
# Dropped the <code>'''response_maps'''</code> table
# Dropped the <code>'''response_maps'''</code> table
<br/>
===Models===
====Existing Design====
[[File:E806DBModelsDesignBefore.png]]<br/><br/>
In the existing design, there is a 1:1 composition relationship between <code>'''Response'''</code> and <code>'''ResponseMap'''</code> model i.e. <code>'''Response'''</code> has-a <code>'''ResponseMap'''</code>.


===Terminology===
====New Design====
Some terminology used throughout this page<ref name='ietf'/>:
[[File:E806DBModelsDesignAfter.png]]<br/><br/>
; Client/Consumer : An HTTP client capable of making OAuth authenticated requests.
In the new design, since there is only one database table representing <code>'''Response'''</code> and <code>'''ResponseMap'''</code> models - we have an inheritance relationship as depicted above. The inheritance relationship allows us to localize the impact of the data migration. This was necessary because many models, views and controllers are using <code>'''ResponseMap'''</code> model. In this design, <code>'''ResponseMap'''</code> just forwards <code>ActiveRecord</code> calls to <code>'''Response'''</code> since columns from <code>'''response_maps'''<code> table are now in <code>'''responses'''</code> table.
; Server/Provider : An HTTP server capable of accepting OAuth authenticated requests.
; Protected resource : An access-restricted resource that can be obtained from the server using an OAuth authenticated request.
; Resource owner : An entity capable of accessing and controlling protected resources by using credentials to authenticate with the server.
; Credentials : Credentials are a pair of a unique identifier and a matching shared secret. OAuth defines three classes of credentials: client, temporary and token, used to identify and authenticate the client making the request, the authorization request, and the access grant, respectively.
; Token : A unique identifier issued by the server and used by the client to associate authenticated requests with the resource owner whose authorization is requested or has been obtained by the client.  Tokens have a matching shared-secret that is used by the client to establish its ownership of the token, and its authority to represent the resource owner.
; Shared secret: Tokens have a matching shared-secret that is used by  the client to establish its ownership of the token, and its authority to represent the resource owner.
; HMAC: keyed-hash message authentication code – used to verify the data integrity and authentication.
; HMAC-sha1 : HMAC can be used in combination with any iterated cryptographic hash function. SHA1 is one such hash function.
; Model: Model is where the application’s data objects are stored.
; Subclass : Derived or child class.
; Plugin : A software component that adds a specific feature to the software application.
; Migrate : Process of altering the database schema in a consistent and easy way.
 
===How OAuth operates?===
In the traditional client-server authentication model, the client uses its credentials to access its resources hosted by the server. OAuth introduces a third role to this model: the resource owner. In the OAuth model, the client (which is not the resource owner, but is acting on its behalf) requests access to resources controlled by the resource owner, but hosted by the server.
In order for the client to access resources, it first has to obtain permission from the resource owner.  This permission is expressed in the form of a token and matching shared-secret.  The purpose of the token is to make it unnecessary for the resource owner to share its credentials with the client.  Unlike the resource owner credentials, tokens can be issued with a restricted scope and limited lifetime and revoked independently.
This specification consists of two parts.  The first part defines a redirection-based user-agent process for end-users to authorize client access to their resources, by authenticating directly with the server and provisioning tokens to the client for use with the authentication method.  The second part defines a method for making authenticated HTTP requests using two sets of  credentials, one identifying the client making the request, and a second identifying the resource owner on whose behalf the request is being made.<ref name='guide'/>
 
==== The workflow ====
OAuth uses tokens to represent the authorization granted to the client by the resource owner.  Typically, token credentials are issued by the server at the resource owner's request, after    authenticating the resource owner's identity (usually using a username and password). There are many ways in which a server can facilitate the provisioning of token credentials. This redirection-based authorization method includes the following steps as shown in the diagram:<br/><br/>
[[File:Wikipage1.jpg]]
; Step 1 : The resource owner requests the client to perform an action on the server.
; Step 2 to 3 : The client obtains a set of temporary credentials from the server (in the form of an identifier and shared-secret).  The temporary credentials are used to identify the access request throughout the authorization process.
; Step 4 to 5 : The resource owner authorizes the server to grant the client's access request (identified by the temporary credentials).
; Step 6 to 7 : The client uses the temporary credentials to request a set of token credentials from the server, which will enable it to access the resource owner's protected resources.
The server '''must''' revoke the temporary credentials after being used once to obtain the token credentials. It is '''recommended''' that the temporary credentials have a limited lifetime. Servers '''should''' enable    resource owners to revoke token credentials after they have been issued to clients.<ref name='ietf'/><br/><br/>
 
==== Real life example ====
Following is a real life example for an OAuth interaction:<ref name='guide'/>
<br/>
:''Jane is back from her Scotland vacation and wants to share some of her vacation photos with her friends. Jane uses Faji, a photo sharing site, for sharing journey photos. She signs into her faji.com account, and uploads two photos which she marks private.''
: [[File:OAUTHscreen1.png]]
Using OAuth terminology, Jane is the resource owner and Faji the server. The 2 photos Jane uploaded are the protected resources.
: ''After sharing her photos with a few of her online friends, Jane wants to also share them with her grandmother. But grandma doesn’t have an internet connection so Jane plans to order prints and have them mailed to grandma. Being a responsible person, Jane uses Beppa, an environmentally friendly photo printing service.''
Using OAuth terminology, Beppa is the client. Since Jane marked the photos as private, Beppa must use OAuth to gain access to the photos in order to print them.
: ''Jane visits beppa.com and begins to order prints. Beppa supports importing images from many photo sharing sites, including Faji. Jane selects the photos source and clicks Continue.''
: [[File:OAUTHscreen2.png]]
<br/>
When Beppa added support for Faji photo import, a Beppa developer known in OAuth as a client developer obtained a set of client credentials (client identifier and secret) from Faji to be used with Faji’s OAuth-enabled API.
<br/>
After Jane clicks Continue, something important happens in the background between Beppa and Faji. Beppa requests from Faji a set of temporary credentials. At this point, the temporary credentials are not resource-owner-specific, and can be used by Beppa to gain resource owner approval from Jane to access her private photos.
<br/>
: [[File:OAUTHflow2grfc.png]]
: ''Jane clicked Continue and is now waiting for her screen to change. She sips from her prized Black Bowmore while waiting for the next page to load.''
When Beppa receives the temporary credentials, it redirects Jane to the Faji OAuth User Authorization URL with the temporary credentials and asks Faji to redirect Jane back once approval has been granted to http://beppa.com/order.
<br/>
Jane has been redirected to Faji and is requested to sign into the site. OAuth requires that servers first authenticate the resource owner, and then ask them to grant access to the client.
: ''Jane notices she is now at a Faji page by looking at the browser URL, and enters her username and password.''
: [[File:OAUTHscreen3.png]]
<br/>
OAuth allows Jane to keep her username and password private and not share them with Beppa or any other site. At no time does Jane enters her credentials into beppa.com.<br/>
After successfully logging into Faji, Jane is asked to grant access to Beppa, the client. Faji informs Jane of who is requesting access (in this case Beppa) and the type of access being granted. Jane can approve or deny access.
: ''Jane makes sure Beppa is getting the limited access it needs. She does not want to allow Beppa to change her photos or do anything else to them. She also notes this is a onetime access good for one hour which should be enough time for Beppa to fetch her photos.''
: [[File:OAUTHscreen4.png]]
<br/>
Once Jane approves the request, Faji marks the temporary credentials as resource-owner-authorized by Jane. Jane’s browser is redirected back to Beppa, to the URL previously provided http://beppa.com/order together with the temporary credentials identifier. This allows Beppa to know it can now continue to fetch Jane’s photos.
: ''Jane waits for Beppa to present her with her photos fetched from her Faji account.''
: [[File:OAUTHscreen5.png]]
<br/>
While Jane waits, Beppa uses the authorized Request Token and exchanges it for an Access Token. Request Tokens are only good for obtaining User approval, while Access Tokens are used to access Protected Resources, in this case Jane’s photos. In the first request, Beppa exchanges the Request Token for an Access Token and in the second (can be multiple requests, one for a list of photos, and a few more to get each photo) request gets the photos.
<br/>
: [[File:OAUTHflow3grfc.png]]
<br/>
When Beppa is done, Jane’s browser refreshes to complete the order.<br/>
Beppa successfully fetched Jane’s photo. They are presented as thumbnails for her to pick and place her order.
: ''Jane is very impressed how Beppa grabbed her photos without asking for her username and password. She likes what she sees and place the print order.''
: [[File:OAUTHscreen6.png]]
<br/>
<br/>


== OAuth in Ruby ==
===Challenges===  
OAuth does not come out of the box with Ruby. However, there are many generic and site-specific (Twitter, Facebook, etc.) gems to enable OAuth in your Ruby application. Some of the popular ones are discussed below.
====Challenge 1====  
 
'''Problem:''' ResponseMaps are created independently of Responses in the current version of the project. However, after merging these tables, we cannot really have a ResponseMap without a Response.<br/>
=== OAuth Provider support ===
'''Resolution:''' We fixed this in a way that controller like <code>grades_controller.rb</code> creates an entry in the <code>responses</code> table and later <code>response_controller.rb</code> (create action) can update this entry.
The following gems provide support for turning your application into an OAuth Provider:
* '''<code>[http://oauth.rubyforge.org/ oauth]</code>''' and '''<code>[http://github.com/pelle/oauth-plugin oauth-plugin]</code>'''
: <code>[http://oauth.rubyforge.org/ oauth]</code> is a Ruby gem for implementing both OAuth consumers and providers in Ruby applications. However, this is NOT a Rails plugin, but could easily be used as a foundation for a Rails plugin. As a matter of fact it has been pulled out from a Rails plugin called <code>[http://github.com/pelle/oauth-plugin oauth-plugin]</code> which now requires this gem.<ref name="oauthgem">Braendgaard, P. (2010, April 21). ''Ruby oauth gem.'' Retrieved from https://github.com/pelle/oauth</ref>
: The <code>[http://github.com/pelle/oauth-plugin oauth-plugin]</code> can generate an OAuth Provider that supports the following features out of the box:<ref name="oauthplugin">Braendgaard, P. (2012, April 2). ''OAuth plugin.'' Retrieved from https://github.com/pelle/oauth-plugin</ref>
: 1. User can register their own applications to receive consumer key/secret pairs.
: 2. Provider supports standard best practices out of the box hmac-sha1, etc.
: 3. Users can manage and revoke tokens issued in their name
: 4. Easy before filter to provide OAuth protection on your actions
 
* '''<code>[https://github.com/songkick/oauth2-provider oauth2-provider]</code>'''
: This gem provides a toolkit for adding OAuth2 provider capabilities to a Ruby web app. It handles most of the protocol for you. It is designed to provide a sufficient level of abstraction such that it can implement updates to the protocol without affecting your application code at all. Thus, the providers only have to be concerned about authenticating users and letting them grant access to client apps.<ref>Coglan, J. (2013, August 19). ''oauth2-provider gem.'' Retrieved from https://github.com/songkick/oauth2-provider</ref>
 
=== OAuth Consumer support ===
* '''<code>[http://oauth.rubyforge.org/ oauth]</code>''' and '''<code>[http://github.com/pelle/oauth-plugin oauth-plugin]</code>'''
: The oauth-plugin can generate an OAuth Consumer which includes a controller to manage the authentication flow between your application and any number of external OAuth secured applications that you wish to connect to.<ref name="oauthgem"/>
* '''<code>[https://github.com/intridea/omniauth omniauth]</code>'''
: <code>[https://github.com/intridea/omniauth omniauth]</code> is a mega-authorization gem, giving you access to the OAuth processes for a whole list of web services (Twitter, Facebook, Foursquare, Gowalla, Netflix, YouTube, etc.), so you can call specific functions for each service and set it up quickly.<ref name="omniauth">Drake, K. (2012, November). ''Omniauth''. Retrieved from https://github.com/intridea/omniauth/wiki</ref><ref name="oauthvsomniauth">Rhode, J. (2011, July). ''Omniauth vs oauth-plugin''. Retrieved from http://stackoverflow.com/a/6830090/1617100</ref>
* '''<code>[https://github.com/moomerman/twitter_oauth twitter_oauth]</code>'''
: <code>[https://github.com/moomerman/twitter_oauth twitter_oauth]</code> is an example of a site-specific OAuth gem that generates OAuth consumer for Twitter.
 
== Sample OAuth Application ==
This section will help you create two web applications:
* '''OAuthProviderApp''': A web application that allows access to it's services through OAuth.
: https://github.com/jbangani/OAuthProviderSample
* '''OAuthConsumerApp''': A web application that accesses services provided by OAuthProviderApp through OAuth.
: https://github.com/jbangani/OAuthConsumerSample
 
These tutorials were created on the following system configuration:
Windows 7
Ruby 1.9.3
Rails 3.2


=== Creating an OAuth Provider ===
====Challenge 2====  
Following steps will create a basic Rails application that uses OAuth to authenticate the requests.<br/>
'''Problem:''' Existing code uses <code>response.id</code> and <code>response_map.id</code>. As per the outcome of our earlier discussions, there was a need to maintain the <code>map_id</code>. However, after aliasing <code>map_id</code> to id (in order to resolve calls from controllers), we found that some part of the code also refers to <code>response.id</code><br/>
1. Create a Rails application and remove <code>public/index.html</code>
'''Resolution:''' Since the references to <code>response.id</code> are very few, 2 files to be specific. We updated these files to use a different attribute name i.e. <code>response.response_id</code>
rails new OAuthProviderApp
<br/>
2. Add <code>devise</code>, <code>oauth-plugin</code> and <code>dynamic_form</code> gems to your Gemfile
gem 'dynamic_form'
gem 'devise'
gem 'oauth-plugin'
;<code>[https://github.com/rails/dynamic_form dynamic_form]</code> : DynamicForm holds a few form helper method that are required by <code>oauth-plugin</code>.
;<code>[https://github.com/plataformatec/devise devise]</code> : Flexible authentication solution for Rails with Warden.
<br/>
3. Run <code>bundle install</code> to install the Gems
bundle install
<br/>
4. Run the <code>devise:install</code> and <code>devise User</code> generators to generate the User model, migration, controller and views
rails generate devise:install
rails generate devise User
<br/>
5. Run the <code>oauth_provider</code> generator
rails generate oauth_provider
This will generate the migrations, models, controllers, views and routes for the following:
* OAuthToken or AccessToken - The token used to associate the request with the resource owner.
* ClientApplication - Client application that needs access to the services offered by the Server on behalf of the Resource owner
* OAuthNonce - Used for verifying requests from the client
<br/>
6. Run db:migrate to create tables for User, OAuthToken, ClientApplication, and OAuthNonce in the database
rake db:migrate
<br/>
7. To test the application, add the following route to your <code>config/routes.rb</code>
root :to => 'oauth_clients#index'
Thus, the home page will display the list of OAuth clients registered by a user (developer of OAuth client).
<br/><br/>
8. Add ClientApplication and OAuthToken associations to User model (<code>app/models/user.rb</code>)
has_many :client_applications
has_many :tokens, :class_name => 'Oauth2Token', :order => 'authorized_at desc', :include=>[:client_application]
<br/>
9. Add the following accessors to the corresponding models
attr_accessor :expires_at                                                      # Add this to OauthToken
attr_accessible :user, :client_application                                      # Add this to AccessToken
attr_accessible :nonce, :password, :timestamp                                  # Add this to OauthNonce
attr_accessible :callback_url, :client_application                              # Add this to RequestToken
attr_accessible :user, :client_application, :scope                              # Add this to Oauth2Token
attr_accessible :client_application, :user, :scope, :callback_url              # Add this to Oauth2Verifier
attr_accessible :name, :url, :callback_url, :support_url, :token_callback_url  # Add this to ClientApplication
This is required since the generator for <code>oauth_provider</code> is outdated.
<br/><br/>
10. Add the following alias to <code>app/controllers/oauth_controller.rb</code> and <code>app/controllers/oauth_clients_controller.rb</code> after the class declaration
alias :login_required :authenticate_user!
This is required because <code>oauth-plugin</code> uses <code>login_required</code> method to determine whether the user is authenticated or not. In order to do this, we use the <code>authenticate_user!</code> method provided by <code>devise</code> gem.<br/><br/>
11. Add the following filter to <code>config/application.rb</code>
require 'oauth/rack/oauth_filter'               #Add before declaration of module OAuthProviderApp
config.middleware.use OAuth::Rack::OAuthFilter  #Add after declaration of class Application
This adds the OAuthFilter to the middleware layer and thus allows filtering out unauthorized calls.<br/><br/>
12. Add the following method to <code>app/controllers/application_controller.rb</code>
def current_user=(user)
  current_user = user
end
This method is required by <code>oauth-plugin</code> to let <code>devise</code> know who the user is.<br/><br/>
13. Generate a new controller that will define the services provided by the this provider
rails generate controller API::V1::Data
<br/>
14. Add a dummy service method to this controller (<code>app/controllers/api/v1/data_controller.rb</code>) and have it render some response. This will be the service that the OAuth client will try to access.
class Api::V1::DataController < ApplicationController
  respond_to :json, :xml
  oauthenticate :interactive=>false                # Actions in this controller can only be accessed via OAuth
  def show                                        # This is the service OAuth client will call
    respond_with 'My birthday is on 09/05/2013'
  end
end
<br/>
15. Add the following to <code>config/routes.rb</code>
namespace :api do
  namespace :v1 do
    match "show" => "data#show"
  end
end
<br/>
16. Run the Rails server
rails server -p 3000
<br/>
17. Sign up as a client developer for the OAuthProviderApp at http://localhost:3000/users/sign_up
<br/><br/>
{|
|'''Client registration'''
|'''Client registration success'''
|-
|[[File:tn_OAPSignUp.jpg|link=http://wiki.expertiza.ncsu.edu/images/3/34/OAPSignUp.png]]
|[[File:tn_OAPSignUpSuccess.jpg|link=http://wiki.expertiza.ncsu.edu/images/e/e2/OAPSignUpSuccess.png]]
|}
<br/><br/>
18. Register your application with the following parameters and Note down the Consumer key and Consumer secret
Name:                test
Main Application URL: http://localhost:4000/
Callback URL:        http://localhost:4000/oauth_consumers/test/callback
In the next section, we will create an OAuthConsumerApp with these parameters. OAuthConsumerApp will act as a client for OAuthProviderApp.
<br/><br/>
{|
|'''Application registration'''
|'''Application registration success'''
|-
|[[File:tn_OAPRegister.jpg|link=http://wiki.expertiza.ncsu.edu/images/8/83/OAPRegister.png]]
|[[File:tn_OAPRegisterSuccess.jpg|link=http://wiki.expertiza.ncsu.edu/images/0/03/OAPRegisterSuccess.png]]
|}
<br/><br/>
<br/><br/>
==Refactoring==
Here are some examples of refactoring that were performed throughout the code:
===Use of find()===
We replaced instances of code that use the following version of <code>find()</code>:
<pre>
ResponseMap.find(:all, :conditions => ['reviewee_id = ? and reviewer_id = ?', participant.id, reviewer.id])
</pre>
with the following version of <code>find()</code>
<pre>
ResponseMap.find_all_by_reviewee_id_and_reviewer_id(participant.id, reviewer.id)
</pre>
===Unused code===
In the following method, we found an unused local variable <code>assignment_id</code> that we removed.
<pre>
  def self.delete_mappings(mappings, force=nil)
    failedCount = 0
    mappings.each{
      |mapping|
      assignment_id = mapping.assignment.id
      begin
        mapping.delete(force)
      rescue
        failedCount += 1
      end
    }
    return failedCount
  end
</pre>


=== Creating an OAuth Consumer ===
===Removing redundancy===
Following steps will create a basic Rails application that uses OAuth to access data from the show() action that we just defined.
We removed some redundancy in several parts of the code.
<br/>
1. Create a Rails application and remove <code>public/index.html</code>
rails new OAuthConsumerApp
<br/>
2. Add <code>devise</code> and <code>oauth-plugin</code> gems to your Gemfile
gem 'devise'
gem 'oauth-plugin'
<br/>
3. Run <code>bundle install</code> to install the Gems
bundle install
<br/>
4. Run the <code>devise:install</code> and <code>devise User</code> generators to generate the User model, migrations, controller and views
rails generate devise:install
rails generate devise User
<br/>
5. Run the <code>oauth_consumer</code> generator
rails generate oauth_consumer user
This will generate the migrations, models, controllers and routes for ConsumerToken which is used by this Consumer to authenticate with the Provider.
<br/><br/>
6. Migrate the database to create tables for User and ConsumerToken
rake db:migrate
<br/>
7. Add the following alias to <code>app/controllers/oauth_consumers_controller.rb</code> after the class declaration
alias :login_required :authenticate_user!
This is required because oauth-plugin uses login_required method to determine whether the user is authenticated or not. In order to determine whether the user is authenticated or not, we use the authenticate_user! method provided by devise gem.
<br/><br/>
8. Add the following methods to <code>app/controllers/application_controller.rb</code>
def current_user=(user)
  current_user = user
end
def logged_in?
  user_signed_in?
end
This method is required by <code>oauth-plugin</code> to let <code>devise</code> know who the user is and whether (s)he is logged in or not.<br/><br/>
9. Create a new model that subclasses ConsumerToken for the above OAuthProvider service
class TestToken < ConsumerToken
  TEST_SETTINGS={
      :site => "http://localhost:3000",
      :request_token_path => "/oauth/request_token",
      :access_token_path => "/oauth/access_token",
      :authorize_path => "/oauth/authorize"
  }
  def self.consumer(options={})
    @consumer ||= OAuth::Consumer.new(credentials[:key], credentials[:secret], TEST_SETTINGS.merge(options))
  end
end
The purpose of this subclass is to define the <code>consumer</code> method that is based on the Provider.
<br/><br/>
<br/><br/>
11. Add the following association to the <code>User</code> model
==Testing==
has_one :test, :class_name=>"TestToken", :dependent=>:destroy
We have created a YouTube video that can help reviewers verify that this project works as expected.<br/><br/>
<br/>
[[File:OSSYoutubeDemo.png|link=http://www.youtube.com/watch?v=XT2Kc7dveQ4]]<br/>
10. Add the following to <code>config/initializers/oauth_consumers.rb</code> defining the Consumer key and secret provided by the OAuthProviderApp
OAUTH_CREDENTIALS={
    :test => {
        :key => "CRcIJ15MwSqlDTxsH8MpO3En4wjaOxkqeofLioH4",      # From Step 18 of previous section
        :secret => "C7uci8xkyMShCf4SNXWPclKbBo3ml1Zf2W2XWu4W",  # From Step 18 of previous section
        :expose => true
    }
}
<br/>
11. Generate a controller for testing the application
rails generate controller welcome index
<br/>
12. Add logic to a controller action that performs the OAuth workflow as discussed in Introduction
class WelcomeController < ApplicationController
  def index
    if(current_user)
      @consumer_tokens = TestToken.all :conditions => {:user_id => current_user.id}
      if(@consumer_tokens.first)
        @token = @consumer_tokens.first.client
        render inline: @token.get("/api/v1/show").body
      else
        redirect_to '/oauth_consumers/test'
      end
    else
      redirect_to new_user_registration_path
    end
  end
end
<br/>
13. Add the following route to <code>config/routes.rb</code>
root :to => 'welcome#index'
<br/>
14. Run the rails server on port 4000
rails server -p 4000
<br/>
14. Experience the OAuth workflow
<br/>
<br/>
{|style="width: 200px; background-color: white; cellspacing=20"
==Future work==
|'''Screen 1'''
The future work for this project involves:
|'''Screen 2'''
# Renaming all sub-classes of <code>'''ResponseMap'''</code>, for example: <code>FeedbackResponseMap</code>, so that the names end in <code>'''Response'''</code>, for example: <code>FeedbackResponse</code>.
|'''Screen 3'''
# Remove <code>'''ResponseMap'''</code> model and have it's children inherit from <code>'''Response'''</code> instead.
|'''Screen 4'''
# Refactor all models, controllers and views that use <code>'''ResponseMap'''</code> to use <code>'''Response'''</code>.
|-
|[[File:tn_OACRegister.jpg|link=http://wiki.expertiza.ncsu.edu/images/b/b9/OACRegister.png]]
|[[File:tn_OACRedirect.jpg|link=http://wiki.expertiza.ncsu.edu/images/a/a4/OACRedirect.png]]
|[[File:tn_OAPAuthorize.jpg|link=http://wiki.expertiza.ncsu.edu/images/0/08/OAPAuthorize.png]]
|[[File:tn_OACAccess.jpg|link=http://wiki.expertiza.ncsu.edu/images/8/86/OACAccess.png]]
|}
; Screen 1 : A customer (who has an account with OAuthProviderApp) registers with OAuthConsumerApp
; Screen 2 : Upon registration, the customer is redirected to OAuthProviderApp to import data from OAuthProviderApp to OAuthConsumerApp
; Screen 3 : Customer authorizes OAuthConsumerApp to access his/her data from OAuthProviderApp
; Screen 4 : OAuthConsumerApp can now access Customer's data from OAuthProviderApp
 
==Additional examples==
Following are some full-length tutorials for OAuth creating consumers for popular web applications:
; [http://railscasts.com/episodes/360-facebook-authentication?view=asciicast Facebook Authentication by RailsCasts] : This will show how to create a new Facebook application and configure it. Then add some authentication with the omniauth-facebook gem and top it off with a client-side authentication using the JavaScript SDK.
; [https://github.com/arsduo/koala Koala gem for Facebook] : Koala is a Facebook library for Ruby, supporting the Graph API (including the batch requests and photo uploads), the REST API, realtime updates, test users, and OAuth validation.
; [http://railscasts.com/episodes/235-omniauth-part-1 OmniAuth for Twitter by RailsCasts] : Uses omniauth gem to integrate Twitter based authentication in your application.
; [https://github.com/tardate/rails-twitter-oauth-sample Rails Twitter OAuth Sample] : Demonstrates the use of rails with the Twitter RESTful API with OAuth 1.0a.
; [http://blogs.burnsidedigital.com/2013/03/rails-3-devise-omniauth-and-google/ Rails 3, Devise, Omniauth, and Google] : Uses omniauth gem to integrate Google authentication in your application.
 
==Conclusion==
OAuth is an open standard for authorization that allows users to approve application to act on their behalf without sharing their password. There are several gems such as oauth, oauth-plugin, and omniauth that bring OAuth 1.0a and 2.0 capabilities to your application. These gems hides the internal complexity of the protocol and provides developers with a very simple interface to act as OAuth provider or consumer. The '''[[#Further reading|Further reading]]''' section has links to guides and comparative study of OAuth 1.0a and OAuth 2.0 specifications and an informative video explaining the internals of the protocol.


== References ==
== References ==
<references />
<references />
== Further reading ==
# Braendgaard, P. (2009, July). ''Consuming oauth intelligently in rails''. Retrieved from http://stakeventures.com/articles/2009/07/21/consuming-oauth-intelligently-in-rails
# Braendgaard, P. (2009, July). ''How to turn your rails site into an oauth provider''. Retrieved from http://stakeventures.com/articles/2007/11/26/how-to-turn-your-rails-site-into-an-oauth-provider
# Yonskai, N. (2013, September 19). ''OAuth 1a guide.'' Retrieved from http://oauthbible.com/#oauth-10a-three-legged
# Yonskai, N. (2013, September 19). ''OAuth 2.0 guide.'' Retrieved from http://oauthbible.com/#oauth-2-refresh-token
# Brail, G. (2010, July 27). Top differences between OAuth 1.0(a) and OAuth 2.0 for API calls. Retrieved from https://blog.apigee.com/detail/oauth_differences
# Williams, A. (2009, December 3). ''OAuth official wiki.'' Retrieved from http://wiki.oauth.net/w/page/12238516/FrontPage
# Van den Enden, S. (2010, July 27). Authorization with OAuth 2.0. Retrieved from https://www.youtube.com/watch?v=zTsyeMV-N0c '''VIDEO'''


== Notes ==
== Notes ==
* All references and further reading links are in the APA style
* All references and further reading links are in the APA style
* All the content on this page is from websites that have a Attribution-NonCommercial-NoDerivs 3.0 or similar license that allows us to use their content.
* All the content on this page is from websites that have a Attribution-NonCommercial-NoDerivs 3.0 or similar license that allows us to use their content.

Latest revision as of 04:34, 31 October 2013

E806 Remove ResponseMaps

The primary aim of this project was to create a data migration that merges all data from response_maps table to responses table.


Revision history
Date Changes
10/30/2013 Updated section on testing:
- Added link to YouTube demo
10/29/2013 Updated section on design:
- Added existing and new Database design
- Added existing and new Models design
10/28/2013 Initial version

Introduction

Expertiza

Expertiza is a web application where students can submit and peer-review learning objects (articles, code, web sites, etc). It is used in select courses at NC State and by professors at several other colleges and universities.<ref name='expertizagithub'>Kofink, A. (2013, July). expertiza @ GitHub Retrieved from https://github.com/expertiza/expertiza</ref>

OSS Project

Classes

  • response_map.rb (94 lines)
  • feedback_response_map.rb (29 lines)
  • metareview_response_map.rb (107 lines)
  • participant_review_response_map.rb (5 lines)
  • review_response_map.rb (97 lines)
  • team_review_response_map.rb (5 lines)
  • teammate_review_response_map.rb (104 lines)
  • response.rb (171 lines)

What they do?

Responses (all kinds) are instances of filled-out rubrics. When someone responds to a rubric, a response is created. There are different kind of responses for different kinds of rubrics. A response_map keeps track of who is the reviewer and who is being reviewed. ResponseMaps have a 1 to 1 correspondence with Responses.

What we did?

The following activities were carried out as part of the project:

New data migration
Since Responses have a 1 to 1 correspondence with ResponseMaps, we migrated the data from response_maps table to responses table.
Removing table
After the above migration was complete, we removed the response_maps table from the database.
Refactoring
We had to refactor the above listed classes to ensure that they continue to operate as expected after removal of the response_maps table.

Design

Database

Existing Design



In the existing design, there are two tables responses and response_maps. However, there is no need to maintain a separate table called response_maps since there is a 1:1 mapping between a responses and response_maps table entry.

responses
Maintains the version number, additional comment, created at, updated at and foreign key for response_maps table.
response_maps
Maintains the mapping to reviewed object, reviewer and reviewee. It also maintains the type of the review - Feedback, Team Review, Meta Review, etc.


New Design



In the new design, there is only one table called responses. Each row in the responses table now contains the data from the corresponding row of the response_maps table.
In order to achieve this, we wrote a data migration that does the following:

  1. Altered responses table to add the missing columns from response_maps table
  2. Updated these new columns in the responses with data from response_maps table by performing a join on responses.map_id and response_maps.id fields.
  3. Dropped the response_maps table


Models

Existing Design



In the existing design, there is a 1:1 composition relationship between Response and ResponseMap model i.e. Response has-a ResponseMap.

New Design



In the new design, since there is only one database table representing Response and ResponseMap models - we have an inheritance relationship as depicted above. The inheritance relationship allows us to localize the impact of the data migration. This was necessary because many models, views and controllers are using ResponseMap model. In this design, ResponseMap just forwards ActiveRecord calls to Response since columns from response_maps table are now in responses table.

Challenges

Challenge 1

Problem: ResponseMaps are created independently of Responses in the current version of the project. However, after merging these tables, we cannot really have a ResponseMap without a Response.
Resolution: We fixed this in a way that controller like grades_controller.rb creates an entry in the responses table and later response_controller.rb (create action) can update this entry.

Challenge 2

Problem: Existing code uses response.id and response_map.id. As per the outcome of our earlier discussions, there was a need to maintain the map_id. However, after aliasing map_id to id (in order to resolve calls from controllers), we found that some part of the code also refers to response.id
Resolution: Since the references to response.id are very few, 2 files to be specific. We updated these files to use a different attribute name i.e. response.response_id

Refactoring

Here are some examples of refactoring that were performed throughout the code:

Use of find()

We replaced instances of code that use the following version of find():

ResponseMap.find(:all, :conditions => ['reviewee_id = ? and reviewer_id = ?', participant.id, reviewer.id])

with the following version of find()

ResponseMap.find_all_by_reviewee_id_and_reviewer_id(participant.id, reviewer.id)

Unused code

In the following method, we found an unused local variable assignment_id that we removed.

  def self.delete_mappings(mappings, force=nil)
    failedCount = 0
    mappings.each{
       |mapping|
       assignment_id = mapping.assignment.id
       begin
         mapping.delete(force)
       rescue
         failedCount += 1
       end
    }
    return failedCount
  end

Removing redundancy

We removed some redundancy in several parts of the code.

Testing

We have created a YouTube video that can help reviewers verify that this project works as expected.



Future work

The future work for this project involves:

  1. Renaming all sub-classes of ResponseMap, for example: FeedbackResponseMap, so that the names end in Response, for example: FeedbackResponse.
  2. Remove ResponseMap model and have it's children inherit from Response instead.
  3. Refactor all models, controllers and views that use ResponseMap to use Response.

References

<references />

Notes

  • All references and further reading links are in the APA style
  • All the content on this page is from websites that have a Attribution-NonCommercial-NoDerivs 3.0 or similar license that allows us to use their content.