http://<host name>/auth/github/callback
$ vi Gemfile
gem 'omniauth' gem 'omniauth-github'
(You can see sample from here.)
$ bundle install
$ vi ~/.bashrc
export GITHUB_KEY="<Client ID>" export GITHUB_SECRET="<Client Secret>"
$ 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.)
$ rails g model user provider:string uid:string screen_name:string name:string $ rake db:migrate
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.)
$ rails g controller welcome index $ rails g controller sessions
$ vi config/routes.rb
get 'welcome/index' ... root 'welcome#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.)
You can check the configuration result from the following command.
$ rake routes
$ vi app/controller/application_controller.rb
class ApplicationController < 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.)
$ 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.)
$ vi app/view/layout/application.rb
<% if current_user %> <%= current_user.name %> <%= link_to 'Logout', logout_path %> <% else %> <%= link_to 'Login', '/auth/github' %> <% end %>
S.Yatsuzuka