سؤال

I am learning Ruby on Rails and was looking into utilizing cancan to help restrict users access to actions that they shouldn't have and to pages depending on who they are. I currently understand how to restrict actions, but I was curious if someone could help with actually restricting certain pages and unique pages.

One example is I have a home page for admin users and one for regular users, how would I restrict the admin page from the normal user?

Thanks, and any pointers on if I am doing something wrong is greatly appreciated.

هل كانت مفيدة؟

المحلول

If you want to use cancan :

Admit you add in your user controller a method admin_home :

def admin_home
    @user = current_user
    authorize! :admin_home
end

You need to specify in ability.rb file you want to restrict access to admin_home for standard users :

class Ability
    include CanCan::Ability

    def initialize(user)
        user ||= User.new # guest user (not logged in)
        if user.admin?
            #Authorize all actions
            can :manage, User
        else
            #authorize only self modifications and restrict access to admin_home
            can :manage, User, :id => user.id
            cannot :admin_home, User
        end
    end
end

You can find great resources about cancan in official wiki like https://github.com/ryanb/cancan/wiki/Defining-Abilities and https://github.com/ryanb/cancan/wiki/Authorizing-controller-actions

Hope this help

نصائح أخرى

Note: I am just giving you an example, you are not supposed to use it as it is, but you can have an Idea that how you will be able to put your logic.

class AdminsController < ApplicationController
  before_filter :check_admin, :only => [:index, :show]

  def index
    @admins = //whatever your query for this action
  end

  def show
    @admin = //whatever your query for this action
  end

  protected    
    def check_admin
      if(my_condition to check if user type is admin)
         {
           return true // or anything u want for ur admin user
         }
      else
         {
          //anything here when user is not admin
           1. you can redirect to users home page using redirect_to
           2. you can redirect to a specific page which shows "You are not authorized to see this web page"
         }
      end
    end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top