Pundit与Rails加用户,管理员和角色模型 [英] Pundit with Rails plus User, Admin and Roles Models

查看:400
本文介绍了Pundit与Rails加用户,管理员和角色模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails_admin:我应该有admin_user或管理员角色的用户来管理用户和管理面板我想要采用 Pundit 为其应用程序的政策优雅。该应用程序具有用户模型和管理模式 - 一个用于客户,另一个用于员工。它也是多租的,虽然这不应该非常影响的问题。

Following on from Rails_admin: Should I have admin_user or user with admin role to manage users and admin panel I'm wanting to adopt Pundit for its policy elegance for an application. The application has both a User model and an Admin model - one for customers, the other for staff. It is also multi-tenanted, though that should not impact the problem terribly.

我也想要一个单独的角色模型,允许客户混合 - 根据需要匹配自己的标题作为角色。实际上这不应该是非常困难的。

I'd also like to have a separate Role model, allowing customers to mix-and-match their own "title" for a Role as they need. This again shouldn't be terribly difficult in implementation.

困难的部分是支持Pundit政策来支持两种不同的用户模型 - 用户(客户)和管理员(员工)。

The hard part is the support for the Pundit Policies to support two different user models - the User (Customer) and Admin (Staff).

是否应该使用pundit_user方法将Admin或User设置为pundit_user(基于这些通过current_user的可用性和current_admin_user)还是有另一种方法。我没有在这个用例中找到很多好的文档(除了 github )。

Is it a case that I should be using the pundit_user method to set either the Admin or User as the pundit_user (based on the availability of these through current_user and current_admin_user) or is there another method. I haven't found much good documentation on this use case (other than the short line on github).

def pundit_user
  if !current_admin_user.nil?
    current_admin_user
  elsif !current_user.nil?
    current_user
  else
    nil
  end        
end


推荐答案

在我应用程序的公开访问部分,使用User模型。默认的Pundit配置工作,因为 pundit_user 返回 current_user

In the publicly accesible part of my application, the User model is used. The default Pundit configuration works since pundit_user returns current_user.

在我的应用程序的管理员部分,使用管理员模型。一个原因是管理员可以在模拟用户时保持登录状态(查看他们在个人资料中看到的内容并帮助排除故障)。

In the admin part of my application, the Administrator model is used. One reason for this is that an admin can stay logged in while impersonating a user (to see what they see in their profile and help troubleshoot).

在管理控制器中 pundit_user 返回 current_administrator

在Rails Admin中,当前用户被设置为当前管理员:

In Rails Admin, the current user is set to the current administrator:

config.authenticate_with do
  warden.authenticate! :scope => :administrator
end
config.current_user_method(&:current_administrator)

我不在Rails管理员中使用授权(所有管理员都拥有所有权力),您应该可以使用 rails_admin_pundit gem,因为它是

While I don't use authorization in Rails Admin(all admins have all powers), you should be able to use the rails_admin_pundit gem since it does

@ controller.class.send(:alias_method,:pundit_user,:_current_user)

在Rails Admin中定义的

which is defined in Rails Admin as

def _current_user
  instance_eval(&RailsAdmin::Config.current_user_method)
end

这篇关于Pundit与Rails加用户,管理员和角色模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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