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

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

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