User Profile authorization with cancan
I have an app using Devise, Rolify and Cancan.
Right now its only setup to differentiate between admin and user to prevent access to the user index, and admin portions of the site.
My problem is that right no a user can access other user profiles and this should no be the case. For example, if i am logged in at ....user/2 I can just change my url and see user/1. How do i block this?
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.has_role? :admin can :manage, :all can :access, :rails_admin can :dashboard else can :manage, Profile, :user_id => user.id end end end
class ApplicationController < ActionController::Base protect_from_forgery rescue_from CanCan::AccessDenied do |exception| redirect_to root_path, :alert => exception.message end
class Role < ActiveRecord::Base has_and_belongs_to_many :users, :join_table => :users_roles belongs_to :resource, :polymorphic => true end
You will have to check the abilities in the controller, and according to the CanCan docs this can be done by putting this at the top of your controller: load_and_authorize_resource
This should restrict users from peeking at other profiles, as it looks like you already defined your abilities to restrict viewing to only one's profile.
Refer to the CanCan wiki for more information: https://github.com/ryanb/cancan/wiki