2012-06-08

railsでgoogleさんのopenidを利用する

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
rails 3.2 + ruby 1.9.3で認証としてgoogleさんのopenidを利用させてもらう例です。

http://yorunocafe.blogspot.jp/2012/02/rails-omniauth.html
を参考にさせていただきました。

omniauthを利用します。


とりあえず最低限の動作をするためのものを作る手順です。

まずはプロジェクトを作成
-Oをつけるとデータベースを使わないプロジェクトを作成できます。
rails new rails_google_openid_sample -O

cd rails_google_openid_sample

public/index.htmlを削除しておきます。

まずは
Gemfile
を以下のようにします。
source 'https://rubygems.org'

gem 'rails', '3.2.3'

gem 'omniauth'
gem 'omniauth-openid'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

bundle install
を実行します。

以下のような
config/initializers/omniauth.rb
を作成します。
require 'omniauth-openid'
require 'openid/store/filesystem'

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :open_id, :store => OpenID::Store::Filesystem.new(Rails.root.join('tmp','openid'))
  provider :open_id, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'
end


とりあえずcontrollerを作成します。
rails g controller welcome index

作成された
app/views/welcome/index.html.erb
を以下のようにします。
<h1>Welcome#index</h1>
<p>Find me in app/views/welcome/index.html.erb</p>
<dif><%= flash.notice %></div>
<div id="user_nav"> 
  <% if current_user %> 
    User Info,
    <pre>
    <%= current_user %>
    </pre>
    <%= link_to "Sign Out", signout_path %> 
  <% else %> 
    <%= link_to "Sign in with Google", "/auth/open_id?openid_url=https://www.google.com/accounts/o8/id" %>
  <% end %> 
</div>

上記で利用しているcurrent_userを処理するため
app/controllers/application_controller.rb
も以下のように変更します。
class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user

  private
  def current_user
    @current_user ||= session[:user_info] if session[:user_info]  
  end
end

openidで受け取った情報を処理するためのcontrollerを作成します。
rails g controller sessions

作成された
app/controllers/sessions_controller.rb
を以下のようにします。
本来ならば、ここのcreateメソッドでユーザを新規登録したり、登録済みユーザを検索したりします。
class SessionsController < ApplicationController

  def create
    auth = request.env["omniauth.auth"]
    session[:user_info] = auth["info"]
    redirect_to root_url, :notice => "Signed in!"
  end

  def destroy
    session[:user_info] = nil
    redirect_to root_url, :notice => "Signed out!"
  end

end

routeの設定をします。
config/routes.rb
RailsGoogleOpenidSample::Application.routes.draw do
  get "welcome/index"

  root :to => 'welcome#index'

  match "/auth/:provider/callback" => "sessions#create"
  match "/signout" => "sessions#destroy", :as => :signout
end

これでOKです、
rails s

http://localhost:3000
に接続して試してみてください。

この手順で作成したものを以下においておきました。
https://github.com/vivahiraj/rails_google_openid_sample

0 件のコメント: