Hello World from OSS Silicon Valley


HowToUse/RubyOnRails/4.2/Omniauth/1.2


_ Prerequisite

_ Install&Setup

Step.1
Setup "Client ID" and "Client Secret" from GitHub.com
Step.2
Edit Gemfile
$ vi Gemfile
gem 'omniauth'
gem 'omniauth-github'

(You can see sample from here.)

Step.3
Install gem files
$ bundle install
Step.4
Setup "Client ID" and "Client Secret" to environment variable.
$ vi ~/.bashrc
export GITHUB_KEY="<Client ID>"
export GITHUB_SECRET="<Client Secret>"

_ HowToUse

Step.1
Add omniauth.rb
$ vi config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
 provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
end

(You can see sample from here.)

Step.2
Add User model.
$ rails g model user provider:string uid:string screen_name:string name:string
$ rake db:migrate
Step.3
Add method for User model.
class User < ActiveRecord::Base
  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth['provider']
      user.uid = auth['uid']
      user.screen_name = auth['info']['nickname']
      user.name = auth['info']['name']
    end
  end
end

(You can see sample from here.)

Step.4
Create necessary controllers.
$ rails g controller base
$ rails g controller home index
$ rails g controller sessions
Step.5
Edit routes.
$ rake routes
root 'home#index'
get "home/index"
get '/auth/:provider/callback', :to => 'sessions#callback'
post '/auth/:provider/callback', :to => 'sessions#callback'
get '/logout' => 'sessions#destroy', :as => :logout

(You can see sample from here.)

Step.6
Edit Base controller.
$ vi app/controller/base_controller.rb
class BaseController < ActionController::Base
  protect_from_forgery
  def login_required
    if session[:user_id]
      @current_user = User.find(session[:user_id])
    else
      redirect_to root_path
    end

  end

  helper_method :current_user

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

(You can see sample from here.)

Step.7
Edit Home controller.
$ vi app/controller/home_controller.rb
class HomeController < BaseController
  def index
  end
end

(You can see sample from here.)

Step.8
Edit Session controller.
$ vi app/controllers/session_controller.rb
class SessionsController < ApplicationController
  def callback
    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_path
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end

(You can see sample from here.)

Step.9
Edit view file.
$ vi app/view/layout/application.rb
<% if current_user %>
  <%= current_user.name %> <%= link_to 'Logout', logout_path %>
<% else %>
  <%= link_to 'Login', '/auth/github' %>
<% end %>

_ Author

S.Yatsuzuka