0

I am using Devise and Cancan gems on a Rails 3.1 app.

I added several additional columns to User.

I managed to define the abilities and they work fine, I can see that it works but I haven't figured out how do I unauthorize actions (such as :update) since I don't have access to Devise or users controller?

How do that work?

zabumba
  • 12,172
  • 16
  • 72
  • 129
  • You probably want a combination of the two answers offered. Tsagadai is correctly showing you how to use a before_filter to control access and simonmorley is using the CanCan roles like you will want to do. – Andrew Hubbs Nov 21 '12 at 01:40

2 Answers2

1

Add a field to User, say :approved and make it only accessible to admins.

Write a filter in your ApplicationsController, because you are keeping everything DRY nd once you start using authorization you will use it a lot.

def verify_approval
  unless current_user.approved
    flash[:error] = I18n.t("not_approved")
    redirect_to(root_path)
  end 
end

Then use that filter where users require the privilege:

class RandomsController
  before_filter :verify_approval, only: [:update]

Bam, done. No editing devise or the UsersController.

Tsagadai
  • 887
  • 2
  • 8
  • 21
  • yes but when and where do I set :approved to TRUE? and how do make it only accessible for admin? – zabumba Nov 24 '12 at 16:14
  • Oh I see what you mean now. What I want is to allow a user to edit his own profile but not others. Your solution is to allow admin only to edit profiles right? That's not what I need – zabumba Nov 24 '12 at 16:25
1

Or, try using the following in ability.rb

 if user.role? :admin
  can [:create, :read], [Model1, Model2]
 end

 if user.role? :user
  can [:read], Model1, :id => user.id
 end

That will allow admins to create or read but not update. And allow users to read Model1 if it belongs to them. If you create custom actions, like "copy_model", you could add the same to ability.rb

 ...
 can [:copy_model, :read], Model1, :id => user.id
 ...
simonmorley
  • 2,810
  • 4
  • 30
  • 61
  • 1
    Ah, ok. What do you mean don't have access to devise? Just trying to figure out exactly what you need? S – simonmorley Nov 24 '12 at 16:46
  • Since Devise is an engine, I don't have access to users_controller in order to call authorise! :update, @user in edit or create for instance. Then I realise that I didn't even need to do that afterall. So I suppose I should close this question now. Thx Simon – zabumba Nov 24 '12 at 22:43
  • 1
    Glad you've fixed it. I'm sure you've read the wiki but you can override the controller actions. Sorry if you've already tried this https://github.com/plataformatec/devise#configuring-controllers. Good luck, I hope you get it fixed. – simonmorley Nov 25 '12 at 11:26