devise
簡単にユーザー登録が出来るgem.
devise導入手順
Gemfileに追加.
gem 'devise'
bundleのインストール
bundle install
deviseの準備
rails g devise:install
development.rbに設定を追加
config/environments/development.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
deviseのメッセージのための修正
app/views/layouts/application.html.erb
<div id="contents">
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
<%= yield %>
</div>
トップページの作成
routesに追加する.
config/routes.rb
root :to => 'welcome#index'
public/index.htmlを削除する.
ユーザーモデルの作成
rails g devise user
rake db:migrate
ルーティングの追加
config/routes.rb
get 'questions', :to => 'questions#index', :as => :user_root
index.htmlの編集
app/view/welcome/index.html.erb
<p><%= link_to 'ログイン', [ :new, :user_session ] %></p>
<p><%= link_to 'パスワード再発行', [ :new, :user_password ] %></p>
コントローラに設定を追加
app/controller/welcome_controller.rb
def index
if current_user
redirect_to :user_root
return
end
end
フィルタの追加
hoge_controllerのクラス宣言後に以下の記述を追加.
before_filter :authenticate_user!
サインアウトを追加
hogeアプリケーションのindex.html.erbに以下の記述を追加.
<%= link_to "Sign Out", destroy_user_session_path, :method => :delete %>
cancan
ユーザーに権限を設定できるgem.
cancan導入手順
Gemfileに追加
gem 'cancan'
bundleのインストール
bundle install
制限の生成
rails g cancan:ability
deviseのviewの作成と, Usersモデルにroleカラムを追加
rails g devise:views
rails g migration add_role_to_users role:string
rake db:migrate
Userモデルにアクセサを追加
app/models/users.rb
attr_accessible :role
ROLES=%w[admin user]
abilityに管理者アカウントと一般アカウントの権限設定の記述を追加
app/models/ability.rb
def initialize(user)
if user.role == "admin"
can :manage, :all
else
can :read, :all
end
end
アカウントの作成はseedでのみ追加することにするので, sign_upを削除
以下の箇所を削除/コメントアウトしておく
app/views/devise/shared/_links.erb
<%= link_to "Sign up", new_registration_path(resource_name) %><br />
使い方
if can? でその権限があるかどうか, if cannotでその権限がないかどうか判定できる.
<% if can? :manage, @users %>
Your role is 'admin'.
<% else %>
Your role is 'user'.
<% end %>
herokuでSMTPを使う
HerokuでDeviseのメール通知を利用するまでの手順
や
HerokuのRailsアプリからメールを送信するには?
であるように無料のSMTPサーバーを利用すればよいとのこと.
deviseのsign_up問題
Deviseプラグインのsign_upを制御するを見るにcontrollerを継承して振る舞いを変更する.
ユーザー登録
管理者のみ出来るようにする, そのためにdeviseのsign_upの振る舞いを変えたい.