ruby-on-rails - 设计 SessionsController#create:覆盖默认登录策略
问题描述
这是我的问题:
我目前有两条路线允许用户登录:
- 管理员路由:
host/admin/sign_in
适用于具有该admin
角色的用户 - “正常”路线:
host/users/sign_in
对于没有admin
角色的用户
我想根据组合路由/用户角色限制登录策略:
- 无法
admin
通过正常路径登录host/users/sign_in
- 普通用户无法通过管理员路由登录
host/admin/sign_in
我试过的
- 我已经生成了设计
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
我的用户。
有没有人遇到过类似的问题?你是如何解决这个问题的?
解决方案
推荐阅读
- python - Python 视频处理
- jquery - 关注不适用于 Bootstrap 4 的标签元素
- algorithm - 通过用“1”替换任何一个“0”来查找二进制数组中最长的“1”序列
- python - For循环 - 运行1个循环完成然后运行下一个循环python
- php - 正则表达式 - 获取双方括号之间的文本
- node.js - Electron App Loops 在 Windows 上重新启动
- java - Google Home 对话流代理认证错误
- android - 如何在android 7.1版中清除缓存
- python-3.x - gcp:datastore - 使用 Python API 获取总体状态 __Stat_Total__
- swift - 上传到 App Store 时上传失败 ERROR ITMS-90081