Class: Api::V1::PasswordsController

Inherits:
BaseController
  • Object
show all
Defined in:
lib/generators/jwt_api/templates/api/v1/passwords_controller.rb

Overview

User controller

Instance Method Summary collapse

Instance Method Details

#reset_password_instructionsObject

Password Reset Flow

  1. User requests password reset instructions by sending params with email

to /api/v1/passwords/reset



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/generators/jwt_api/templates/api/v1/passwords_controller.rb', line 10

def reset_password_instructions
  @user = User.find_by(email: password_params[:email])
  if @user.nil?
    render json: { message: 'email not found' }, status: :not_found
  elsif @user.update(
    reset_password_token: SecureRandom.uuid,
    reset_password_sent_at: Time.now
  )
    JwtMailer.reset_password(@user.id, @user.reset_password_token).deliver
    render json: { message: 'reset password instructions sent' }, status: :ok
  else
    render json: { message: @user.errors }, status: :not_found
  end
end

#update_passwordObject

Step 3: User submits password reset form with new password and includes the newly issued Bearer token within 10 minutes of issuing the token



51
52
53
54
55
56
57
# File 'lib/generators/jwt_api/templates/api/v1/passwords_controller.rb', line 51

def update_password
  if user_found? && passwords_match?(password_params[:password],
                                     password_params[:password_confirmation])

    password_update(password_params[:password])
  end
end

#verifyObject

Step 2: User clicks on link in email which sends them to /api/v1/passwords/verify with a token in the params, if a succesful response is received, the client can store the newly issued JWT and redirect the user to the password reset form



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/generators/jwt_api/templates/api/v1/passwords_controller.rb', line 28

def verify
  @user = User.find_by(reset_password_token: params[:token])
  if @user.nil?
    render json: { message: 'reset password token not found' }, status: :not_found
  elsif @user.reset_password_sent_at < 10.minutes.ago
    render json: { message: 'reset password token has expired' }, status: :not_found
  else
    @user.update!(
      reset_password_token: nil,
      reset_password_sent_at: nil,
      jti: SecureRandom.uuid
    )
    render json: {
      token: JsonWebToken.encode({ user_id: @user.id,
                                   jti: @user.jti,
                                   iat: Time.now.to_i,
                                   exp: Time.now.to_i + 10 * 60 })
    }, status: :ok
  end
end