shimmyShow Webアプリ開発ブログ

プログラミングスクールTECH::CAMPを73期を卒業し、紙媒体で実施されている教育の根本を変えていくためのサービスを開発中。当ブログを読めば誰でも当該サービスを開発できるようにするため軌跡を記録中。

【第8章】オンライン教科書サービス作成【管理者権限と一般権限の付与 rails_admin, cancancan】

目的

第7章ではユーザー登録機能を実装した。本章ではアプリケーションの性質を考え管理者権限と一般権限を分ける実装を行う。

Gemfileへの追加

Gemfileの最下部へ下記を追加する。
Gemfile

〜上部分省略〜
gem 'cancancan', '~> 2.3'
gem 'rails_admin', '~> 2.0.0.beta'

追加後、ターミナルを立ち上げ、下記コマンドをonline_textディレクトリで実施する。
ターミナル

cd online_text
bundle install

cancan abilityモデルの生成

ユーザーごとのアクセス制限に関する処理を統一するためのクラス(Abilityクラスが多い)を作成する。
下記コマンドをonline_textディレクトリで実施し、abilityモデルを生成される。
ターミナル

cd online_text
rails g cancan:ability

app/models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user
    # permission to do.
    # If you pass :manage it will apply to every action. Other common actions
    # here are :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on.
    # If you pass :all it will apply to every resource. Otherwise pass a Ruby
    # class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the
    # objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details:
    # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities
  end
end

管理者権限を所有している場合、管理画面へのアクセス権限と全モデルに対する全アクションの許可をするため
生成されたモデルを下記のように編集する。

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user
    # permission to do.
    # If you pass :manage it will apply to every action. Other common actions
    # here are :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on.
    # If you pass :all it will apply to every resource. Otherwise pass a Ruby
    # class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the
    # objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details:
    # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities
    if user.try(:admin?)
      # 管理者ページへのアクセスを許可
      can :access, :rails_admin
      # 全ての権限を付与
      can :manage, :all
    end
  end
end

rails_adminの設定

下記コマンドを実施し、rails_adminの設定をする。
ターミナル

cd online_text
rails g rails_admin:install

上記コマンドを実施すると、ターミナルへ下記表示がされる。
今回は初期設定の/adminで表示するため、そのままEnterを押下して進む。

?  Where do you want to mount rails_admin? Press <enter> for [admin] 

生成された下記ファイルを下記のように編集する。
config/initializers/rails_admin.rb

RailsAdmin.config do |config|

  ### Popular gems integration

  ## == Devise ==
  config.authenticate_with do
    warden.authenticate! scope: :user
  end
  config.current_user_method(&:current_user)

  ## == CancanCan ==
  config.authorize_with :cancancan

  ## == Pundit ==
  # config.authorize_with :pundit

  ## == PaperTrail ==
  # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0

  ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration

  ## == Gravatar integration ==
  ## To disable Gravatar integration in Navigation Bar set to false
  # config.show_gravatar = true

  config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new
    export
    bulk_delete
    show
    edit
    delete
    show_in_app

    ## With an audit adapter, you can add:
    # history_index
    # history_show
  end
end

管理者権限をUsersモデルへ付与

ユーザーを管理者か判断するため、Usersテーブルへadminカラムを追加する。
追加するカラムはboolean型とし、管理者かどうかをture or falseで判断する方針とする。
追加するためのマイグレーションファイルを下記コマンドで生成する。
ターミナル

cd online_text
rails g migration AddAdminToUsers

上記コマンドで生成されたマイグレーションファイルを下記のように編集する。
db/migrate/20XXXXXXXXXXXX_add_admin_to_users.rb

class AddAdminToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

マイグレーションファイルを編集後、下記コマンドでUsersテーブルへ追加する。
ターミナル

cd online_text
rails db:migrate

管理画面

ローカルサーバーを立ち上げ、下記へアクセスし、
下記のように表示されれば、管理画面の生成は成功です。
http://localhost:3000/admin/

f:id:erwinmarvin:20200922201902p:plain

上図の場合、英語での表示のため、次章では日本語化を実施する。