4-3 STORY 2 - admin 可以登录后台
目标
- 管理者(商家)必须先登录网站才能进入(商店)后台
- 管理者必须有 admin 权限才能进入后台
Step 0:
git checkout -b story2
Step 1: 必须要先登入才能进入
app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
+ before_action :authenticate_user!
def index
@products = Product.all
end...(略)
在浏览器测试是否强制验证
http://localhost:3000/admin/products/new
Step 2: 必须要有 admin 权限才能进入
app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
before_action :authenticate_user!
+ before_action :admin_required
def index
@products = Product.all
end...(略)
Step 3: 建立 admin 判断式
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
+ def admin_required
+ if !current_user.admin?
+ redirect_to "/", alert: "You are not admin."
+ end
+ end
end
Step 4: 加入 admin? 判断式
app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
+ def admin?
+ is_admin
+ end
end
Step 5: 新增 is_admin 栏位(boolean)
rails g migration add_is_admin_to_user
修改里面的档案
db/migrate/xxx(一堆数字)_add_is_admin_to_user.rb
class AddIsAdminToUser < ActiveRecord::Migration[5.0]
def change
+ add_column :users, :is_admin, :boolean, default: false
end
end
执行rake db:migrate
重开rails server
测试admin是否能进后台
存取http://localhost:3000/admin/products/new
Step 6: 在 rails console 操作新增一个 admin 使用者
rails c
u = User.new(email: "[email protected]", password: "123456", password_confirmation: "123456")
u.save
u.is_admin = true
u.save
再次测试admin是否能进后台
存取http://localhost:3000/admin/products/new
Step 7: 新增一个 user 种子档
db/seeds.rb
u = User.newu.email = "[email protected]" # 可以改成自己的
emailu.password = "123456" # 最少要六码
u.password_confirmation = "123456" # 最少要六码
u.is_admin = true
u.save
然后rake db:seed
即可自动建一个有 admin 权限的帐号
补充: 日后资料库设定 ( migrate ) 重建时发生错误时的 bug fix
rake db:reset
Step 8: 建立后台 layout
建立 layout: admin
app/controllers/admin/products_controller.rb
class Admin::ProductsController < ApplicationController
+ layout "admin"
before_action :authenticate_user!
before_action :admin_required
...(略)
touch app/views/layouts/admin.html.erb
app/views/layouts/admin.html.erb
JDstore 后台
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<%= render "common/navbar" %>
<%= yield %>
完成
Step 9: git 存档
git add .
git commit -m "only admin can access backend panel"