0
votes

I'm relatively new to ruby on rails, and so I am now very confused how to setup a user management system for admins.

Besides, users should be able to register themselfs (Devise Registerable).

I have a User controller, using devise_for :users and resources :users .

I can sign_up users, since I used the :registerable, flag in my Users model.

What I want to do now is to add the ability for admins to create users.

If I used the described system, I always get the message 'You are already signed in' when creating a new user through /users/new as admin. This is a message from devise.

So I followed the tutorial www.tonyamoyal.com/2010/07/28/rails-authentication-with-devise-and-cancan-customizing-devise-controllers/ to use cancan to restrict some actions and created a own devise registrations controller like described there.

My cancan ability model looks like this:

if user.has_role?(:admin)
  #admin
  can :manage, :all
elsif !(user.new_record?)
  #logged in but no admin
   ...
else
  # Guest
  can :create, User
end

and my registrations controller like in the tutorial

class RegistrationsController < Devise::RegistrationsController
  before_filter :check_permissions, :only => [:new, :create, :cancel]
  skip_before_filter :require_no_authentication

  def check_permissions
    authorize! :create, resource
  end
end

I also added the controller to the routes.rb

With this I can create new users with the admin, but if I want to sign_up as not logged in user ("#Guest") I get always the message cancan exception "Access denied". And if I call exception.subject in the CanCan exception handling it is empty.

Can it be, that 'resource' from my controller is not initialized? How can I get the expected behaviour?

Thanks a lot for your help ;-)

1

1 Answers

1
votes

Mhm, I figured out, that resource seems to be a method of the devise-controller. No idea, why it is not called, or is not returning an object

My solution was now (since I can only register users) to change

def check_permissions
    authorize! :create, resource
end

to

def check_permissions
    authorize! :create, User #could also be User.new 
end

And with this it works. But I'm not sure, if it is the best solution ;-)