Screencast: OmniAuth Teil 2

Im zweiten Teil der OmniAuth-Screencasts zeigt Ryan wie OmniAuth in Device integriert werden kann und wie neue Benutzer incl. Validierung angelegt werden können.

 

Download:

Download(25.6 MB, 15:59)
Alternativer Download für iPod & Apple TV(23.9 MB, 15:59)

 

Resourcen:

 

Quellcode:

[bash]
bundle update
rails g controller registrations
rails g devise:views
[/bash]

[ruby]
# Gemfile
gem ‚mongrel‘, ‚1.2.0.pre2‘

# config/initializers/omniauth.rbb
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
[/ruby]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.