· 1 min read

Screencast: Authentifizierung über OmniAuth

Download:

Download(12 MB, 9:06) Alternativer Download für iPod & Apple TV(12 MB, 9:06)

Resourcen:

Quellcode:

[bash] rails g controller sessions rails g model user provider:string uid:string name:string rake db:migrate [/bash]

[ruby] # Gemfile gem ‘omniauth’

# config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, ‘CONSUMER_KEY’, ‘CONSUMER_SECRET’ end

# routes.rb match “/auth/:provider/callback” => “sessions#create” match “/signout” => “sessions#destroy”, :as => :signout

# sessions_controller.rb def create auth = request.env[“omniauth.auth”] user = User.find_by_provider_and_uid(auth[“provider”], auth[“uid”]) || User.create_with_omniauth(auth) session[:user_id] = user.id redirect_to root_url, :notice => “Signed in!” end

def destroy session[:user_id] = nil redirect_to root_url, :notice => “Signed out!” end

# models/user.rb def self.create_with_omniauth(auth) create! do |user| user.provider = auth[“provider”] user.uid = auth[“uid”] user.name = auth[“user_info”][“name”] end end

# application_controller.rb helper_method :current_user

private

def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end [/ruby]

[html] <% if current_user %> Welcome <%= current_user.name %>! <%= link_to “Sign Out”, signout_path %> <% else %> <%= link_to “Sign in with Twitter”, “/auth/twitter” %> <% end %> [/html]

Back to Blog