summaryrefslogtreecommitdiff
path: root/app/controllers/settings/passwords_controller.rb
blob: cc227cf4b9ecf0abfb0a76b870d70790b75a995d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# frozen_string_literal: true

class Settings::PasswordsController < Settings::ApplicationController
  skip_before_action :check_password_expiration, only: [:new, :create]
  skip_before_action :check_two_factor_requirement, only: [:new, :create]

  before_action :set_user
  before_action :authorize_change_password!

  layout :determine_layout

  def new
  end

  def create
    unless @user.password_automatically_set || @user.valid_password?(user_params[:current_password])
      redirect_to new_settings_password_path, alert: _('You must provide a valid current password')
      return
    end

    password_attributes = {
      password: user_params[:password],
      password_confirmation: user_params[:password_confirmation],
      password_automatically_set: false
    }

    result = Users::UpdateService.new(current_user, password_attributes.merge(user: @user)).execute

    if result[:status] == :success
      Users::UpdateService.new(current_user, user: @user, password_expires_at: nil).execute

      redirect_to root_path, notice: _('Password successfully changed')
    else
      render :new
    end
  end

  def edit
  end

  def update
    password_attributes = user_params.select do |key, value|
      %w(password password_confirmation).include?(key.to_s)
    end
    password_attributes[:password_automatically_set] = false

    unless @user.password_automatically_set || @user.valid_password?(user_params[:current_password])
      redirect_to edit_settings_password_path, alert: _('You must provide a valid current password')
      return
    end

    result = Users::UpdateService.new(current_user, password_attributes.merge(user: @user)).execute

    if result[:status] == :success
      flash[:notice] = _('Password was successfully updated. Please login with it')
      redirect_to new_user_session_path
    else
      @user.reset
      render 'edit'
    end
  end

  def reset
    current_user.send_reset_password_instructions
    redirect_to edit_settings_password_path, notice: _('We sent you an email with reset password instructions')
  end

  private

  def set_user
    @user = current_user
  end

  def determine_layout
    if [:new, :create].include?(action_name.to_sym)
      'application'
    else
      'profile'
    end
  end

  def authorize_change_password!
    render_404 unless @user.allow_password_authentication?
  end

  def user_params
    params.require(:user).permit(:current_password, :password, :password_confirmation)
  end
end