代码之家  ›  专栏  ›  技术社区  ›  pyfl88

如何在rails中生成类似确认页面的临时页面?

  •  3
  • pyfl88  · 技术社区  · 9 年前

    我正在使用device,并希望在注册时将用户重定向到确认页面,这就是我现在正在做的:

    用户/registrations_controller.html.erb

    class Users::RegistrationsController < Devise::RegistrationsController
    
     def confirm_email
     end
    
     private
    
     def after_inactive_sign_up_path_for(resource)
      users_confirmyouremail_path
     end
    end
    

    配置/路由.rb

    devise_scope :user do     
      get 'users/confirmyouremail' => 'users/registrations#confirm_email' 
    end
    

    我在注册后重定向页面没有问题。然而,我认为任何人都可以访问带有类似“host”的url的页面,这很奇怪。com/confirmyouremail”并查看确认页面。有什么方法可以让我写一条只允许一次访问的随机代码的路线吗?提前谢谢。

    1 回复  |  直到 9 年前
        1
  •  4
  •   Chris    9 年前

    可能是这样的:

    before_action :authenticate_user!
    
    def confirm_mail
        redirect_to root_path if current_user.confirmed
    ...
    end
    

    如果用户已确认其帐户,则将存储在数据库中。如果他的帐户被确认,那么他将无法访问此页面。你可以重定向到你想要的任何页面。由于之前的操作,没有任何帐户的用户将无法访问此页面

    如果用户在访问此confirm_mail页面时未登录,则有不同的可能性。您可以使用会话或cookie:

    # after sign up:
    session[:confirm] = true
    # alternatively a cookie
    cookies[:confirm] = true
    

    然后在确认邮件操作中:

    def confirm_mail
      if session[:confirm].blank? # or cookies[:confirm].blank?
        redirect_to root_path
      end
    
      # otherwise delete the field from the session
      session.delete(:confirm)
      # alternatively the cookie
      cookies.delete(:confirm)
    end
    

    另一种方法是使用令牌。创建一个新模型,如 ConfirmMailToken 。然后在注册时,您创建一个新令牌,并将用户重定向到确认页面,该令牌作为URL参数。然后在confirm_mail操作中,检查令牌是否可用,如果可用,则将其删除。这样可以确保页面仅在重定向后显示。