Commit a49b266d by Quang Vinh Nguyen

Add password reset

parent 452816b5
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
// Place all the styles related to the PasswordResets controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
# comment
class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update] # only: %i[edit udpate]
before_action :valid_user, only: [:edit, :update] # only: %i[edit update]
before_action :check_expiration, only: [:edit, :update] # only: %i[edit update] # Case(1)
# Case(1) An expired password reset
# Case(2) A failed update due to an invalid password
# Case(3) A failed update (which initially looks “successful”)
# due to an empty password and confirmation
# Case(4) A successful update
def new; end
def create
@user = User.find_by(email: params[:password_reset][:email].downcase)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = 'Email sent with password reset instructions'
redirect_to root_url
else
flash.now[:danger] = 'Email address not found'
render 'new'
end
end
def edit; end
def update
if params[:user][:password].empty? # Case(3)
@user.errors.add(:password, "can't be empty")
render 'edit'
elsif @user.update_attributes(user_params) # Case(4)
@user.update_attribute(:reset_digest, nil)
log_in @user
flash[:success] = 'Password has been reset.'
redirect_to @user
else # Case(2)
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
def get_user
@user = User.find_by(email: params[:email])
end
# Confirm a valid user.
def valid_user
unless ( @user && @user.activated? &&
@user.authenticated?(:reset, params[:id]))
redirect_to root_url
end
end
# Checks expiration of reset token.
def check_expiration
if @user.password_reset_expired?
flash[:danger] = 'Password reset has expired.'
redirect_to new_password_reset_url
end
end
end
# This is user controller # comment
class UsersController < ApplicationController class UsersController < ApplicationController
before_action :logged_in_user, only: %i[edit update index destroy] before_action :logged_in_user, only: [:edit, :update, :index, :destroy]
before_action :correct_user, only: %i[edit update] before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy before_action :admin_user, only: :destroy
def new def new
......
module PasswordResetsHelper
end
...@@ -19,9 +19,8 @@ class UserMailer < ApplicationMailer ...@@ -19,9 +19,8 @@ class UserMailer < ApplicationMailer
# #
# en.user_mailer.password_reset.subject # en.user_mailer.password_reset.subject
# #
def password_reset def password_reset(user)
@greeting = 'Hi' @user = user
mail to: user.email, subject: 'Password reset'
mail to: 'to@example.org'
end end
end end
# comment # comment
class User < ApplicationRecord class User < ApplicationRecord
attr_accessor :remember_token, :activation_token # we don't wan't to save this attribute to database attr_accessor :remember_token, :activation_token, :reset_token # we don't wan't to save this attribute to database
before_save :downcase_email # before_save { email.downcase! } before_save :downcase_email # before_save { email.downcase! }
before_create :create_activation_digest before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 } validates :name, presence: true, length: { maximum: 50 }
...@@ -58,6 +58,23 @@ class User < ApplicationRecord ...@@ -58,6 +58,23 @@ class User < ApplicationRecord
UserMailer.account_activation(self).deliver_now UserMailer.account_activation(self).deliver_now
end end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Return true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
private private
# converts email to all lower-case. # converts email to all lower-case.
......
<% provide(:title, 'Reset password') %>
<h1>Reset password</h1>
<div class='row'>
<div class='col-md-6 col-md-offset-3'>
<%= form_for(@user, url: password_reset_path(params[:id])) do |f| %>
<%= render 'shared/error_messages' %>
<%= hidden_field_tag :email, @user.email %>
<%= f.label :password %>
<%= f.password_field :password, class: 'form-control' %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, class: 'form-control' %>
<%= f.submit 'Update password', class: 'btn btn-primary' %>
<% end %>
</div>
</div>
\ No newline at end of file
<% provide(:title, 'Forgot password') %>
<h1>Forgot password</h1>
<div class='row'>
<div class='col-md-6 col-md-col-offset-3'>
<%= form_for(:password_reset, url: password_resets_path) do |f| %>
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.submit "Submit", class: 'btn btn-primary' %>
<% end %>
</div>
</div>
\ No newline at end of file
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
<%= f.email_field :email, class: 'form-control' %> <%= f.email_field :email, class: 'form-control' %>
<%= f.label :password %> <%= f.label :password %>
<%= link_to "(forgot password)", new_password_reset_path %>
<%= f.password_field :password, class: 'form-control' %> <%= f.password_field :password, class: 'form-control' %>
<%= f.label :remember_me, class: 'checkbox inline' do %> <%= f.label :remember_me, class: 'checkbox inline' do %>
......
<h1>User#password_reset</h1> <h1>Password reset</h1>
<p>To reset your password click the link below:</p>
<%= link_to "Reset password", edit_password_reset_url(@user.reset_token,
email: @user.email) %>
<p>This link will expire in two hours.</p>
<p> <p>
<%= @greeting %>, find me in app/views/user_mailer/password_reset.html.erb If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
</p> </p>
\ No newline at end of file
User#password_reset To reset your password click the link below:
<%= @greeting %>, find me in app/views/user_mailer/password_reset.text.erb <%= edit_password_reset_url(@user.reset_token, email: @user.email) %>
This link will expire in two hours.
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
\ No newline at end of file
Rails.application.routes.draw do Rails.application.routes.draw do
root 'static_pages#home' root 'static_pages#home'
get '/signup', to: 'users#new' get '/signup', to: 'users#new'
get '/help', to: 'static_pages#help' get '/help', to: 'static_pages#help'
...@@ -11,4 +10,5 @@ Rails.application.routes.draw do ...@@ -11,4 +10,5 @@ Rails.application.routes.draw do
delete '/logout', to: 'sessions#destroy' delete '/logout', to: 'sessions#destroy'
resources :users resources :users
resources :account_activations, only: [:edit] resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
end end
class AddResetToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users, :reset_digest, :string
add_column :users, :reset_sent_at, :datetime
end
end
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20180601074419) do ActiveRecord::Schema.define(version: 20180604030416) do
create_table "users", force: :cascade do |t| create_table "users", force: :cascade do |t|
t.string "name" t.string "name"
...@@ -23,6 +23,8 @@ ActiveRecord::Schema.define(version: 20180601074419) do ...@@ -23,6 +23,8 @@ ActiveRecord::Schema.define(version: 20180601074419) do
t.string "activation_digest" t.string "activation_digest"
t.boolean "activated", default: false t.boolean "activated", default: false
t.datetime "activated_at" t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.index ["email"], name: "index_users_on_email", unique: true t.index ["email"], name: "index_users_on_email", unique: true
end end
......
require 'test_helper'
class PasswordResetsTest < ActionDispatch::IntegrationTest
def setup
ActionMailer::Base.deliveries.clear
@user = users(:foo)
end
test 'password resets' do
get new_password_reset_path
assert_template 'password_resets/new'
# Invalid email
post password_resets_path, params: { password_reset: { email: ''} }
assert_not flash.empty?
assert_template 'password_resets/new'
# Valid email
post password_resets_path,
params: { password_reset: { email: @user.email } }
assert_not_equal @user.reset_digest, @user.reload.reset_digest
assert_equal 1, ActionMailer::Base.deliveries.size
assert_not flash.empty?
assert_redirected_to root_url
# Password reset form
user = assigns(:user)
# Wrong email
get edit_password_reset_path(user.reset_token, email: '')
assert_redirected_to root_url
# Inactive user
user.toggle!(:activated)
get edit_password_reset_path(user.reset_token, email: user.email)
assert_redirected_to root_url
user.toggle!(:activated)
# Right email, wrong token
get edit_password_reset_path('wrong token', email: user.email)
assert_redirected_to root_url
# Right email, right token
get edit_password_reset_path(user.reset_token, email: user.email)
assert_template 'password_resets/edit'
assert_select 'input[name=email][type=hidden][value=?]', user.email
# Invalid password & confirmation
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: 'foobaz',
password_confirmation: 'barquux' } }
assert_select 'div#error_explanation'
# Empty password
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: '',
password_confirmation: '' } }
assert_select 'div#error_explanation'
# Valid password & confirmation
patch password_reset_path(user.reset_token),
params: { email: user.email,
user: { password: 'foobaz',
password_confirmation: 'foobaz' } }
assert is_logged_in?
assert_not flash.empty?
assert_redirected_to user
assert_nil user.reload.reset_digest
end
test 'expired token' do
get new_password_reset_path
post password_resets_path,
params: { password_reset: { email: @user.email } }
@user = assigns(:user)
@user.update_attribute(:reset_sent_at, 3.hours.ago)
patch password_reset_path(@user.reset_token),
params: { email: @user.email,
user: { password: 'foobar',
password_confirmation: 'foobar' } }
assert_response :redirect
follow_redirect!
assert_match /expired/i, response.body
end
end
...@@ -11,6 +11,8 @@ class UserMailerPreview < ActionMailer::Preview ...@@ -11,6 +11,8 @@ class UserMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset # Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
def password_reset def password_reset
UserMailer.password_reset user = User.first
user.reset_token = User.new_token
UserMailer.password_reset(user)
end end
end end
...@@ -24,11 +24,14 @@ class UserMailerTest < ActionMailer::TestCase ...@@ -24,11 +24,14 @@ class UserMailerTest < ActionMailer::TestCase
assert_match CGI.escape(user.email), mail.body.encoded assert_match CGI.escape(user.email), mail.body.encoded
end end
# test "password_reset" do test 'password_reset' do
# mail = UserMailer.password_reset user = users(:foo)
# assert_equal "Password reset", mail.subject user.reset_token = User.new_token
# assert_equal ["to@example.org"], mail.to mail = UserMailer.password_reset(user)
# assert_equal ["from@example.com"], mail.from assert_equal 'Password reset', mail.subject
# assert_match "Hi", mail.body.encoded assert_equal [user.email], mail.to
# end assert_equal ['noreply@example.com'], mail.from
assert_match user.reset_token, mail.body.encoded
assert_match CGI.escape(user.email), mail.body.encoded
end
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment