What is the best way to bypass devise authorization for a specific record marked public
Asked Answered
H

2

12

I'm using devise and cancan in a Rails 3.2 project. I have an event model with a boolean flag public. If the event is marked as public => true then I want anybody, signed in or not to be able to access the record with

GET /events/:id

If it is marked as public => false then a series of cancan abilities will decide authorization and access to the above resource.

What is the best pattern for achieving this?

Hydatid answered 5/3, 2012 at 20:17 Comment(0)
C
21

You can do that by skip the authenticate_user! in case of you have this args

  skip_before_filter :authenticate_user!, :only => :show, :if => lambda { 
    if params[:id]
      @event = Event.find(params[:id])
      @event and @event.public?
    else
      false
    end
  }
Cook answered 5/3, 2012 at 20:21 Comment(3)
Actually the parameter is a field in the resource but now I think of it of course I can load the resource in the lambda and check the field.Hydatid
The params[:id] is the resource identifier and if the resource is marked public then authentication is not needed. Can you suggest another method?Hydatid
This solution seems to be deprecated. Check this: github.com/rails/rails/issues/9703.Cianca
S
-2

No, do not skip authentication. You want to skip authorization. A better solution would be to explicitly authorize events with public => true.

In your cancan ability class:

can :read, Event do |e|
  some_other_authorization_boolean || e.public?
end

This ability would be given to all users; even ones that are not logged in.

Spoony answered 5/3, 2012 at 20:56 Comment(1)
If you don't skip authentication then you get thrown back out to the sign up screen. CANCAN authorization only occurs after devise authentication has had a chance to cancel the filter chain.Hydatid

© 2022 - 2024 — McMap. All rights reserved.