简体   繁体   中英

CanCanCan is not blocking access for users index page

I want to stop users who aren't logged in from accessing the URL using CanCanCan

http://localhost:3000/users

My Ability model is

class Ability
include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin?
      can :manage, :all
    elsif user.roles.size > 0
      can :manage, User, :id => user.id
    else
      can :read, :all
      cannot :read, :User
    end
  end
end

And my Users controller is

class UsersController < ApplicationController
  load_and_authorize_resource

  def index
    @users = User.paginate(page: params[:page],:per_page => 5)
  end

  def new
    # @user = User.new
  end

  ...
end

When I access the page as an guest user. I see the users index page instead of being redirected to login by this code in my application controller

rescue_from CanCan::AccessDenied do |exception|
  if user_signed_in?
    flash[:error] = "Access denied!"
    redirect_to root_url
  else
    flash[:error] = "Please Sign in"
    redirect_to new_user_session_path
  end
end

CanCanCan works and stops access to the other actions in the controller just not for index.

In my users controller I was missing

before_filter :authenticate_user!, :except => [:new, :create]

This was allowing the guest user to access the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM