繁体   English   中英

Devise自定义策略要求首次使用新用户登录两次才能使用该应用程序

[英]Devise Custom Strategy Requires a New User Login Twice for the First Time to Use the Application

我基本上是在遵循https://github.com/mattconnolly/devise-custom-strategy-demo/blob/master/lib/my_authentication.rb

一切正常,但是有一个错误,如果我是我的应用程序新用户(当然,我的用户信息已经在我们的中央身份验证服务器中),我必须首次登录两次才能使用该应用程序

和我的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

在我的User模型中:

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

如您所见,我根本没有使用database_authenticatable ,但是我们需要将一些用户信息从中央服务器保存到我们的应用程序服务器。

我猜是因为:

    user = klass.find_or_initialize_by_email(username)

    puts "user: #{user.inspect}"

    success! user

但我不知道如何修改它,因此新用户不必登录两次即可使用该应用程序。

我自己弄清楚了。 success! user之前success! user success! user ,添加:

    if (user.new_record?)
      user.save
      puts "new user saved ******"
    end

最近,我遇到了这个问题,并通过更换解决它find_or_initialize_by_emailfind_or_create_by_email

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM