Rails Devise限制管理员用户的IP地址访问 [英] Rails Devise restrict IP address access for admin users

查看:97
本文介绍了Rails Devise限制管理员用户的IP地址访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目使用Devise进行身份验证(相当标准)。用户可以是普通用户也可以是管理员用户。

My project uses Devise for authentication (fairly standard). Users can be either normal users or administrator users.

我现在需要将管理员用户的登录限制为某些IP地址(在防火墙后)。

I now have a requirement to restrict login for administrator users to some IP addresses (behind the firewall).

我曾简要考虑过使用Rails路由约束,但这并不适用,因为普通用户和管理员用户都是通过同一登录页面登录的。

I briefly considered to use a Rails routing constraint, but this is not applicable, since ordinary users and admin users log in through the same login page.

所以,我想要的是:


  1. 让设计句柄身份验证

  2. 进入验证周期并验证管理员:

  3. 如果登录用户的类型为:管理员,则验证IP地址

  4. 如果有效IP,则继续

  5. 如果IP地址不在可接受的范围内,则不要登录

  1. let Devise handle authentication
  2. hook into the authentication cycle and verify administrators:
  3. If logged in user is of type: administrator, then verify IP address
  4. If valid IP, then continue
  5. If IP address is not within accepted range, then don't login

如何我应该在这里进入Devise登录周期吗?以及如何根据我的自定义验证接受或拒绝登录尝试?

How should I hook into the Devise login cycle here? And how do I either accept or reject the login attempt based on my custom validation?

我正在使用Rails 4.2并设计4.1(如果相关)

I am using Rails 4.2 and devise 4.1 if that is relevant

推荐答案

请勿为此使用Devise。让他们以用户或管理员身份登录-仅基于其IP地址访问某些控制器。如果他们没有访问权限,请重定向。

Don't use Devise for this. Let them log in, user or admin - just base access to certain controllers on their ip address. Redirect if they don't have access.

创建一个管理名称空间和基本控制器。您可以轻松地将其添加到路由。

Make an admin namespace and base controller. You can add this to routes easily. Subclass all other admin related controllers from the admin base controller so they inherit the before action.

class Admin::BaseController > ApplicationController
  before_action require_valid_ip

  def require_valid_ip
    # Test for IP.  Redirect if bad
  end 

end

从BaseController继承而来

Other classes would be subclassed from the BaseController

class Admin::OtherController > Admin::BaseController


  ...
end

您也可以将很多这样的内容放到CanCan之类的Authorization瑰宝中,尽管如果您的需求很简单,也可能会过于复杂。

You can also put a lot of this in an Authorization gem like CanCan, though that can also be overly complicated if your needs are simple.

这篇关于Rails Devise限制管理员用户的IP地址访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