关于简单授权的问题
我正在使用 Devise 进行身份验证,我只需要对几个控制器进行简单的管理或使用检查。我是 Rails 新手,所以我正在尝试以正确的方式做到这一点。我基本上已经向用户模型添加了一个布尔管理字段并添加了此方法
def is_admin?
admin == 1
end
然后我只需将控制器操作修改为此
def new
if current_user.nil? || !current_user.is_admin?
flash[:notice] = "You do not have permission to view this page"
redirect_to "/gyms"
else
@gym = Gym.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @gym }
end
end
end
所以此解决方案有效,但我应该以不同的方式执行此操作吗?
I am using Devise for authentication, and I only need a simple admin or use check for a few controllers. I'm new to rails, so I'm trying to do this the right way. I've basically added a boolean admin field to the user model and added this method
def is_admin?
admin == 1
end
Then I simply modified the controller action to this
def new
if current_user.nil? || !current_user.is_admin?
flash[:notice] = "You do not have permission to view this page"
redirect_to "/gyms"
else
@gym = Gym.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @gym }
end
end
end
So this solution works, but should I be doing this a different way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这会起作用,但除了小规模项目之外,我可能不会推荐此解决方案。随着时间的推移,如果您在控制器中执行授权检查,您的代码将变得臃肿且难以管理。
相反,我会考虑使用授权模块,例如 Cancan ,它将您的授权规则集中在一个地方,从而将您的授权规则解耦。应用程序逻辑来自您的授权逻辑。最终结果是更干净且更易于维护的代码。
使用 Cancan 后,您的代码可能如下所示:
This will work but I probably would not recommend this solution for anything else than a small scale project. Over time, if you perform authorization checks within your controllers, your code is going to become bloated and difficult to manage.
Instead I would consider using an authorization module such as Cancan which centralizes your authorization rules in one place and thus decouples your application logic from your authorization logic. The end result is cleaner and more maintainable code.
With Cancan in place, your code might look like this: