smallseo.info

cancan

Authorization Gem for Ruby on Rails.

How can I test CanCan in the console?

I need to check :read? on an object in the console, how can I do this?


Source: (StackOverflow)

CanCan gem for MVC .NET

I am looking for NuGet package that provides similar functionality as the CanCan gem in rails ( https://github.com/ryanb/cancan ).

Does anyone know a plugin that provides a similar functionality? Or a simple way to implement this?

Thanks


Source: (StackOverflow)

Testing views that use CanCan and Devise with RSpec

I was trying to test a simple index view, which has following code inside:

- if can? :destroy, MyModel
  %th Options

MyModelsController has following options (Inherited Resources + CanCan + Devise):

class MyModelsController < ApplicationController
  inherit_resources
  nested_belongs_to :mymodel
  before_filter :authenticate_user!
  load_and_authorize_resource :project
  load_and_authorize_resource :mymodel, :through => :project

When running specs, it crashes at the line - if can? :destroy, MyModel

Failure/Error: render
   ActionView::Template::Error:
      undefined method `authenticate' for nil:NilClass

There's no traceback, nothing to base on...

I thought that maybe I'm not authorized and signed when testing views, but Devise::TestHelpers should only be included in controller tests (and that's how I have it).

I was trying to override method can? in both Ability and the controller, but that gave no effect.


Source: (StackOverflow)

CanCan: limiting a user's ability to set certain model attributes based on their role

I have a Post model with a :published attribute (boolean) and a User model with a role attribute (string). There are three roles: ROLES = %w[admin publisher author]

I don't want users whose role is author to be capable of setting, or editing, the :published field on the Post model.

I'm using CanCan (and RailsAdmin gem) and my simplified Ability.rb file looks like this:

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new

    if user.role? :admin
      can :manage, :all
    elsif user.role? :publisher
      can :manage, Post
    elsif user.role? :author
      # I want to prevent these guys from setting the :published attribute
    end

  end
end

Anyone got any tips for doing this sort of thing?


Source: (StackOverflow)

CanCan load_and_authorize_resource triggers Forbidden Attributes

I have a standard RESTful controller that uses strong parameters.

class UsersController < ApplicationController
  respond_to :html, :js

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def edit
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(safe_params)

    if @user.save
      redirect_to @user, notice: t('users.controller.create.success')
    else
      render :new
    end
  end

  def update
    @user = User.find(params[:id])

    if @user.update_attributes(safe_params)
      redirect_to @user, notice: t('users.controller.update.success')
    else
      render :edit
    end
  end

  def destroy
    @user = User.find(params[:id])

    if current_user != @user
      @user.destroy
    else
      flash[:error] = t('users.controller.destroy.prevent_self_destroy')
    end
    redirect_to users_url
  end

  private

  def safe_params
    safe_attributes =
      [
        :first_name,
        :last_name,
        :email,
        :password,
        :password_confirmation,
      ]
    if current_user.is?(:admin)
      safe_attributes += [:role_ids]
    end
    params.require(:user).permit(*safe_attributes)
  end
end

In my config/initializers I have the file strong_parameters.rb

ActiveRecord::Base.send(:include,  ActiveModel::ForbiddenAttributesProtection)

When I add a simple call to CanCan's load_and_authorize_resource I get

1) UsersController POST create with invalid params re-renders the 'new' template
 Failure/Error: post :create, user: @attr
 ActiveModel::ForbiddenAttributes:
   ActiveModel::ForbiddenAttributes
 # ./spec/controllers/users_controller_spec.rb:128:in `block (4 levels) in <top (required)>'

Where @attr in the test is defined as

  before(:each) do
    @attr =
      {
        first_name: "John",
        last_name: "Doe",
        email: "user@example.com",
        password: "foobar",
        password_confirmation: "foobar"
      }
  end

In the tests I have it all setup properly to login the user and give them the necessary roles for being an administrator so I know it's not that. I don't know why this is causing ForbiddenAttributes to trigger. I'm sure it's something simple I've overlooked. Has anyone else encountered this problem and found a solution to it?


Source: (StackOverflow)

Context aware authorization using CanCan

I want to use CanCan to handle my permissions. My site has many different permissions levels, and most of them are context aware. For instance, Here are the relations in my 3 main models:

class User < ActiveRecord::Base
  has_many :league_relations
  has_many :leagues, :through => :league_relations
end

class League < ActiveRecord::Base
  has_many :league_relations
  has_many :users, :through => :league_relations
end

class LeagueRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :league
end

Note, LeagueRelations is a nested resource of Leagues. What I want to do is allow a user to modify leagues, and gauge each user's authorization based off of data stored in league_relation. I would then like a user to modify league relation, based only the data stored in the user model.

To be succinct: I basically want LeagueRelations to be used to authorize League actions, and Users to be used to authorize LeagueRelations actions. i.e. league_relation.owner = true to delete a League, but user.owner? must be true to delete a LeagueRelation. How can I authorize based on the attributes of league_relation when inside the league controller, and authorize other actions in other controllers on other models. Please leave a comment if you need more clarification.

Thanks.


Source: (StackOverflow)

Rails4 authorization strategies

When it comes to Authorization/Authentication devise + cancan are usually my gems of choice. After the release of Rails4's strong parameters I've been looking into using the cancan_strong_parameters gem.

I can't shake the feeling that this approach seems a bit 'hacky'. The other options seems to be TheRole gem or simply rolling my own auth from scratch.

Was hoping anyone with first hand experience here could give a few pointers on how they tackled the problem, what problems the faced and where each approach fell short (if anywhere).

I know this isn't a clean cut StackOverflow typed question, but there doesn't seem to be much info regarding this subject when Googling. Thanks.


Source: (StackOverflow)

Is it possible to use cancan with two ability class

I'm using rails 3.0.9, cancan 1.6.7 and devise 1.4.8

I'm using two devise models(User and Admin) for different log-in and registration process

So I want to divide the abilities depend upon the logged-in user(resource), because there are more than 70 models and only 10 models are common for both type of users(here more than 50 models and views are only used by Admin users)

I want to implement two Ability class(UserAbility and AdminAbility) and the devise helper method current_user/current_admin should be passed to UserAbility/AdminAbility

Example:

In ApplicationController.rb file

    def current_ability
        if current_user
            @current_ability = UserAbility.new(current_user)
        elsif current_admin
            @current_ability = AdminAbility.new(current_admin)
        end
    end

From the above my questions,

  1. Is multiple ability class is possible in cancan, if possible then how to create it because I tried

    rails g cancan:user_ability

    but I got error as Could not find generator cancan:user_ability.

  2. How to choose the appropriate Ability class for the logged-in User/Admin.

  3. If a controller is accessed by both the User and Admin, then how can I get the currently logged-in User/Admin's object

Is there any other solution for this?

Any one please help to solve this


Source: (StackOverflow)

How to access 'can?' method from within cell?

I'm using cancan and cells gems in my ruby-on-rails project. How to access can? method from within cell? Thanks.


Source: (StackOverflow)

How to create the first (Admin) user (CanCan and Devise)?

I made authentication in my Rails 3 app fallowed by Tony's tutorial

I don't want public registrations on my app, just to create new users with Admin account, but I can't create Admin account manually, because in table Users there is encrypted password and salt that must to be generated, and I don't know how :|


Source: (StackOverflow)

Access CanCan's `can?` method from a model

You can get the current_user's permissions from a view or controller using can? in this fashion:

  <% if can? :update, @article %>
    <%= link_to "Edit", edit_article_path(@article) %>
  <% end %>

How can I access this functionality from a model using this syntax:

user.can?(:update, @article)

Source: (StackOverflow)

How to do integration testing with RSpec and Devise/CanCan?

If I have a Devise model User, of which only those users with role :admin are allowed to view a certain url, how can I write an RSpec integration test to check that the status returns 200 for that url?

def login(user)
  post user_session_path, :email => user.email, :password => 'password'
end

This was pseudo-suggested in the answer to this question: Stubbing authentication in request spec, but I can't for the life of me get it to work with devise. CanCan is receiving a nil User when checking Ability, which doesn't have the correct permissions, naturally.

There's no access to the controller in integration specs, so I can't stub current_user, but I'd like to do something like this.

describe "GET /users" do
  it "should be able to get" do
    clear_users_and_add_admin #does what it says...
    login(admin)
    get users_path
    response.status.should be(200)
  end
end

NOTE!!!: all this has changed since the question was asked. The current best way to do this is here: http://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara


Source: (StackOverflow)

Cancan accessible_by

What exactly is happening when I do:

@patient.course_enrollments.accessible_by(current_ability)

What seems to happen is I get course_enrollments where course.client_id = user.client.id, I just don't understand how accessible_by works.

# ability.rb
can :manage, CourseEnrollment, :course => {:client_id => user.client.id}

Source: (StackOverflow)

Passing params to CanCan in RoR

I have a controller with a method like;

def show

    if params[:format].eql?("pdf")
    // do something
    elsif params[:format].eql?("csv")
    // do something
    end
end

But i have users with different roles. So i use CanCan to manage access control. Now i want X role can do the action show in controller iff params[:format].eql?("csv")

I think it can be like ;can :show, resource if params[:format].eql?("csv"). So how can i send parameters to ability.rb?

Any idea?

Thanks.


Source: (StackOverflow)

cancan: the difference between "manage" and the combination of "read, create, update and destroy"?

In trying to debug use of cancan i found that if use the following i can get past the accessdenied message:

  can :manage, Model

When i changed it to the following I am denied access:

  can :read, Model
  can :create, Model
  can :update, Model
  can :destroy, Model

What does manage include that the combination of read, create, update and destroy do not?

Thanks.


Source: (StackOverflow)