Friday, July 14, 2017

My own style RoR project with Remember me feature

* Now it is the time for me to create my own style Ruby on Rails project with "Remember me" function.

* In the Bracket text editor, I switched the project to "myapp2".

* As usual, I started the Rails server using the rails server command.
~$ cd myapp2
~/myapp2$ rails s -b 0.0.0.0 -p 3000

* I went to the homepage of the project. In Firefox, I typed: http://localhost:3000/


* I opened a new Linux shell terminal, tested, tested the project, and made sure no failures.

~$ cd myapp2
~/myapp2$ rails test
Running via Spring preloader in process 20987
Run options: --seed 11214

# Running:

...........................

Finished in 1.639271s, 16.4707 runs/s, 40.2618 assertions/s.

27 runs, 66 assertions, 0 failures, 0 errors, 0 skips

* I went back to the book https://www.railstutorial.org/book/advanced_login

* I created a branch "advanced-login"

* I fixed some typos in the READMD.md file
/myapp2/README.md
For this version, I added this line in the Gemfile to make the test runs properly.

* I added the remember_digest field in the User model.
~/myapp2$ rails generate migration add_remember_digest_to_users remember_digest:string

* Here was the database migration file.
class AddRememberDigestToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :remember_digest, :string
  end
end

* Then, I ran db migration command.
$ rails db:migrate
== 20170714235540 AddRememberDigestToUsers: migrating =========================
-- add_column(:users, :remember_digest, :string)
   -> 0.0222s
== 20170714235540 AddRememberDigestToUsers: migrated (0.0231s) ================

* I copied and pasted (with some modifications) the User model file.
myapp2/app/models/user.rb
class User < ApplicationRecord
  before_save { self.email = email.downcase }
  validates :first_name, presence: true, length: { maximum: 50 }
  validates :last_name, presence: true,  length: { maximum: 50 }   
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i   
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }
   
  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end   

  # 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   
   
  # Returns a random token.   
  def User.new_token
    SecureRandom.urlsafe_base64
  end   

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # 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   

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end   
   
end

* I copied and pasted the codes in Sessions controller.
myapp2/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController

  def new
  end

  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

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end   
   
end

* I copied and pasted the codes in Sessions Helper.
myapp2/app/helpers/sessions_helper.rb
module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # 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

  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end   
       
  # Returns the current logged-in user (if any).
  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   

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end   

  # Logs out the current user.
  def log_out
    forget(current_user)     
    session.delete(:user_id)
    @current_user = nil
  end   
   
end

* I copied and pasted the codes for Users Login Integration Test.
myapp2/test/integration/users_login_test.rb
require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:jimmy)
  end   
   
  test "login with invalid information" do
    get login_path
    assert_template 'sessions/new'
    post login_path, params: { session: { email: "", password: "" } }
    assert_template 'sessions/new'
    assert_not flash.empty?
    get root_path
    assert flash.empty?
  end   

  test "login with valid information" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                          password: 'password' } }
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
  end   

  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                          password: 'password' } }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    # Simulate a user clicking logout in a second window.
    delete logout_path     
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end   

  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
   
end

* I added a test case: "authenticated? should return false for a user with nil digest"  the User Models Test.
myapp/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 checkbox control for the Login page in Ruby Embedded Html file (html.erb) file.
myapp2/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 %>

* And I added the properties of class .checkbox and id #session_remember_me  in the CSS stylesheet file as well.
app/assets/stylesheets/templatemo-style.css
.checkbox {
  margin-top: 10px;
  margin-bottom: 10px;
  span {
    margin-left: 20px;
    font-weight: normal;
  }
}

#session_remember_me {
  width: auto;
  margin-left: 10;
}

* I copied and pasted the codes in Test Helper.
myapp2/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 created a new file sessions_helper_test.rb
~/myapp2$ touch test/helpers/sessions_helper_test.rb

* I copied and pasted the codes in it.
myapp2/test/helpers/sessions_helper_test.rb
require 'test_helper'

class SessionsHelperTest < ActionView::TestCase

  def setup
    @user = users(:jimmy)
    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

* Lastly, I ran a test for the project.
$ rails test
Running via Spring preloader in process 23052
Run options: --seed 45355

# Running:

..............................

Finished in 1.240612s, 24.1816 runs/s, 57.2298 assertions/s.

30 runs, 71 assertions, 0 failures, 0 errors, 0 skips

* After the test command, I ran the test manually to verify the "Remember me" functionality work as the intention.


* To wrap to, I ran the test again, added all untracked files, committed changes, merged into Master branch, and pushed onto Github.
$ rails test
$ git add -A
$ git commit -m "Implement advanced login"
$ git checkout master
$ git merge advanced-login
$ git push

* The Github URL address for myapp2 project is: https://github.com/jimmy2046/myapp2

1 comment:

  1. Really nice blog post.provided a helpful information.I hope that you will post more updates like thisRuby on Rails Online Training India

    ReplyDelete

How to kill an abandoned process in Linux/Unix

I remembered it, then I forgot, then I remembered it, and then I forgot again. In case of a Linux/Unit process hang, I have to figure out ...