简体   繁体   中英

How to allow only Admin (or some user) to edit the pages in Rails?

I have a scaffold Finances and I just realized that it can be edited by any logged in user by going to /finances/1/edit

I have installed activ_admin gem but I don't think it is what I need. How to make sure other than admin (or may be some users) no one can edit finances resource type- I

EDIT - I found https://github.com/EppO/rolify , is this best option or I still can do something better as it may be overkill ?

EDIT 1 - I went through this https://github.com/EppO/rolify/wiki/Tutorial and have assigned role "admin" to user = User.find(1), everything went well upto "ability.can? :manage, :all" in console, which shows TRUE for user 1 and false for other users. Now I am not able to figure out what to do ? I can still see all users being able to edit the page even though I have added "resourcify" in the finance.rb model. Any help ?

I'm not sure how your models are set up, but lets say your User model has an admin column, you can do the following:

FinancesController < ApplicationController
  before_filter :must_be_admin, only: :edit

  def edit
    ...
  end

  private

  def must_be_admin
    unless current_user && current_user.admin?
      redirect_to root_path, notice: "Some message"
    end
  end
end

You can add any actions needed to the before filter, eg before_filter :must_be_admin, only: [:edit, :destroy]

Well, I personally use rolify for my project and love it.. but to be honest this is super easy to achieve by simply adding a column "admin" to your User model and having it default to false. When you want a user to be an admin update the attribute to true and then require the User.admin==true to access the finances edit action... You can do this by redirecting the non-admin user from the controller (within the finances edit action)

By the way if you're using devise for auth check out Devise before_filter authenticate_admin?

If you're looking to add sensible user authorization without rolling your own solution, definitely check out CanCan . Also helpful is this screencast by its author, Ryan Bates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM