在 actionmailer 中设计身份验证

devise authentication inside actionmailer

我想 sign_in 我的用户在我的 UserMailer 中使用设计:

期望的行为:

class UserMailer < ActionMailer::Base

  # need to include devise somehow

  def show_preview(user)
    sign_in(:user, user)
    response = RestClient.get 'http://localhost:3000/api/posts.json' #this needs authentication
    # email_body = format response ... ...
  end

end

问题:我不知道我需要在我的 UserMailer 中包含哪些设计部分,以及如何包含它们。

我试过 include Devise::Controllers::InternalHelpers(为了使用 sign_in),来自 this link,但它似乎已被弃用。

原因: 因为我想在发送给用户的电子邮件中包含与我在网络应用程序上向用户显示的相同的数据。因此,我想访问相同的 api(即 localhost:3000/api/posts.json,这是我用于我的 controlle/view 的内容,它要求用户经过身份验证。

您可以在调用邮件程序方法之前向 api 发出请求,并将数据作为参数传递。

您的控制器操作可能看起来像这样

def my_action
  response = RestClient.get 'http://localhost:3000/api/posts.json'
  UserMailer.show_preview(current_user, response)
  #render or redirect as needed
end

你的邮件可能看起来像这样

class UserMailer < ActionMailer::Base

  # need to include devise somehow

  def show_preview(user, data)

    # email_body = format response ... ...
    @email_body = format data #this will make the data available to your view
  end

end

目前我正在使用一种解决方法,它使用 Rabl::Renderer:

class UserMailer < ActionMailer::Base
  class RablScope
    include ApplicationHelper # A way to include applicationHelper in Rabl::Engine
  end

  def show_preview(user)
    # @posts = function of user
    response = JSON.parse( Rabl::Renderer.new('api/posts/show',@posts,view_path: 'app/views', scope: RablScope.new()).render )
    # email_body = format response ... ...
  end
end

缺点是我必须将 api 控制器中的所有 logic/code 复制粘贴到邮件程序中 # @posts = function of user 否则这就足够了。