To test pundit, its necessary to log in at the app first? - ruby-on-rails

I am using pundit gem to authorize in my system app. before to implement pundit I had my endpoint index like this:
def index
#cars = Car.all
render json: #cars
end
worked ok, but now with pundit, i made a change like this
def index
#cars = Car.all
authorize #cars
end
Now I am getting this error:
current_user must be defined before the impersonates method

Pundit works a little differently for the index route. typically you want to do exactly what you where trying authorize #post but we only pass one record.
So for you:
# posts_controller.rb
def index
#posts = policy_scope(Post)
end
this hits the following in pundit:
# app/policies/post_policy.rb
# [...]
class Scope < Scope
def resolve
scope.all # If users can see all posts
# scope.where(user: user) # If users can only see their posts
# scope.where("name LIKE 't%'") # If users can only see posts starting with `t`
# ...
end
end
As for your error related to the current_user, is that coming from pundit? In pundit itself your current_user (from devise for example) will be just user, such that you can check record.user == user.

Related

Rails - Handle User roles using pundit

I have a table of users with enum user_type [Manager, Developer, QA]. Currently, I'm handling sign in using Devise and after login I'm using the following logic to display the appropriate webpage:
class HomeController < ApplicationController
before_action :authenticate_user!
def index
if current_user.manager?
redirect_to manager_path(current_user.id)
end
if current_user.developer?
redirect_to developer_path(current_user.id)
end
if current_user.quality_assurance?
redirect_to qa_path(current_user.id)
end
end
end
I want to use pundit gem to handle this. From the documentation, it transpired that this logic will be delegated to policies but I can't figure out how. Can somebody help me in implementing pundit in my project?
This is my users table:
I have created a user_policy but its mostly empty:
class UserPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
end
User model:
You want to use Pundit to authorize a user, as in check if that user should be allowed to visit a controller action. If the user is not authorized for a specific action it raises a Pundit::NotAuthorizedError
You can check if a user is allowed to perform an action in the pundit policy, in which you have access to record (the instance thats passed to authorize) and user. So assuming you have a Flat Model, where only the owner can edit the Flat you might do this:
# flats_policy.rb
def edit?
record.user == user
end
Now lets say you also want to allow admins to edit you might do this
# flats_policy.rb
def owner_or_admin?
record.user == user || user.admin # where admin is a boolean
end
def edit?
owner_or_admin?
end
and the controller:
# flats_controller.rb
def edit
#flat = Flat.find(params[:id])
authorize #flat
# other code here
end
Now the index action is the odd one out because you would essentially have to call authorize on each instance, so the way Pundit handles this is with the Scope:
# flats_policy.rb
class Scope < Scope
def resolve
scope.all
end
end
and a corresponding index action might look like:
def index
#flats = policy_scope(Flat) # note that we call the model here
end
So lets say a user can only see flats that he/she owns:
# flats_policy.rb
class Scope < Scope
def resolve
scope.where(user: user)
end
end
and if admins can see all flats:
# flats_policy.rb
class Scope < Scope
def resolve
if user.admin
scope.all
else
scope.where(user: user)
end
end
end
In any case if the user is not allowed to perform an action you can rescue from the error like so:
# application_controller
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def user_not_authorized
flash[:alert] = "You are not authorized to perform this action."
redirect_to(root_path)
end
I guess you could do some dirty redirecting here, as in send admins to an admins_root_path, users to a default_root_path and so on...
On a final note, since this post is already too long you can check a policy in the view like this:
<% if policy(restaurant).edit? %>
You can see me if you have edit rights
<% end %>

Ruby On Rails Pundit Gem Authorizing Dashboard

