I am working on adding authorizations to an app I am building and I have a question. I have added an :admin column to my User table and set it as a boolean. In my controller I have added this code:
class ShipsController < ApplicationController
def index
ships = Ship.all
@ships = ships.sort_by { |v| [v[:empire_image], v[:cost]] }
if current_user.admin == true
respond_to do |format|
format.html # index.html.erb
format.json { render json: @ships }
end
else
respond_to do |format|
format.html { redirect_to root_path }
end
end
end
It looks like I will have to add this to all of my actions and this seems wrong. My question is, is doing it this way insecure or just more work for myself but fine.
Also I am using the authentication from railstutorial.org and am wondering if a library like cancan would work well with that.
Thanks for your time,
Nick
This way is not insecure, it’s just clutter your controllers, at least consider to use a before_filter to authorize your actions.
Maybe for a simple application use a 3rd party authorization gem could seems overkill but move the authorization rules in a single place is a very good thing (the
ability.rbfile in the case of CanCan).You can use CanCan with that authentication system, CanCan just expects a
current_usermethod to exist in the controller.