OpenIDを使ったユーザ認証の実験

ruby-openidを使ってみることに.

% ruby script/generate openid_login openid
      create  lib/openid_login_system.rb
      create  app/controllers/openid_controller.rb
      create  test/functional/openid_controller_test.rb
      create  app/helpers/openid_helper.rb
      create  app/models/user.rb
      create  test/unit/user_test.rb
      create  test/fixtures/users.yml
      create  app/views/layouts/scaffold.rhtml
No such file or directory - /var/lib/gems/1.8/gems/rails-2.1.0/lib/rails_generator/generators/components/scaffold/templates/layout.rhtml

と,なんかファイルがないと言われる.なんか気持ち悪いので,他を調べて,open_id_authentication を使ってみることに.

% ruby script/plugin install open_id_authentication
% rake open_id_authentication:db:create
(in /home/path/to/project)
      create  db/migrate
      create  db/migrate/20080729125249_add_open_id_authentication_tables.rb
% rake db:migrate
% ruby script/generate controller sessions
  • config/routes.rb
map.open_id_complete 'session', :controller => 'sessions', :action => 'create', :requirements => {:method => :get}
map.resource :session
  • app/controller/sessions_controller.rb
class SessionsController < ApplicationController
  def index
  end

  def create
    if using_open_id?
      open_id_authentication
    else
      #password_authentication(params[:name], params[:password])
      redirect_to :action => "index"
    end
  end

  protected
  def open_id_authentication
    authenticate_with_open_id do |result, identity_url|
      if result.successful?
  successful_login identity_url
      else
        failed_login result.message
      end
    end
  end

  private
  def successful_login(identity_url)
    session[:user_id] = identity_url
    flash[:notice] = "login successful.(#{session[:user_id]})"
    redirect_to :action => "index"
  end

  def failed_login(message)
    flash[:error] = message
    redirect_to :action => "index"
  end
end
  • app/views/sessions/new.html.erb
<% form_tag(session_url) do %>
  <p>
    <label for="openid_url">OpenID:</label>
    <%= text_field_tag "openid_url" -%>

    <%= submit_tag 'Sign in', :disable_with => "Signing in&hellip;" %>
  </p>
<% end %>
  • app/views/sessions/index.html.erb
<% if flash[:error] -%>
  <%= flash[:error] %>
<% end -%>
<% if flash[:notice] -%>
  <%= flash[:notice] %>
<% end -%>

<%= link_to "login", :action => "new" -%>

とりあえず動くところまでできた.次はユーザ管理とパスワード認証かな.

###参考

 
comments powered by Disqus