Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

cancan
ruby

How to ensure authorization in CanCan

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

CanCan is an authorization library for Ruby on Rails that defines the authorization of specific resources for multiple users.

If there is an instance where you want to ensure that a certain authorization is not forgotten, you can append the add check_authorization to the ApplicationController.

class ApplicationController < ActionController::Base
  check_authorization
end

This will ensure that authorization takes place in every inherited controller action. If not, the following exception will be raised.

CanCan::AuthorizationNotPerformed

We can modify the permissions so that it is skipped on new objects using skip_authorization_check. This authorization can be skipped using :only, which only skips the properties stated, and :except, which skips all the properties except the ones stated. The following code skips the authorization check for newly created objects:

class ApplicationController < ActionController::Base
  skip_authorization_check :only =>[:new] 
end

Conditional Check

CanCan1.6 allows you to conditionally check authorizations when given a method. This is done by using the keyword :if and :unless. Here is an example that allows access to a user who is tagged as admin:

class ApplicationController < ActionController::Base
  check_authorization :if => :admin?
  private
  def admin?
    request.subdomain == "admin"
  end
end

Note:check_authorization only ensures that the authorization is performed.

RELATED TAGS

cancan
ruby
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring