#236 OmniAuth Part 2
Oct 13, 2010 | 15 minutes | Plugins, Authentication
In this episode we continue our look at integrating OmniAuth with devise. Here I show how to set up new users with validations.
- Download:
- source codeProject Files in Zip (143 KB)
- mp4Full Size H.264 Video (26.3 MB)
- m4vSmaller H.264 Video (17.4 MB)
- webmFull Size VP8 Video (43.6 MB)
- ogvFull Size Theora Video (39.6 MB)
Resources
Update: Florian Unglaub pointed out in the comments that this is necessary to add to the authentications controller in Rails 3.0.4 and later.
authentications_controller.rb
protected # This is necessary since Rails 3.0.4 # See https://github.com/intridea/omniauth/issues/185 # and http://www.arailsdemo.com/posts/44 def handle_unverified_request true end
bash
bundle update rails g controller registrations rails g devise:views
Gemfile
gem 'mongrel', '1.2.0.pre2'
config/initializers/omniauth.rb
require 'openid/store/filesystem' Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET' provider :open_id, OpenID::Store::Filesystem.new('/tmp') end
authentications_controller.rb
def create omniauth = request.env["omniauth.auth"] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication flash[:notice] = "Signed in successfully." sign_in_and_redirect(:user, authentication.user) elsif current_user current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid']) flash[:notice] = "Authentication successful." redirect_to authentications_url else user = User.new user.apply_omniauth(omniauth) if user.save flash[:notice] = "Signed in successfully." sign_in_and_redirect(:user, user) else session[:omniauth] = omniauth.except('extra') redirect_to new_user_registration_url end end end
models/user.rb
def apply_omniauth(omniauth) self.email = omniauth['user_info']['email'] if email.blank? authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid']) end def password_required? (authentications.empty? || !password.blank?) && super end
routes.rb
devise_for :users, :controllers => {:registrations => 'registrations'}
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController def create super session[:omniauth] = nil unless @user.new_record? end private def build_resource(*args) super if session[:omniauth] @user.apply_omniauth(session[:omniauth]) @user.valid? end end end
models/authentication.rb
def provider_name if provider == 'open_id' "OpenID" else provider.titleize end end