fl00r
fl00r

Reputation: 83680

Authlogic and OpenID registration and login in one action

I was playing with Rayan Bates http://railscasts.com/episodes/170-openid-with-authlogic sources as the basis.

So I created few icons for OpenID providers, like Google, Yandex, OpenID, and user have to choose which one to use (similar like here on stackoverflow). So everything is fine. Now I decide to make only one click for login or register: when user click on icon Authlogic have to create new user and authenticate him, or, if user exists, just authenticate him. So I tied to change logic in User#create:

class UsersController < ApplicationController      
  def create
    @user = User.new(params[:user])
    @user.save do |result|
      if result
        redirect_to root_url
      else
        @user_session = UserSession.new(:openid_identifier => @user.openid_identifier)
        @user_session.save
        redirect_to root_url
      end
    end
  end
end

So, if user can't be saved Authlogic will try to authenticate him (of course, user can't be saved not only if there exists another user with same openid_identifier, but just for example). But these scheme isn't work. Nothing happened, @user_session.save return nothing in this case.

Upd

Looking into Shripad K link sources (http://github.com/shripadk/authlogic_openid_selector_example/blob/master/app/models/user_session.rb) I've catch out this:

class UserSession < Authlogic::Session::Base
  auto_register
end

auto_register is all I need

Upvotes: 2

Views: 214

Answers (2)

Shripad Krishna
Shripad Krishna

Reputation: 10498

Rather than reinvent the wheel you can give this a try: http://github.com/shripadk/authlogic_openid_selector_example

Live example app: http://testingauth.heroku.com/

Upvotes: 1

fl00r
fl00r

Reputation: 83680

Ehm. As I can't redirect POST to user_sessions create action, so I've made hack like this:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    @user.save do |result|
      if result
        redirect_to root_url
      else
        if User.find_by_openid_identifier(@user.openid_identifier)
          redirect_to :action => 'login', "user_session[openid_identifier]" => @user.openid_identifier
        else
          render :action => "new"
        end
      end
    end
  end

  def login
    @user_session = UserSession.new(params[:user_session])
    @user_session.save do |result|
      if result
        redirect_to root_url
      else
        render :action => 'new'
      end
    end    
  end
end

Upvotes: 0

Related Questions