Rails设计在Facebook注册后发送确认电子邮件

时间:2017-02-11 20:26:36

标签: ruby-on-rails facebook devise omniauth mailer

问题:如何在用户首次注册Facebook后向用户发送电子邮件?我正在使用设备和omniauth。

我有确认电子邮件正在使用设计进行定期注册。我需要在用户登录Facebook后第一次将用户添加到我的数据库时发送电子邮件。 代码中的位置发生了什么?

我尝试在omniauth_callbacks_controller中添加一行代码发送电子邮件。

class OmniauthCallbacksController < Devise::OmniauthCallbacksController

# omniauth_callbacks_controller

def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    facebook = "www.facebook.com"

    if @user.persisted?
        print "User persisted"
        sign_in @user, :event => :authentication
        set_flash_message(:notice,:success,:kind => "Facebook") if is_navigational_format?

        # I SENT THE EMAIL HERE

    else
        session["device.facebook_data"] = request.env["omniauth.auth"]
        redirect_to root_path
    end
end

但是,这只会在用户使用Facebook登录时向用户发送确认电子邮件,这不是我想要的。我想在他们第一次登录时发送电子邮件。

电子邮件应该在registrations_controller中发送。但是,当用户注册Facebook时,从不使用此控制器。

class RegistrationsController < Devise::RegistrationsController

def create
build_resource(sign_up_params)
if resource.save
  if resource.active_for_authentication?
    set_flash_message :notice, :signed_up if is_navigational_format?
    sign_up(resource_name, resource)
    # Tell the UserMailer to send a welcome email after save
    UserMailer.welcome_email(current_user).deliver_later
    return render :json => {:success => true}
  else
    set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
    expire_session_data_after_sign_in!
    return render :json => {:success => true}
  end
else
  clean_up_passwords resource
  invalid_signin_attempt
end
end

想知道在注册Facebook后向用户发送确认的正确方法。

1 个答案:

答案 0 :(得分:2)

问题

您的User.from_omniauth功能看起来像find_or_create次呼叫。这意味着控制器不知道用户是刚刚创建的还是从数据库中的现有标识中提取的。

如果用户是作为此from_omniauth调用的一部分创建的,那么您应该只能依赖于Devise :confirmable模块。否则,在您返回OAuth凭据之前会创建用户,因此您需要手动处理它。

from_omniauth函数中的代码可能如下所示:

def self.from_omniauth(token)
  user = User.find(token: token)
  if user.nil?
    user = User.create(token: token, ...)
    # ...
  end
  # ...
end

可能有中间人TokenIdentity或其他此类,但逻辑应该相同。

修复

有两种简单的方法可以解决这个问题:

  1. 包含created布尔值作为from_omniauth返回值的一部分,然后控制器可以使用该布尔值来确认确认电子邮件。
  2. 将“查找或创建”逻辑的“创建”部分移出控制器,以便电子邮件可以作为“创建”路径的一部分发送。
  3. 除了

    另外,我建议使用Devise resource.send_confirmation_instructions功能并将您的电子邮件捎带。这样,所有欢迎电子邮件共享相同的代码,并且您不会仅为Facebook / OAuth登录维护单独的模块。

相关问题