sRails 5设计after_sign_in_path

时间:2017-07-16 12:00:49

标签: ruby-on-rails ruby devise

我有一个带Devise的Rails 5应用程序。每个用户都有role_id,在创建时会为其分配角色。我尝试使用Devise提供的after_sign_in_path_for方法,根据角色重定向到登录时的特定页面。

以下是我到目前为止的情况,但在尝试退出已停用的用户时,它无法正常工作。

    class ApplicationController < ActionController::Base
   def after_sign_in_path_for(resource)
    case resource.role_id
      when Role.find_by(name: "admin").id
      root_path
      when Role.find_by(name: "disabled").id
      destroy_user_session_path
      else
      super
    end
  end
end

当我是管理员用户并且重定向时,我能够登录。但是,如果我尝试以禁用其角色的用户身份登录,它会尝试拆除会话,然后引发No route matches [GET] "/users/sign_out"的异常。我知道方法destroy_user_session_path需要一个delete方法但是如何在应用程序控制器中传递它?

我在这里做错了什么?

更新

我按照第一个回答中的建议尝试了sign_out(resource),并引发了异常undefined method to_model&#39; for true:TrueClass in my my_sessions_controller.rb`,我用它来覆盖create方法来设置登录令牌并限制并发会话。这是控制器。

class MySessionsController < Devise::SessionsController
  skip_before_action :check_concurrent_session

  def create
    super
    set_login_token
  end

  private
  def set_login_token
    token = Devise.friendly_token
    session[:token] = token
    current_user.login_token = token
    current_user.save(validate: false)
  end
end

3 个答案:

答案 0 :(得分:1)

您可以检查MySessionsController #start内的角色,如果角色无效而不允许用户登录然后注销,则可以阻止日志记录

def create 
 unless current_user.role_id == Role.find_by(name: "disabled").id 
  super set_login_token 
 else 
  redirect_to new_user_session_path, alert: "You can't log in"    
  end 
end

您还可以使用active_for_authentication吗?和用户模型中的inactive_message方法,以防止他登录。在/app/models/user.rb

def active_for_authentication?
 super and self.role_id != Role.find_by(name: "disabled").id 
end

def inactive_message
 "You can't log in"
end

答案 1 :(得分:0)

destroy_user_session_path 正在提出[GET] "/users/sign_out"请求。

您可以使用sign_outreset_session功能直接删除会话。

希望这个答案适合你。

答案 2 :(得分:0)

使用devise的sign_out(resource)方法而不是destroy_user_session_path。此方法将破坏用户会话。