I am installing pundit on my app. My RestaurantPolicy file inherits from the ApplicationPolicy one (which by default gives access to none of the methods). When changing the methods in RestaurantPolicy (from false to true) it seems to have no effect as I still have access to none of the methods. BUT when changing falses to trues in the ApplicationPolicy file...I have the accesses ! Any idea why methods in the RestaurantPolicy file do not override the ApplicationPolicy's ones ? Thank youuu!!
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
include Pundit
# Pundit: white-list approach.
after_action :verify_authorized, except: :index, unless: :skip_pundit?
after_action :verify_policy_scoped, only: :index, unless: :skip_pundit?
private
def skip_pundit?
devise_controller? || params[:controller] =~ /(^(rails_)?admin)|(^pages$)/
end
end
restaurants_controller.rb
class RestaurantsController < ApplicationController
before_action :set_restaurant, only: [:show, :edit, :update, :destroy]
def index
#restaurants = Restaurant.all
authorize #restaurants
end
def show
end
def new
#restaurant = Restaurant.new
authorize #restaurant
end
def edit
end
def create
#restaurant = Restaurant.new(restaurant_params)
#restaurant.user = current_user
# OU : #restaurant = current_user.restaurants.build(restaurant_params)
respond_to do |format|
if #restaurant.save
format.html { redirect_to #restaurant, notice: 'Restaurant was successfully created.' }
format.json { render :show, status: :created, location: #restaurant }
else
format.html { render :new }
format.json { render json: #restaurant.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #restaurant.update(restaurant_params)
format.html { redirect_to #restaurant, notice: 'Restaurant was successfully updated.' }
format.json { render :show, status: :ok, location: #restaurant }
else
format.html { render :edit }
format.json { render json: #restaurant.errors, status: :unprocessable_entity }
end
end
end
def destroy
#restaurant.destroy
respond_to do |format|
format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_restaurant
#restaurant = Restaurant.find(params[:id])
end
def restaurant_params
params.require(:restaurant).permit(:name)
end
end
restaurant.rb
class Restaurant < ApplicationRecord
belongs_to :user
end
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :restaurants
end
application_policy.rb
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
#user = user
#record = record
end
def index?
false
end
def show?
scope.where(:id => record.id).exists?
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
def scope
Pundit.policy_scope!(user, record.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope
end
end
end
restaurant_policy.rb
class RestaurantPolicy < ApplicationPolicy
class Scope < Scope
def index?
true
end
def show?
scope.where(:id => record.id).exists?
end
def create?
true
end
def new?
create?
end
def update?
true
end
def edit?
update?
end
def destroy?
true
end
end
end
You must define your policy methods out of RestaurantPolicy::Scope, like so:
class RestaurantPolicy < ApplicationPolicy
class Scope < Scope
def index?
true
end
end
# Notice we have closed the definition of Scope class.
def show?
scope.where(:id => record.id).exists?
end
def create?
true
end
def new?
create?
end
def update?
true
end
def edit?
update?
end
def destroy?
true
end
end
Related
I'm using the Pundit gem for the user authorizations in my Rails project. The Edit function works as I expected, just user admin and whoever created the review is able to update it. However, I can't delete them with the pundit set up.
Here's my Reviews Controller:
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
def index
#reviews = Review.all
end
def new
#review = Review.new
end
def create
#review = Review.new(review_params)
#review.user_id = current_user.id
if #review.save
redirect_to review_path(#review), :alert => "Awesome! Here's your small review!"
else
error_messages(#review)
render 'new'
end
end
def show
end
def edit
authorize #review
end
def update
if #review.update(review_params)
redirect_to review_path(#review), :alert => "That's a good update!"
else
error_messages(#review)
render 'edit'
end
end
def destroy
authorize #review
#review.destroy
redirect_to reviews_path, :alert => "We'll miss that review."
end
private
def set_review
#review = Review.find_by(id: params[:id])
end
def review_params
params.require(:review).permit(:title, :content)
end
end
The Application Policy looks like this:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
#user = user
#record = record
end
def index?
false
end
def show?
false
end
def create?
false
end
def create?
new?
end
def update?
false
end
def edit?
update?
end
def destroy?
destroy?
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope.all
end
end
end
And here's my customized Review Policy file:
class ReviewPolicy < ApplicationPolicy
def edit?
user.admin? || record.user == user
end
def destroy?
user.admin? || record.user == user
end
end
In case you're wondering, I created the user_not_authorized helper method. My Application Controller looks like this.
class ApplicationController < ActionController::Base
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
protect_from_forgery with: :exception
helper_method :current_user
add_flash_types :info, :error, :warning
def logged_in?
!!current_user
end
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
def error_messages(obj)
obj.errors.messages.each do |k,v|
flash[:alert] = "#{k.to_s} #{v.first.to_s}"
end
end
private
def user_not_authorized
flash[:alert] = "Ooops sorry. You don't have access to this."
redirect_to (request.referrer || root_path)
end
end
Hope my message is clear enough and would appreciate any help. Remember, '''user.admin? || record.user == user''' works for editing but the user admins and the review creators can't delete the reviews when applying the same methods.
Please let me know if any question.
I'm still trying to wrap my head around Pundit policies. I think I'm close but I've wasted too much time trying to figure this out. My Posts policy works great, but trying to authorize comments, I am getting undefined errors...
comments_controller.rb
class CommentsController < ApplicationController
before_action :find_comment, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.create(params[:comment].permit(:comment))
#comment.user_id = current_user.id if current_user
authorize #comment
#comment.save
if #comment.save
redirect_to post_path(#post)
else
render 'new'
end
end
def edit
authorize #comment
end
def update
authorize #comment
if #comment.update(params[:comment].permit(:comment))
redirect_to post_path(#post)
else
render 'edit'
end
end
def destroy
authorize #comment
#comment.destroy
redirect_to post_path(#post)
end
private
def find_comment
#post = Post.find(params[:post_id])
#comment = #post.comments.find(params[:id])
end
end
comment_policy.rb
class CommentPolicy < ApplicationPolicy
def owned
comment.user_id == user.id
end
def create?
comment.user_id = user.id
new?
end
def new?
true
end
def update?
edit?
end
def edit?
owned
end
def destroy?
owned
end
end
The formatting and indenting is a bit off... thats not how I code I swear
class ApplicationPolicy
attr_reader :user, :post
def initialize(user, post)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
#user = user
#post = post
end
def index?
false
end
def show?
scope.where(:id => post.id).exists?
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
def scope
Pundit.policy_scope!(user, post.class)
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope
end
end
end
You initialized your resource in ApplicationPolicy as #post. And since your CommentPolicy inherits from ApplicationPolicy and uses its initialization, it only has access to #post. Best option is to keep it as record:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
#user = user
#record = record
end
## code omitted
end
class CommentPolicy < ApplicationPolicy
def owned
record.user_id == user.id
end
## code omitted
end
Basically you can call it anything you want but record makes more sense as it will be used in different policy subclasses.
In my application I have designed a cart while following a similar format to the layout in the book Agile Web Development With Rails 4 and I have a slight problem. So a user can add items to a cart, view their cart, and see price of each item and also the total. The issue I ran into is when a user puts items in a cart and then signs out, the cart keeps the items in the cart even when a different user signs in. I believe the proper way would be that each user would have their own individual cart.
Here is my user model and controller
class User < ActiveRecord::Base
has_one :cart
# :confirmable, :lockable, :timeoutable and :omniauthable
# :confirmable, :lockable, :timeoutable and :omniauthable
has_secure_password
validates :email, presence: true
end
class UsersController < ApplicationController
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
redirect_to #user
end
end
private
def user_params
params.require(:user).permit(:first_name, :admin, :last_name, :email, :password, :password_confirmation, :phone_number, :address_one, :address_two, :city, :country, :state, :zip)
end
end
My cart model and controller
class Cart < ActiveRecord::Base
has_many :order_items
belongs_to :user
has_many :line_items, dependent: :destroy
def add_part(part_id)
current_part = line_items.find_by(part_id: part_id)
if current_part
current_part.quantity += 1
else
current_part = line_items.build(part_id: part_id)
end
current_part
end
def total_price
line_items.to_a.sum { |item| item.total_price}
end
end
class CartsController < ApplicationController
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def show
#cart = Cart.find(params[:id])
end
def edit
#cart = Cart.new(cart_params)
end
def update
#cart = Cart.find(params[:id])
if #cart.update_attributes(cart_params)
redirect_to #cart
end
end
def destroy
#cart.destroy if #cart.id == session[:cart_id]
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to root_path }
format.json { head :no_content }
end
end
private
def cart_params
params.require(:cart).permit(:user_id)
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to root_path, notice: "Invalid cart"
end
end
and my Line Items controller and current module (line items associates a part to a cart in my layout)
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
def create
part = Part.find(params[:part_id])
#line_item = #cart.add_part(part.id)
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item.cart }
format.json { render action: 'show', status: :created,
location: #line_item }
else
format.html { render action: 'new' }
format.json { render json: #line_item.errors,
status: :unprocessable_entity }
end
end
end
end
module CurrentCart
extend ActiveSupport::Concern
private
def set_cart
#cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
#cart = Cart.create
session[:cart_id] = #cart.id
end
end
Any advice on how I can get one cart to be associate with one user would be a big help :) if anymore information is needed just ask. Thanks again!
Hahaha! I did this whole book and never realized this bug!
Yeah... so the session stuff is cute, but you can always make it more secure by doing something like this:
def set_cart
#cart = Cart.find_by(id: session[:cart_id], user: session[:user_id])
rescue ActiveRecord::RecordNotFound
#cart = Cart.create
session[:cart_id] = #cart.id
end
Now I know you don't have the session[:user_id], but I'm guessing you already have a pretty good idea on how to get it done. ;)
Hint: On Sign In
In my Rails 4 app, there are 5 models:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
has_many :posts
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Post < ActiveRecord::Base
belongs_to :calendar
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
I implemented authentication with Devise (so we have access to current_user).
Now, I am trying to implement authorization with Pundit (first timer).
Following the documentation, I installed the gem and ran the rails g pundit:install generator.
Then, I created a CalendarPolicy, as follows:
class CalendarPolicy < ApplicationPolicy
attr_reader :user, :calendar
def initialize(user, calendar)
#user = user
#calendar = calendar
end
def index?
user.owner? || user.editor? || user.viewer?
end
def show?
user.owner? || user.editor? || user.viewer?
end
def update?
user.owner? || user.editor?
end
def edit?
user.owner? || user.editor?
end
def destroy?
user.owner?
end
end
I also updated my User model with the following methods:
def owner?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Owner"
end
def editor?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Editor"
end
def viewer?
Administration.find_by(user_id: params[:user_id], calendar_id: params[:calendar_id]).role == "Viewer"
end
I updated my CalendarsController actions with authorize #calendar, as follows:
def index
#user = current_user
#calendars = #user.calendars.all
end
# GET /calendars/1
# GET /calendars/1.json
def show
#user = current_user
#calendar = #user.calendars.find(params[:id])
authorize #calendar
end
# GET /calendars/new
def new
#user = current_user
#calendar = #user.calendars.new
authorize #calendar
end
# GET /calendars/1/edit
def edit
#user = current_user
authorize #calendar
end
# POST /calendars
# POST /calendars.json
def create
#user = current_user
#calendar = #user.calendars.create(calendar_params)
authorize #calendar
respond_to do |format|
if #calendar.save
current_user.set_default_role(#calendar.id, 'Owner')
format.html { redirect_to calendar_path(#calendar), notice: 'Calendar was successfully created.' }
format.json { render :show, status: :created, location: #calendar }
else
format.html { render :new }
format.json { render json: #calendar.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /calendars/1
# PATCH/PUT /calendars/1.json
def update
#user = current_user
#calendar = Calendar.find(params[:id])
authorize #calendar
respond_to do |format|
if #calendar.update(calendar_params)
format.html { redirect_to calendar_path(#calendar), notice: 'Calendar was successfully updated.' }
format.json { render :show, status: :ok, location: #calendar }
else
format.html { render :edit }
format.json { render json: #calendar.errors, status: :unprocessable_entity }
end
end
end
# DELETE /calendars/1
# DELETE /calendars/1.json
def destroy
#user = current_user
#calendar.destroy
authorize #calendar
respond_to do |format|
format.html { redirect_to calendars_url, notice: 'Calendar was successfully destroyed.' }
format.json { head :no_content }
end
end
And I included after_action :verify_authorized, :except => :index in my ApplicationController.
Now, when I log in, I can access http://localhost:3000/calendars/ but when I try to visit http://localhost:3000/calendars/new, I get the following error:
Pundit::NotAuthorizedError in CalendarsController#new
not allowed to new? this #<Calendar id: nil, name: nil, created_at: nil, updated_at: nil>
#user = current_user
#calendar = #user.calendars.new
authorize #calendar
end
Obviously, I must have done something wrong.
Problem: I can't figure out what.
Any idea?
You don't have access to the params in the model unless you pass them through. You should pass the calendar to the model instance function and you already have access to the user.
user.editor?(calendar)
def editor?(calendar)
Administration.find_by(user_id: self.id, calendar_id: calendar.id).role == "Editor"
end
The problem was that I had not defined a create action in the CalendarPolicy.
Since the CalendarPolicy inherits from the ApplicationPolicy — CalendarPolicy < ApplicationPolicy — and the create action in the ApplicationPolicy is set to false by default, I was getting an error.
Simply adding the following code to CalendarPolicy fixed the problem:
def create?
true
end
Bonus tip: there is no need to add a new action to CalendarPolicy since we already have the following code in ApplicationPolicy:
def new?
create?
end
I'm having problems with allowing admin users only to see and edit the users he created.
I have a tiered system: SuperUser > Admin > other users
My SuperUser can edit all users, but my Admin user can only edit himself. To try to fix this, I have a creator_id parameter that gives a creator_id to the new user that matches the id of the current user.
My controller for users:
class UsersController < ApplicationController
#CanCan resource will generate a 500 error if unauthorized
load_and_authorize_resource :user
# GET /users
# GET /users.json
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
# GET /users/1
# GET /users/1.json
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #user }
end
end
# GET /users/new
# GET /users/new.json
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #user }
end
end
# GET /users/1/edit
def edit
#user = User.find(params[:id])
#User.find(session[:user])
end
# POST /users
# POST /users.json
def create
#user = User.new(params[:user])
#user.creator = current_user
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'Registration successful.' }
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
#user = User.find(params[:id])
##user = current_user
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, notice: 'Successfully updated profile.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
end
and my ability.rb file:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new #Guest user w/o account
#Permissions on what pages can be seen by which users, and what
#Users can do with those pages
if user.status == "Super User"
can :manage, :all
elsif user.status == "Admin"
can :manage, Book
can [:create,:new], User
can [:show, :update], User, :id => user.id
can :manage, User, :creator_id => user.id
end
end
end
I did check the database, and it correctly assigns the current user's id to the creator_id of the new user. I'm just stuck. Cancan keeps denying the permission of updating those users and I'm not sure why. Any help is appreciated!
EDIT
My user model:
class User < ActiveRecord::Base
has_many :books
has_many :listings
has_many :orders
belongs_to :organizations
belongs_to :creator, class_name: 'User'
attr_accessible :password, :email, :first_name, :last_name, :password_confirmation, :status, :username
acts_as_authentic
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :username, :presence => true, :uniqueness => true
validates :email, :presence => true, :uniqueness => true
validates :status, :presence => true
end
Okay just reading your question again it looks like you want an administrator to have authoritative access to manage a user. In this case you could define something fairly similar in your application_controller
def correct_user
if !params[:id].nil?
#user.User.find_by_id(params[:id])
if current_user.status :admin
else
access_denied unless current_user?(#user)
end
end
end
What this does is allows an administrator to have access to all users accounts and if the user is not an administrator then they are denied access. You can enable this feature using the before_filter in your controllers so that you could do something like before_filter :correct_user, :only => [:edit, :show] this means that only the correct user can have access to these actions. So should you have a UserController like the following maybe:
class UsersController < ApplicationController
load_and_authorize_resource
before_filter :correct_user, :only => [:edit, :show]
..
....
.....
end
This example shows that as a correct user or an admin will have access to edit and show actions.
Try this.
def initialize(user)
user ||= User.new
if user.super_user?
can :manage, :all
elsif user.admin?
can [:create, :new], User
can [:show, :edit, :update], User do |usr|
id == usr.id
end
can :manage, User do |usr|
usr.creator_id == usr.id
end
end
end
In user model, add methods:
def has_status?(given_status)
status == given_status
end
def admin?
has_status? 'Admin'
end
def super_user?
has_status? 'Super User'
end