SleeplessFox
SleeplessFox

Reputation: 183

Rails CANCAN - No Access on first click

I have some trouble with Rails 4 and CanCan. I did all like described here https://github.com/ryanb/cancan and actually it works but I have following problem:

Sometimes when I click on a link in the navi e.g. "Employee" to open the Employee/Show page CanCan fires an alert:

"...employee/?alert=You+are+not+authorized+to+access+this+page"

and I will redirected to the main page.

When I click again on the same link then page will open. No access problems now...

I dont know what the reason for this problem is... :(

I hope somebody can help.

Some Code:

ability.rb

def initialize(user)

    if user.admin?
      can :manage, :all

    elsif user.secretary?
      can :manage, :all       

      cannot [:destroy],[Employee, Setting, Section, Role, Position]

    elsif user.leader? 
      can :manage, :all

      cannot [:manage],[Setting, Section, Role, Position]
      cannot [:destroy],[Project, Customer, Distributor]
      cannot [:destroy, :edit],[Employee]


    elsif user.employee?
      can :manage, :all

      cannot [:manage],[Setting, Section, Role, Position, Employee, Customer, Distributor]
      cannot [:destroy, :edit],[Project]

    else
      #can :read, :all
    end
end

employees_controller.rb

class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
#before_action :set_tmpPswVar, only: [:show]

#CanCan
load_and_authorize_resource

...

application_controller.rb

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
include SessionsHelper
before_action :require_login
protect_from_forgery with: :exception

#load_and_authorize_resource
#CanCan
skip_authorization_check

#for CanCan version necessary because is not optimized for rails 4
#without that eacht create method will generate an ForbiddenAttributeError!
 before_filter do
    resource = controller_name.singularize.to_sym
   method = "#{resource}_params"
   params[resource] &&= send(method) if respond_to?(method, true)
 end


 #CANCAN
 rescue_from CanCan::AccessDenied do |exception|
   redirect_to :controller=>"workdays", :action => "index", :alert =>    exception.message
 end

 ...

Best regards Kumaro

Upvotes: 1

Views: 64

Answers (1)

Sean Huber
Sean Huber

Reputation: 3985

Unfortunately CanCan does not support Rails 4+. You should instead use CanCanCan:

https://github.com/CanCanCommunity/cancancan

Upvotes: 3

Related Questions