简体   繁体   English

CanCanCan不会阻止对用户索引页面的访问

[英]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 我想阻止未登录的用户使用CanCanCan访问URL

http://localhost:3000/users HTTP://本地主机:3000 /用户

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. CanCanCan可以工作并且停止访问控制器中的其他操作,只是不用于索引。

In my users controller I was missing 在我的用户控制器中,我不见了

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

This was allowing the guest user to access the page. 这允许来宾用户访问页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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