How would I provide pundit authorization for a dashboard controller which provides data from various models?
My DashboardsController looks like this:
class DashboardsController < ApplicationController
before_action :authenticate_user!
before_action :set_user
before_action :set_business
after_action :verify_authorized
def index
end
private
def set_user
#user = current_user
end
def set_business
#business = current_user.business
end
end
How would I authorize for both #user and #business within my DashboardsPolicy?
I would argue that trying to get access to a dashboard is not a policy based on a resource named dashboard, but simply a special method in the business policy.
Therefore, I would add this to the BusinessPolicy as a method dashboard.
# in your controller
authorize #business, :dashboard?
# and the business_policy
class BusinessPolicy < ApplicationPolicy
def dashboard?
# condition depending on a `user` (current_user) and a record (business)
user.admin? || user.business == record
end
end
Or it might be even simpler. If someone is allowed to see the dashboard when she is allowed to show the business, then just re-use BusinessPolicy#show? in your controller:
authorize #business, show?
Pundit expects a current user and a model object to be passed to it. In this case I think what you would want is a DashboardsPolicy class, and you would authorize it like:
def index
authorize(#business)
end
From the README:
Pundit will call the current_user method to retrieve what to send into
this argument
The authorize method automatically infers that Post will have a
matching PostPolicy class, and instantiates this class, handing in the
current user and the given record
There is also a specific section in the README regarding headless policies that uses the Dashboard as the example action: https://github.com/varvet/pundit#headless-policies
You can also create a plain ruby object that takes two entities and use that as your object to authorize:
class UserBusiness
def initialize(user, business)
end
...other methods here
end
#model = UserBusiness.new(user, business)
authorize(#model)

Pundit Gem Index Page Prevent Access

I'm using the pundit gem and trying to figure out how to use it to prevent access to an index page that belongs to a user other than the current_user.
The examples only talk about how to scope the results to the current_user but no how to actually prevent access to the page itself if the current_user is NOT the owner of the record.
Any help appreciated
Thanks
Maybe you want something like this? (For class ModelName)
# /policies/model_name_policy.rb
class ModelNamePolicy
attr_reader :current_user, :resource
def initialize(current_user, resource)
#current_user = current_user
#resource = resource
end
def index?
current_user.authorized_to_edit?(resource)
end
end
# /models/user.rb
class User < ActiveRecord::Base
def authorized_to_edit?(resource)
admin? | (id == resource.created_by) # Or whatever method you want to call on your model to determine ownership
end
end
EDIT: Note that you will also need to call authorize from your controller to invoke the policy.

Pundit authorization in index

I have been recently reading through the pundit gem's README and noticed that they never authorize the index view within a controller. (Instead they use scope).
They give good reasoning for this, as an index page generally contains a list of elements, by controlling the list that is generated you effectively control the data on the page. However, occasionally it may be desired to block access to even the index page itself. (Rather than allowing access to a blank index page.) My question is what would be the proper way to perform this?
I have so far come up with several possibilities, and have the following classes:
A model MyModel
A controller MyModelsController
A policy MyModelPolicy
In my index method of my controller, the recommended method to solve this would be as follows:
def index
#my_models = policy_Scope(MyModel)
end
This will then allow access to the index page, but will filter the results to only what that use can see. (E.G. no results for no access.)
However to block access to the index page itself I have arrived at two different possibilities:
def index
#my_models = policy_Scope(MyModel)
authorize #my_models
end
or
def index
#my_models = policy_Scope(MyModel)
authorize MyModel
end
Which of these would be the correct path, or is there a different alternative that would be preferred?
class MyModelPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
raise Pundit::NotAuthorizedError, 'not allowed to view this action'
end
end
end
end
Policy,
class MyModelPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
scope.where(user: user)
end
end
end
def index?
user.admin?
end
end
Controller,
def index
#my_models = policy_scope(MyModel)
authorize MyModel
end

Rails - Pundit with scopes

I am trying to figure out how to write pundit permissions in my Rails 4 app.
I have an article model, with an article policy. The article policy has:
class ArticlePolicy < ApplicationPolicy
attr_reader :user, :scope
def initialize(user, record, scope)
#scope = scope
super(user, record)
end
class Scope < Scope
def resolve
if user == article.user
scope.where(user_id: user_id)
elsif approval_required?
scope.where(article.state_machine.in_state?(:review)).(user.has_role?(:org_approver))
else
article.state_machine.in_state?(:publish)
end
end
end
# TO DO - check if this is correct - I'm not sure.
# I now think I don't need the index actions because I have changed the action in the articles controller to look for policy scope.
# def index?
# article.state_machine.in_state?(:publish)
# end
def article
record
end
The articles controller has:
def index
#articles = policy_scope(Article)
# query = params[:query].presence || "*"
# #articles = Article.search(query)
end
I am following the pundit documents relating to scopes and trying to figure out why the index action shown in the policy documents isn't working for me. I have tried the following (as shown in the docs):
<% policy_scope(#user.articles).sort_by(&:created_at).in_groups_of(2) do |group| %>
but I get this error:
undefined local variable or method `article' for #<ArticlePolicy::Scope:0x007fff08ae9f48>
Can anyone see where I've gone wrong?
I'm not sure that #user.articles is right. In my construct, articles belong to users, but in my index action, I want to show every user the articles that my scopes allow them to see.
You can try this in your action in controller.
#articles = policy_scope(Article).all
It will get all the articles. If you want to get the articles based on search params, you can try this.
#q = policy_scope(Article).search(params[:query])
#articles = #q.result
I think you may need to explicitly set article as an accessor in the Scope class as the error indicates that it doesn't recognise 'article'. Try something like
attr_accessor :article
set it in an initialize method and you can probably do away with the article method.
def initialize(record)
#article = record
end

Resources