* As usual, I switching to a branch called "advanced-login".
$ git checkout -b advanced-login
* I added the remember_digest field of string in the Users data model.
$ rails generate migration add_remember_digest_to_users remember_digest:string
* This was the content of the database migration file 20170714053652_add_remember_digest_to_users.rb
sample_app/db/migrate/20170714053652_add_remember_digest_to_users.rb
class AddRememberDigestToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :remember_digest, :string
end
end
* Then, I ran the database migration command.
$ rails db:migrate
== 20170714053652 AddRememberDigestToUsers: migrating =========================
-- add_column(:users, :remember_digest, :string)
-> 0.0280s
== 20170714053652 AddRememberDigestToUsers: migrated (0.0282s) ================
* I added a new method in User model to return a random token.
* I added a remember method to the User model.
sample_app/app/models/users.rb
* I defined the new token and digest methods using self.
sample_app/app/models/users.rb
# Returns the hash digest of the given string.
def self.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def self.new_token
SecureRandom.urlsafe_base64
end
* I added an authenticated? method to the User model.
sample_app/app/models/user.rb
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
* I added the "remember_user" method to the Sessions Controller
sample_app/app/controllers/sessions_controller.rb
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
remember user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
* I added the "remember(user)" method in the Sessions Helper
sample_app/app/helpers/sessions_helper.rb
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
* I re-wrote the "current_user" method in the Sessions helper.
sample_app/app/helpers/sessions_helper.rb
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
* I added forget method in the User model to forget a user.
sample_app/app/models/user.rb
def forget
update_attribute(:remember_digest, nil)
end
* I added the forget method in Sessions helper. And I added a line "forget(current_user)" in the log_out method to forget a user when a user logs out.
sample_app/app/helpers/sessions_helper.rb
* I added a line "delete logout_path" in Users Login Integration test to simulate a user clicking logout in a second window.
sample_app/test/integration/users_login_test.rb
* I modified the destroy method in Sessions Controller to log out a user only only when the user has already logged in.
sample_app/app/controllers/sessions_controller.rb
* I added a unit test "authenticated?" to test with a nonexistent digest.
sample_app/test/models/user_test.rb
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?('')
end
* I added a line "return false if remember_digest.nil?" in the "authenticated?" method in the User model.
sample_app/app/models/user.rb
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
* I added the "Remember me" checkbox in the log in screen.
sample_app/app/views/sessions/new.html.erb
<%= f.label :remember_me, class: "checkbox inline" do %>
<%= f.check_box :remember_me %>
<span>Remember me on this computer</span>
<% end %>
* I defined the CSS style for the Checkbox and the session_remember_me.
sample_app/app/assets/stylesheets/custom.scss
/* forms */
.checkbox {
margin-top: -10px;
margin-bottom: 10px;
span {
margin-left: 20px;
font-weight: normal;
}
}
#session_remember_me {
width: auto;
margin-left: 0;
}
* I added a line "params[:session][:remember_me] == '1' ? remember(user) : forget(user)" in the Sessions controller to remember a user login if he checks on the "Remember me" checkout.
sample_app/app/controllers/sessions_controller.rb
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
params[:session][:remember_me] == '1' ? remember(user) : forget(user)
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
* I added the "log_in_as(user)" method in Test Helper and a new class "ActionDispatch" to test the "Remember me" feature.
sample_app/test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
include ApplicationHelper
# Add more helper methods to be used by all tests here...
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Log in as a particular user.
def log_in_as(user)
session[:user_id] = user.id
end
end
class ActionDispatch::IntegrationTest
# Log in as a particular user.
def log_in_as(user, password: 'password', remember_me: '1')
post login_path, params: { session: { email: user.email,
password: password,
remember_me: remember_me } }
end
end
* I wrote two test cases "login with remembering" and "login without remembering" in the Users Login Integration Test to test the "Remember me" functionality.
sample_app/test/integration/users_login_test.rb
test "login with remembering" do
log_in_as(@user, remember_me: '1')
assert_not_empty cookies['remember_token']
end
test "login without remembering" do
# Log in to set the cookie.
log_in_as(@user, remember_me: '1')
# Log in again and verify that the cookie is deleted.
log_in_as(@user, remember_me: '0')
assert_empty cookies['remember_token']
end
* I added a line to raise an exception in the suspected untested block of code.
sample_app/app/helpers/sessions_helper.rb
* I created a new file "sessions_helper_test.rb" for testing of persistent sessions.
sample_app/test/helpers/sessions_helper_test.rb
require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
def setup
@user = users(:michael)
remember(@user)
end
test "current_user returns right user when session is nil" do
assert_equal @user, current_user
assert is_logged_in?
end
test "current_user returns nil when remember digest is wrong" do
@user.update_attribute(:remember_digest, User.digest(User.new_token))
assert_nil current_user
end
end
* I deleted the "raise exception" line in Sessions Helper.
sample_app/app/helpers/sessions_helper.rb
* Horay, I had completed chapter 9. Just like usual, I ran a test, added all untracked files, committed changes, merged back to Master branch, pushed on to Github.
$ rails test
$ git add -A
$ git commit -m "Implement advanced login"
$ git checkout master
$ git merge advanced-login
$ git push
* The Github repository address for Michael Hartl's sample_app is https://github.com/jimmy2046/sample_app.
* The screenshot of the login page with "Remember me" function.
No comments:
Post a Comment