#241 Simple OmniAuth
Nov 22, 2010 | 9 minutes | Plugins, Authentication
Authentication is incredibly simple to add with just OmniAuth if you don't need username/password or multiple authentications per user.
- Download:
- source codeProject Files in Zip (101 KB)
- mp4Full Size H.264 Video (13.5 MB)
- m4vSmaller H.264 Video (9.23 MB)
- webmFull Size VP8 Video (23.8 MB)
- ogvFull Size Theora Video (18.5 MB)
There is a newer version of this episode, see the revised episode.
Resources
Update 12/5/11: Some things have changed since OmniAuth version 1.0 was released. Each provider is now a separate gem that should be included in the Gemfile, and the "user_info" hash is now simply "info". The changes have been made below.
bash
rails g controller sessions rails g model user provider:string uid:string name:string rake db:migrate
Gemfile
gem 'omniauth-twitter'
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["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
rhtml
<% if current_user %> Welcome <%= current_user.name %>! <%= link_to "Sign Out", signout_path %> <% else %> <%= link_to "Sign in with Twitter", "/auth/twitter" %> <% end %>