I’m basically following https://github.com/mattconnolly/devise-custom-strategy-demo/blob/master/lib/my_authentication.rb
Everything works well, but there is one bug, if I’m a new user to my application (of course my user info is already in our central authentication server), I have to login twice for the first time to use the application
And my authenticate!:
def authenticate!
# mapping comes from devise base class, "mapping.to" is the class of the model
# being used for authentication, typically the class "User". This is set by using
# the `devise` class method in that model
klass = mapping.to
# login credentials
username = params[:user][:email] # The username is the email field
password = params[:user][:password]
begin
# Here is the code to authenticate
# Basically, we are sending the credentials to another central authentication server
# If the authentication fails, it will throw an exception, which will be caught below to fail!
user = klass.find_or_initialize_by_email(username)
puts "user: #{user.inspect}"
success! user
rescue Exception => e
failureMessage = "Auth error: #{e.inspect}"
puts "#{failureMessage}"
fail! failureMessage
end
# if we wanted to stop other strategies from authenticating the user
end
And in my User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :my_authentication,
:rememberable, :trackable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :first_name, :last_name, :remember_me, :email
end
As you can see that I’m not using database_authenticatable at all, but we need to save some user info from the central server to our application server.
I’m guessing it’s because of:
user = klass.find_or_initialize_by_email(username)
puts "user: #{user.inspect}"
success! user
but I don’t know how to modify it, so that a new user does NOT have to login twice to use the application.
I just figured it out myself. Before
success! user, add: