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



问题:用户首次注册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后向用户发送确认的正确方式。

问题

看起来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. 将"查找或创建"逻辑的"创建"部分移到控制器中,这样电子邮件就可以作为"创建"路径的一部分发送

除此之外

此外,我建议使用Deviseresource.send_confirmation_instructions功能,并将您的电子邮件从中提取出来。这样,所有欢迎电子邮件都共享相同的代码,并且您不会只为Facebook/OAuth登录维护单独的模块。

最新更新