CanCanで権限管理

目的

Deviseでユーザー認証を行い、CanCanで権限管理をする。
権限は、管理者、登録者、歌詞閲覧

インストール

Gemfileに追記

# Authentication
gem 'cancan'

gemをインストール

bundle install

CanCan設定

rails g cancan:ability

ロールを追加

admin 管理者
register 登録する人
lyrics_viewer 歌詞閲覧
attr_accessible :role
module Roles
  ADMIN = "admin"
  REGISTER = "register"
  LYRICS_VIEWER = "lyrics_viewer"
end

追加するとこんな感じ

  • app/models/user.rb
class User < ActiveRecord::Base
  module Roles
    ADMIN = "admin"
    REGISTER = "register"
    LYRICS_VIEWER = "lyrics_viewer"
  end

  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :rememberable, :trackable, :validatable,
         :authentication_keys => [:user_id]

  # Setup accessible (or protected) attributes for your model
  attr_accessible :user_name, :user_id, :email, :password, :password_confirmation, :remember_me, :role
  # attr_accessible :title, :body

  def email_required?
    false
  end
end

Usersテーブルにroleを追加

rails g migration add_role_to_users role:string

マイグレーション

rake db:migrate
  • app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.role == User::Roles::ADMIN
      can :manage, :all
    else
      can :read, :all
    end
  end
end

初期ユーザー(管理者)を作成

  • db/seeds.rb
# -*- coding: utf-8 -*-

unless User.find_by_user_id("admin")
  # ユーザーID : admin
  # パスワード : ********
  User.create(:user_name => "管理者", :user_id => "admin", :role => "admin", :password => "********")
end

db:seedを実行

rake db:seed