首页 > 解决方案 > 设计 SessionsController#create:覆盖默认登录策略

问题描述

这是我的问题:

我目前有两条路线允许用户登录:

我想根据组合路由/用户角色限制登录策略:

我试过的

class Users::SessionsController < Devise::SessionsController
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message!(:notice, :signed_in)
    if !resource.admin?
      # Normal authentication strategy
      sign_in(:user, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    else
      # custom strategy
      flash[:info] = t('not_authorized')
      respond_with resource, location: root_path
    end
  end
end

此时,当一个admin尝试通过“正常”路由登录时,他们看到一个带有错误的闪烁,他们被重定向到根目录但他们仍然登录

在 Devise 的 GitHub 上检查问题后,似乎prepend_before_action :allow_params_authentication!inSessionsController导致身份验证策略再次运行。在此处查看已知问题此提交关闭了问题。但这要到 Devise 的第 5 版才会发布。

到目前为止,我所做的是sign_out在我的警报 + 重定向之前添加一个。

class Users::SessionsController < Devise::SessionsController
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message!(:notice, :signed_in)
    if !resource.admin?
      # Normal authentication strategy
      sign_in(:user, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    else
      # custom strategy
      sign_out
      flash[:info] = t('not_authorized')
      respond_with resource, location: root_path
    end
  end
end

这工作正常。admin但是我对必须即时登录和注销的事实感到不满。它也弄乱了sign_in_count我的用户。

有没有人遇到过类似的问题?你是如何解决这个问题的?

标签: ruby-on-railsdevise

解决方案


推荐阅读