设计添加管理员角色 [英] Devise Add Admin Role

查看:65
本文介绍了设计添加管理员角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在devem gem中创建管理员角色,以及如何制作即使您以管理员身份登录也可以访问的页面,否则将获得404页面。

I wish to know how to create an admin role in devise gem and how to make pages that just if you are logged as admin you could access, otherwise you get a 404 page.

推荐答案

有一种简单的方法可以与您分享。

There is a simplistic way of doing this that I will share with you.

创建一个迁移,添加对您的设计用户来说是布尔值:

Create a migration that adds a boolean to your devise user:

rails g migration AddsAdminColumnToUsers

def change
  add_column :users, :admin, :boolean, default: false, null: false
end

这将映射回您的模型并创建 user.admin?方法。

This will map back to your model and create a user.admin? method.

对于页面访问,我会在 ApplicationController 内创建一个方法,或者更好的方法是将控制器问题称为 AuthenticateAdmin

For the page access I would create a method within ApplicationController or better yet a controller concern called AuthenticateAdmin.

在任一内部,创建一个名为 authenticate_admin!的方法。

Within either, create a method called authenticate_admin!.

def authenticate_admin!
  authenticate_user!
  redirect_to :somewhere, status: :forbidden unless current_user.admin?
end

P.S。如果在 ApplicationController 中,请确保这是受保护的方法

P.S. if within ApplicationController also make sure this is a protected method

然后对于每个需要限制的控制器或操作:

Then for each of your controllers or actions you need to restrict:

before_action :authenticate_admin!, only: [:action] # `only` part if applicable

您要发送禁止

原因超出了此问题的范围,但实际上未找到与没有被授权做某事不同。

The reason is beyond the scope of this question, but essentially Not Found is different than not being authorized to do something.

在HTTP状态代码中,有一个未经身份验证的,但是在这种情况下,我们已经过身份验证,这个人就是

In HTTP status codes, there is an Unauthenticated, but in this case we are authenticated, the person is just forbidden to access the page (i.e. unauthorized).

这种情况要求HTTP状态403禁止。

This case calls for HTTP status 403 Forbidden.

这篇关于设计添加管理员角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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