passwords_controller.rb 2.15 KB
Newer Older
1 2
# frozen_string_literal: true

3
class PasswordsController < Devise::PasswordsController
4 5
  skip_before_action :require_no_authentication, only: [:edit, :update]

6
  before_action :resource_from_email, only: [:create]
7
  before_action :check_password_authentication_available, only: [:create]
8
  before_action :prevent_cas_reset, only: [:create]
9
  before_action :throttle_reset,      only: [:create]
10

11
  # rubocop: disable CodeReuse/ActiveRecord
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
  def edit
    super
    reset_password_token = Devise.token_generator.digest(
      User,
      :reset_password_token,
      resource.reset_password_token
    )

    unless reset_password_token.nil?
      user = User.where(
        reset_password_token: reset_password_token
      ).first_or_initialize

      unless user.reset_password_period_valid?
        flash[:alert] = 'Your password reset token has expired.'
27
        redirect_to(new_user_password_url(user_email: user['email']))
28 29 30
      end
    end
  end
31
  # rubocop: enable CodeReuse/ActiveRecord
32

33 34
  def update
    super do |resource|
35
      if resource.valid? && resource.password_automatically_set?
36 37 38 39 40
        resource.update_attribute(:password_automatically_set, false)
      end
    end
  end

41 42 43 44 45 46 47
  protected

  def resource_from_email
    email = resource_params[:email]
    self.resource = resource_class.find_by_email(email)
  end

48 49 50 51
  def check_password_authentication_available
    if resource
      return if resource.allow_password_authentication?
    else
52
      return if Gitlab::CurrentSettings.password_authentication_enabled?
53
    end
54 55

    redirect_to after_sending_reset_password_instructions_path_for(resource_name),
56
      alert: "Password authentication is unavailable."
57 58
  end

59 60 61 62 63 64 65
  def prevent_cas_reset
    return unless resource && resource.cas_user?

    redirect_to after_sending_reset_password_instructions_path_for(resource_name),
      alert: "Cannot reset password for CAS user."
  end

66 67
  def throttle_reset
    return unless resource && resource.recently_sent_password_reset?
68

69 70 71 72
    # Throttle reset attempts, but return a normal message to
    # avoid user enumeration attack.
    redirect_to new_user_session_path,
      notice: I18n.t('devise.passwords.send_paranoid_instructions')
73
  end
74
end