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 ItuLucas Renan
 
Empowering users: modifying the admin experience
Empowering users: modifying the admin experienceEmpowering users: modifying the admin experience
Empowering users: modifying the admin experienceBeth Soderberg
 
Plug in development
Plug in developmentPlug in development
Plug in developmentLucky Ali
 
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.3kidtangerine
 
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 - #wcmiaRoy Sivan
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Vikas Chauhan
 
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 | #wcmiaRoy Sivan
 
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 Vengeancebrianauton
 
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 frameworkPankaj Bhageria
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On RailsWen-Tien Chang
 
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 rails3Andolasoft Inc
 
multiple views and routing
multiple views and routingmultiple views and routing
multiple views and routingBrajesh Yadav
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialKaty Slemon
 
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 expertKaty Slemon
 
Rails Awesome Email
Rails Awesome EmailRails Awesome Email
Rails Awesome Emailimedo.de
 

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 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 8Katy Slemon
 
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 IssueSagar Arlekar
 
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 30fiyuer
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin GeneratorJohn Cleveley
 
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 + TypeScriptKaty Slemon
 
Panmind at Ruby Social Club Milano
Panmind at Ruby Social Club MilanoPanmind at Ruby Social Club Milano
Panmind at Ruby Social Club MilanoPanmind
 
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 pluginAnthony 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 和 AjaxWen-Tien Chang
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdevFrank Rousseau
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action packrupicon
 
Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016Catalyst patterns-yapc-eu-2016
Catalyst patterns-yapc-eu-2016John Napiorkowski
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsJim Jeffers
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Useful Rails Plugins
Useful Rails PluginsUseful Rails Plugins
Useful Rails Pluginsnavjeet
 
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 exampleKaty Slemon
 
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.
 
Rails antipatterns
Rails antipatternsRails antipatterns
Rails antipatternsChul Ju Hong
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-publicChul Ju Hong
 

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

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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 2024Rafal Los
 
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 organizationRadu Cotescu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
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...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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 FresherRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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...Miguel Araújo
 
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 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Recently uploaded (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 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...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced 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...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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