Clearance là hệ thống xác thực đơn giản với email và mật khẩu do đội ngũ Thoughtbot xây dựng. Nó có các mặc định theo quan điểm nhưng dễ dàng ghi đè. Hệ thống được duy trì tích cực, bạn có thể theo dõi trên GitHub.
Trong hướng dẫn này, bạn sẽ thấy cách tích hợp Clearance vào ứng dụng Rails. Chúng ta sẽ dùng một ứng dụng nhỏ. Hãy bắt đầu!
Bắt Đầu
Khởi tạo bằng cách tạo ứng dụng Rails. Cho hướng dẫn này, tôi đặt tên tutsplus-clearance.
rails new tutsplus-clearance -T
Đó sẽ làm việc.
Cần bootstrap để app đẹp hơn. Thêm gem Bootstrap vào Gemfile.
#Gemfile ... gem 'bootstrap-sass'
Cài gem bằng bundle install.
Sửa application.scss thành:
#app/assets/stylesheets/application.scss @import 'bootstrap-sprockets'; @import 'bootstrap';
Thiết Lập Clearance
Mở Gemfile thêm gem Clearance.
#Gemfile gem 'clearance'
Cài gem:
bundle install
Lúc này, chạy lệnh generator cài clearance:
rails generate clearance:install
Sẽ xuất ra terminal kết quả như sau:
create config/initializers/clearance.rb
insert app/controllers/application_controller.rb
create app/models/user.rb
create db/migrate/20161115101323_create_users.rb
*******************************************************************************
Next steps:
1. Configure the mailer to create full URLs in emails:
# config/environments/{development,test}.rb
config.action_mailer.default_url_options = { host: 'localhost:3000' }
In production it should be your app's domain name.
2. Display user session and flashes. For example, in your application layout:
<% if signed_in? %>
Signed in as: <%= current_user.email %>
<%= button_to 'Sign out', sign_out_path, method: :delete %>
<% else %>
<%= link_to 'Sign in', sign_in_path %>
<% end %>
<div id="flash">
<% flash.each do |key, value| %>
<div class="flash <%= key %>"><%= value %></div>
<% end %>
</div>
3. Migrate: rake db:migrate
*******************************************************************************
Khi chạy lệnh, vài file được sinh ra. Một file là clearance.rb trong thư mục config/initializers. Model User cũng được sinh, cùng migration file như sau:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.timestamps null: false
t.string :email, null: false
t.string :encrypted_password, limit: 128, null: false
t.string :confirmation_token, limit: 128
t.string :remember_token, limit: 128, null: false
end
add_index :users, :email
add_index :users, :remember_token
end
end
Theo output, việc đầu tiên là chỉnh config environment. Vào config/environments/development.rb thêm dòng sau, ngay trước delimiter end.
...
config.action_mailer.default_url_options = { host: 'localhost:3000' }
end
Tiếp, vào config/initializers/clearance.rb sửa, đổi email sender từ mặc định sang email bạn chọn. File mặc định như sau:
#config/initializers/clearance.rb Clearance.configure do |config| config.mailer_sender = "reply@example.com" end
Bạn có thể ghi đè cấu hình mặc định bằng đoạn code sau và config theo yêu cầu:
#config/initializers/clearance.rb
Clearance.configure do |config|
config.allow_sign_up = true
config.cookie_domain = ".example.com"
config.cookie_expiration = lambda { |cookies| 1.year.from_now.utc }
config.cookie_name = "remember_token"
config.cookie_path = "/"
config.routes = true
config.httponly = false
config.mailer_sender = "reply@example.com"
config.password_strategy = Clearance::PasswordStrategies::BCrypt
config.redirect_url = "/"
config.secure_cookie = false
config.sign_in_guards = []
config.user_model = User
end
Chạy lệnh migrate database:
rake db:migrate
Mở PagesController thêm action index:
#app/controllers/pages_controller.rb class PagesController < ApplicationController def index end end
Tạo view cho action index vừa tạo.
Thêm code snippet:
#app/views/pages/index.html.erb <h1>Tutsplus Clearance</h1> <p>Welcome to our Clearance Page.</p>
Sửa routes thành:
#config/routes.rb Rails.application.routes.draw do root to: "pages#index" end
Tạo partial _navigation.html.erb trong thư mục layouts. Partial này xử lý mọi thứ liên quan điều hướng trong app.
Dán code sau và lưu:
#app/views/layouts/_navigation.html.erb
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<%= link_to 'Tutsplus-Clearance', root_path, class: 'navbar-brand' %>
</div>
<div id="navbar">
<% if signed_in? %>
<ul class="nav navbar-nav">
<li><%= link_to 'Add Page', new_page_path %></li>
</ul>
<% end %>
<ul class="nav navbar-nav pull-right">
<% if signed_in? %>
<li><span><%= current_user.email %></span></li>
<li><%= link_to 'Sign out', sign_out_path, method: :delete %></li>
<% else %>
<li><%= link_to 'Sign in', sign_in_path %></li>
<% end %>
</ul>
</div>
</div>
</nav>
<div class="container">
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>">
<%= value %>
</div>
<% end %>
</div>
Truy Cập Hạn Chế (Restricted Access)
Với Clearance, bạn có thể tạo truy cập hạn chế đến các trang cụ thể trong ứng dụng. Hãy xem cách làm.
Tạo view cho action new trong app/views/pages, tên file new.html.erb. Dán code sau:
#app/views/pages/new.html.erb <h1>Restricted Page</h1> <p>This page is restricted to authenticated users, if you can see this it means you are a superstar!</p>
Thêm dòng sau vào config/routes.rb:
#config/routes.rb ... resources :pages, only: :new ...
Cuối cùng, vào PagesController làm như sau:
#apps/controllers/pages_controller.rb class PagesController < ApplicationController before_action :require_login, only: [:new] def index end def new end end
Ở trên dùng helper require_login của Clearance để hạn chế truy cập action new. Để test, chạy rails server bằng rails server từ terminal. Truy cập https://localhost:3000/pages/new sẽ chuyển hướng đến trang sign in.
Clearance cũng cung cấp routing constraints để kiểm soát truy cập.
#config/routes.rb
Rails.application.routes.draw do
constraints Clearance::Constraints::SignedOut.new do
root to: 'pages#index'
end
constraints Clearance::Constraints::SignedIn.new do
root to: "pages#new', as: :signed_in_root
end
end
Code trên tạo route khác cho user đã xác thực.
Ghi Đè Mặc Định Clearance
Nhiều thứ xảy ra ngầm khi dùng Clearance, những thứ bạn không thấy. Có lúc bạn muốn tùy chỉnh khác tùy spec ứng dụng. Clearance cho phép ghi đè cấu hình mặc định.
Để ghi đè (hoặc generate) routes Clearance, chạy lệnh từ terminal:
rails generate clearance:routes
File routes giờ sẽ như sau:
#config/routes.rb
Rails.application.routes.draw do
resources :passwords, controller: "clearance/passwords", only: [:create, :new]
resource :session, controller: "clearance/sessions", only: [:create]
resources :users, controller: "clearance/users", only: [:create] do
resource :password, controller: "clearance/passwords", only: [:create, :edit, :update]
end
get "/sign_in" => "clearance/sessions#new", as: "sign_in"
delete "/sign_out" => "clearance/sessions#destroy", as: "sign_out"
get "/sign_up" => "clearance/users#new", as: "sign_up"
root to: "pages#index"
resources :pages, only: :new
end
Lệnh cũng set config.routes thành false trong config/initializers/clearance.rb. Nghĩa là file custom vừa sinh sẽ được dùng.
Để generate views để sửa đổi, chạy:
rails generate clearance:views
Một số file sẽ sinh ra:
app/views/passwords/create.html.erb app/views/passwords/edit.html.erb app/views/passwords/new.html.erb app/views/sessions/_form.html.erb app/views/sessions/new.html.erb app/views/users/_form.html.erb app/views/users/new.html.erb config/locales/clearance.en.yml
Sẽ có prompt trong terminal hỏi ghi đè app/views/layouts/application.html.erb. Chọn tùy chọn bạn muốn.
Layouts
Mặc định Clearance dùng layout mặc định của app. Nếu muốn đổi layout Clearance dùng khi render views, chỉ định layout trong initializer.
Clearance::PasswordsController.layout "my_passwords_layout" Clearance::SessionsController.layout "my_sessions_layout" Clearance::UsersController.layout "my_admin_layout"
Helper Methods
Clearance cung cấp helper methods dùng trong controllers, views, helpers. Các method bao gồm signed_in?, signed_out?, current_user. Ví dụ:
<% if signed_in? %> <%= current_user.email %> <%= button_to "Sign out", sign_out_path, method: :delete %> <% else %> <%= link_to "Sign in", sign_in_path %> <% end %>
Kết Luận
Clearance cung cấp nhiều tính năng cho xác thực, hãy thử dùng cho dự án tiếp theo. Tìm hiểu thêm tại trang GitHub.