SlideShare a Scribd company logo
1 of 22
Devise, OmniAuth, and
               Facebook
A tutorial on how to setup basic rails security using Facebook for authentication
Setup
   Create your basic application
    > rvm use ruby-1.9.2-p290@rails3.2
    > rails new MyGreatApp


   Add devise to your gemfile
    gem 'devise'


   Run bundler again
    > bundle install
Generate User Model
   Generate devise modules
    > rails generate devise:install


   Generate User model
    > rails generate devise User
Update Routes and Configuration
   Add the following line to config/environments/development.rb
    config.action_mailer.default_url_options = { :host => 'localhost:3000' }

   Add a default route to config/routes.rb
    root :to => ‘home#index’


   Add some flash notices into the base template
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>


   Disable model loading when compiling assets. Add the following to
    config/application.rb
    config.assets.initialize_on_precompile = false
Generated User Model
class User < ActiveRecord::Base

 # Include default devise modules. Others available are:

  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and
:omniauthable

 devise :database_authenticatable, :registerable,

         :recoverable, :rememberable, :trackable, :validatable




 # Setup accessible (or protected) attributes for your model

 attr_accessible :email, :password, :password_confirmation, :remember_me

end
Generated Migration
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable

        t.timestamps
      end

      add_index :users, :email,                :unique => true
      add_index :users, :reset_password_token, :unique => true
end

end
Add before filter
   Add a before filter to app/controllers/application_controller.rb
       This will protect all your actions. Use an except filter in places you don’t need
    > before_filter :authenticate_user!


   Create a home controller
    > rails generate controller home


   Add a method and view for index

   Remove index.html from public
Run the application and try it out
Congratulations
   You now have the basic devise working

   See https://github.com/plataformatec/devise for more detailed information
    about what you can do
Add Facebook
   Now everybody wants the ability to sign in using Facebook

   Add omniauth-facebook to your gemfile.
    gem 'omniauth-facebook’


   Do a Bundle install
Configure Devise
   Go into the config/initializers/devise.rb and add
    require "omniauth-facebook"
    config.omniauth :facebook, "APP_ID", "APP_SECRET”

       Go to https://github.com/mkdynamic/omniauth-facebook to get more
        information about options include scopes and display options.

   Go to Facebook and generate a developer key
       Go to https://developers.facebook.com/apps/ select to create a new app
Configure the Facebook App
Set App Domain, Website and capture IDs
Finish configuration
   Take the keys generated by Facebook and put them into config/devise.rb

   Add Omniauth to your User object.
    devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable, :omniauthable
Setup callbacks
   When Facebook returns to the application there are some routes that are
    needed.

   Create a Users:OmniauthCallbackController in the app/controllers/users
    folder.
       Will show this file on the next slide

   Add a route to the new controller by updatating the devise_for in
    config/routes.rb
    devise_for :users, :controllers => { :omniauth_callbacks =>
    "users/omniauth_callbacks" }
Users::OmniauthCallbacksController
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    # You need to implement the method below in your model
    @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)

   if @user.persisted?
     flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
     sign_in_and_redirect @user, :event => :authentication
   else
     session["devise.facebook_data"] = request.env["omniauth.auth"]
     redirect_to new_user_registration_url
   end
 end

  def passthru
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end
end
Add finder to User model
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
   data = access_token.extra.raw_info
   if user = User.where(:email => data.email).first
     user
   else # Create a user with a stub password.
     User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
   end
 end
Run
Connect
Grant Access
Done
More
   https://github.com/plataformatec/devise

   https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview

   https://github.com/plataformatec/devise/wiki/How-To:-Create-Haml-and-
    Slim-Views

More Related Content

What's hot

Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
Lucas Renan
 
Plug in development
Plug in developmentPlug in development
Plug in development
Lucky Ali
 
Ruby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails frameworkRuby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails framework
Pankaj Bhageria
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
Wen-Tien Chang
 
multiple views and routing
multiple views and routingmultiple views and routing
multiple views and routing
Brajesh Yadav
 

What's hot (20)

Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experience
 
13.exemplu closure controller
13.exemplu closure controller13.exemplu closure controller
13.exemplu closure controller
 
Plug in development
Plug in developmentPlug in development
Plug in development
 
Rapid Application Development with CakePHP 1.3
Rapid Application Development with CakePHP 1.3Rapid Application Development with CakePHP 1.3
Rapid Application Development with CakePHP 1.3
 
Building WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmiaBuilding WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmia
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2
 
How to build Client Side Applications with WordPress and WP-API | #wcmia
How to build Client Side Applications with WordPress and WP-API | #wcmiaHow to build Client Side Applications with WordPress and WP-API | #wcmia
How to build Client Side Applications with WordPress and WP-API | #wcmia
 
Rails engines
Rails enginesRails engines
Rails engines
 
Simplify Your Rails Controllers With a Vengeance
Simplify Your Rails Controllers With a VengeanceSimplify Your Rails Controllers With a Vengeance
Simplify Your Rails Controllers With a Vengeance
 
Ruby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails frameworkRuby conf 2011, Create your own rails framework
Ruby conf 2011, Create your own rails framework
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
19.imagini in laravel5
19.imagini in laravel519.imagini in laravel5
19.imagini in laravel5
 
Ajax pagination using j query in rails3
Ajax pagination using j query in rails3Ajax pagination using j query in rails3
Ajax pagination using j query in rails3
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
multiple views and routing
multiple views and routingmultiple views and routing
multiple views and routing
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
 
Top laravel packages to install handpicked list from expert
Top laravel packages to install handpicked list from expertTop laravel packages to install handpicked list from expert
Top laravel packages to install handpicked list from expert
 
Rails Awesome Email
Rails Awesome EmailRails Awesome Email
Rails Awesome Email
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 

Similar to Devise and Rails

How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
fiyuer
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
Joao Lucas Santana
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
Anthony Montalbano
 
Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation
Compare Infobase Limited
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
Wen-Tien Chang
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
Frank Rousseau
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)
Oro Inc.
 

Similar to Devise and Rails (20)

How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8
 
Rails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 IssueRails Plugins - Linux For You, March 2011 Issue
Rails Plugins - Linux For You, March 2011 Issue
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
 
Panmind at Ruby Social Club Milano
Panmind at Ruby Social Club MilanoPanmind at Ruby Social Club Milano
Panmind at Ruby Social Club Milano
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation Zend - Installation And Sample Project Creation
Zend - Installation And Sample Project Creation
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action pack
 
Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Plugins
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)Adding custom ui controls to your application (1)
Adding custom ui controls to your application (1)
 
Rails antipatterns
Rails antipatternsRails antipatterns
Rails antipatterns
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-public
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Devise and Rails

  • 1. Devise, OmniAuth, and Facebook A tutorial on how to setup basic rails security using Facebook for authentication
  • 2. Setup  Create your basic application > rvm use ruby-1.9.2-p290@rails3.2 > rails new MyGreatApp  Add devise to your gemfile gem 'devise'  Run bundler again > bundle install
  • 3. Generate User Model  Generate devise modules > rails generate devise:install  Generate User model > rails generate devise User
  • 4. Update Routes and Configuration  Add the following line to config/environments/development.rb config.action_mailer.default_url_options = { :host => 'localhost:3000' }  Add a default route to config/routes.rb root :to => ‘home#index’  Add some flash notices into the base template <p class="notice"><%= notice %></p> <p class="alert"><%= alert %></p>  Disable model loading when compiling assets. Add the following to config/application.rb config.assets.initialize_on_precompile = false
  • 5. Generated User Model class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me end
  • 6. Generated Migration class DeviseCreateUsers < ActiveRecord::Migration def change create_table(:users) do |t| t.database_authenticatable :null => false t.recoverable t.rememberable t.trackable t.timestamps end add_index :users, :email, :unique => true add_index :users, :reset_password_token, :unique => true end end
  • 7. Add before filter  Add a before filter to app/controllers/application_controller.rb  This will protect all your actions. Use an except filter in places you don’t need > before_filter :authenticate_user!  Create a home controller > rails generate controller home  Add a method and view for index  Remove index.html from public
  • 8. Run the application and try it out
  • 9. Congratulations  You now have the basic devise working  See https://github.com/plataformatec/devise for more detailed information about what you can do
  • 10. Add Facebook  Now everybody wants the ability to sign in using Facebook  Add omniauth-facebook to your gemfile. gem 'omniauth-facebook’  Do a Bundle install
  • 11. Configure Devise  Go into the config/initializers/devise.rb and add require "omniauth-facebook" config.omniauth :facebook, "APP_ID", "APP_SECRET”  Go to https://github.com/mkdynamic/omniauth-facebook to get more information about options include scopes and display options.  Go to Facebook and generate a developer key  Go to https://developers.facebook.com/apps/ select to create a new app
  • 13. Set App Domain, Website and capture IDs
  • 14. Finish configuration  Take the keys generated by Facebook and put them into config/devise.rb  Add Omniauth to your User object. devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable
  • 15. Setup callbacks  When Facebook returns to the application there are some routes that are needed.  Create a Users:OmniauthCallbackController in the app/controllers/users folder.  Will show this file on the next slide  Add a route to the new controller by updatating the devise_for in config/routes.rb devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
  • 16. Users::OmniauthCallbacksController class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook # You need to implement the method below in your model @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user) if @user.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook" sign_in_and_redirect @user, :event => :authentication else session["devise.facebook_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end def passthru render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false end end
  • 17. Add finder to User model def self.find_for_facebook_oauth(access_token, signed_in_resource=nil) data = access_token.extra.raw_info if user = User.where(:email => data.email).first user else # Create a user with a stub password. User.create!(:email => data.email, :password => Devise.friendly_token[0,20]) end end
  • 18. Run
  • 21. Done
  • 22. More  https://github.com/plataformatec/devise  https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview  https://github.com/plataformatec/devise/wiki/How-To:-Create-Haml-and- Slim-Views