Question about simple authorization
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?
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:
# app/controllers/gyms_controller.rb
class GymsController < ApplicationController
load_and_autorize_resource
def new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @gym }
end
end
end
end
# app/models/Ability.rb
can :create, Gym do |trip|
user.is_admin?
end
精彩评论