I'm using Devise for the first time with rails, and I'm having trouble with one thing:
I used the provided authenticate_user! method in my user's controller to restrict access to pages like so:
before_filter :authenticate_user!, :only => [:edit, :show, :update, :create, :destroy]
But this allows any signed in user to access any other users :edit action, which I want to restrict to only that user. How would I do that?
In your edit method, you need to do a check to see if the user owns the record:
def edit
#record = Record.find(params[:id])
if #record.user == current_user
#record.update_attributes(params[:record])
else
redirect_to root_path
end
end
You should look into Authorization such as CanCan. Or alternatively create a new method like so:
# Create an admin boolean column for your user table.
def authenticate_admin!
authenticate_user! and current_user.admin?
end
Related
I have a before filter on my Products Controller:
before_filter :authorize, only: [:create, :edit, :update]
my authorize method is defined in my application_controller as:
def authorize
redirect_to login_url, alert: "Not authorized" if current_user.nil?
end
and current_user is defined as:
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
In my rspec, I am trying:
before(:each) do
session.stub!(:user_id).and_return("admin#email.com")
end
But I am still getting an error as follows:
ProductsController PUT update with valid params redirects to the product
Failure/Error: response.should redirect_to(product)
Expected response to be a redirect to <http://test.host/products/1> but was a redirect to <http://test.host/login>
. . . which means that my test is not logged in at the time of the request.
What am I missing here?
Is there a better way to approach this situation?
Considering you are testing the controller, and trying to keep it focussed on the controller you could stub the current_user method with a real user or a mock.
before(:each) do
ApplicationController.any_instance.stub(:current_user).and_return(#user = mock('user'))
end
With that you will have access to the user mock to apply further expectations and stubs if needed.
If the mock gets in the way, change it out for a real User object.
I'm working on a polling app and use Devise and Cancan for authentication and authorization. I have a User model generated by Devise and a Poll model. A poll belongs to a user. My problem is that I have a custom action in my Polls controller and I can't get Cancan to work with that custom action. This is what I tried to do in my code:
config/routes.rb:
match 'users/:user_id/polls' => 'polls#show_user'
Ability.rb:
def initialize(user)
user ||= User.new
if user.is? :admin
can :manage, :all
else # default
can :read, :all
can :manage, Poll, :user_id => user.id
can :show_user, Poll, :user_id => user.id
end # if else admin
end
polls_controller.rb:
class PollsController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource :except => :show_user
def show_user
authorize! :show_user, user
#polls = Poll.find_all_by_user_id(params[:user_id])
render "index"
end
<...>
end
The idea is that a user's polls can be viewed only when the owner of the poll is signed in. However, with this code, when a poll's owner is signed in, that user gets kicked out of that page with a message that says authorization failed. If I remove the line authorize! :show_user, user, then a user who's signed in can view all other user's polls (the authorization doesn't work at all).
Can anyone see what I might be missing? Thanks in advance!
In abiltity.rb, you're verb/noun combination is :show_user and Poll, but in your controller you're using :show_user and user--you would need to use a Poll instead.
If, instead you want to allow the user to view all their own Polls, you might go with something like:
ability.rb:
can :show_polls_for, User, :id => user.id
polls_controller.rb:
def show_user
authorize! :show_polls_for, user
...
end
I trying to define my abilities as following:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.role == 'admin'
can :manage, :all
elsif user.role == 'member'
can :manage, [User,Post] , :id => user.id
cannot :index, User # list users page
else
can :read, :all
end
end
end
And have included load_and_authorize_resource on top of my PostsController.
If I understand the definitions, guest users SHOULDN'T have access to the create action from PostsController but they do.
Any explanation for this behaviour?
EDIT
Solved!
Just realized that I have forgot to add an before_filter :authenticate_user! since I'm using Devise for authentication.
Solved!
Just realized that I have forgot to add an before_filter :authenticate_user! since I'm using Devise for authentication.
I want to use cancan to allow updating a certain attribute of a model but not others. Here is what my update action looks like.
class UsersController < ApplicationController
load_and_authorize_resource
def update
respond_with User.update(params[:id], params[:user])
end
end
if resource.instance_of? Teacher
can [:read, :update], User do |user|
resource.users.include? user
end
I want Teacher to be able to modify user.course_id but nothing else. How should I change
can :update, User
to do what I want to.
Hm.. I"m not sure if the 'action' in a cancan ability has to explicitly be an action in the controller. If it doesn't, you could do...
# ability.rb
if resource.instance_of? Teacher
can :update_course, User
end
# Controller
def update
params[:user].delete(:course_id) if cannot? :update_course, User
respond_with User.update(params[:id], params[:user])
end
tl;dr
I use CanCan for authorization in a single-author blog. I want non-admin users to not be able to view unpublished posts. The following does not do the trick:
can :read, Post do |post|
post.published_at && post.published_at <= Time.zone.now
end
Why doesn't it work, and what can I do to make it work?
Thanks. ;-)
The long version
Hello World,
I have a single-user blogging application and use CanCan for authorization purposes. I want administrators (user.admin? # => true) to be able to do whatever they wish with everything (they are administrators after all…). I also want regular users (both those who are logged in, but does not have the admin role, and those who are not logged in) to be able to view blog posts that have been published. I do not want them to see those that are not published.
Blog posts (of the model Post) each have an attribute called published_at (which is a DateTime and nil by default). Needless to say: when published_at is nil, the post is not published, otherwise it is published at the set date and time.
I have the following in my Ability class:
class Ability
include CanCan::Ability
def initialize user
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, Post do |post|
post.published_at && post.published_at <= Time.zone.now
end
end
end
end
However, this does not seem to work as I intend it to. I have read on the CanCan wiki that this might not always work. However, I believe it should work in my case here, as I do have an instance of the Post model called #post in my PostsController#show action:
class PostsController < ApplicationController
authorize_resource
respond_to :html, :json
# other actions omitted ...
def show
#post = Post.find params[:id]
respond_with #post
end
# other actions omitted ...
end
Even with this code I am able to visit the blog post through the show action and view. I have also tried removing the authorize_resource call from the PostsController, realizing it might override some abilities or something, but it didn't help.
I have figured out a temporary solution, although I find it ugly and really want to utilize the CanCan abilities. My ugly temporary solution checks internally in the PostsController#show if the user has access to view the resource:
def show
#post = Post.find params[:id]
unless #post.published_at
raise CanCan::AccessDenied unless current_user && current_user.admin?
end
respond_with #post
end
As I said, this works. But I don't really want to go with this solution, as I believe there's a better way of doing this as a CanCan ability.
I'd much appreciate an explanation of why my approach does not work as well as a good solution to the problem. Thanks in advance. :-)
At the point where authorize_resource is being called (before_filter) you don't have a post object to authorize.
Assuming CanCan 1.6 or later, try this..
In your Post model
class Post < ActiveRecord::Base
scope :published, lambda { where('published_at IS NOT NULL AND published_at <= ?', Time.zone.now) }
# the rest of your model code
end
In your Ability model
class Ability
include CanCan::Ability
def initialize user
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, Post, Post.published do |post|
post.published_at && post.published_at <= Time.zone.now
end
end
end
end
In your controller
class PostsController < ApplicationController
load_and_authorize_resource
respond_to :html, :json
# other actions omitted ...
def show
respond_with #post
end
end