sessions_controller.rb 5.2 KB
Newer Older
1
class SessionsController < Devise::SessionsController
2
  include AuthenticatesWithTwoFactor
3
  include Devise::Controllers::Rememberable
4
  include Recaptcha::ClientHelper
5

6
  skip_before_action :check_two_factor_requirement, only: [:destroy]
7

8
  prepend_before_action :check_initial_setup, only: [:new]
9 10
  prepend_before_action :authenticate_with_two_factor,
    if: :two_factor_enabled?, only: [:create]
T
Toon Claes 已提交
11
  prepend_before_action :store_redirect_uri, only: [:new]
12
  before_action :auto_sign_in_with_provider, only: [:new]
13
  before_action :load_recaptcha
14

V
Valery Sizov 已提交
15
  after_action :log_failed_login, only: [:new], if: :failed_login?
16

17
  def new
18
    set_minimum_password_length
19
    @ldap_servers = Gitlab::LDAP::Config.available_servers
20

21 22 23 24
    super
  end

  def create
25
    super do |resource|
R
Robert Speicher 已提交
26
      # User has successfully signed in, so clear any unused reset token
27 28 29 30
      if resource.reset_password_token.present?
        resource.update_attributes(reset_password_token: nil,
                                   reset_password_sent_at: nil)
      end
31 32
      # hide the signed-in notification
      flash[:notice] = nil
33
      log_audit_event(current_user, resource, with: authentication_method)
34
      log_user_activity(current_user)
35
    end
36
  end
37

J
jnoortheen 已提交
38
  def destroy
39
    Gitlab::AppLogger.info("User Logout: username=#{current_user.username} ip=#{request.remote_ip}")
J
jnoortheen 已提交
40 41 42 43 44
    super
    # hide the signed_out notice
    flash[:notice] = nil
  end

45 46
  private

47
  def log_failed_login
48
    Gitlab::AppLogger.info("Failed Login: username=#{user_params[:login]} ip=#{request.remote_ip}")
49 50 51 52 53 54
  end

  def failed_login?
    (options = env["warden.options"]) && options[:action] == "unauthenticated"
  end

55
  def login_counter
B
Ben Kochie 已提交
56
    @login_counter ||= Gitlab::Metrics.counter(:user_session_logins_total, 'User sign in count')
K
Kevin Lyda 已提交
57 58
  end

59 60 61
  # Handle an "initial setup" state, where there's only one user, it's an admin,
  # and they require a password change.
  def check_initial_setup
62
    return unless User.limit(2).count == 1 # Count as much 2 to know if we have exactly one
63 64 65

    user = User.admins.last

66
    return unless user && user.require_password_creation_for_web?
67

J
James Lopez 已提交
68
    Users::UpdateService.new(current_user, user: user).execute do |user|
J
James Lopez 已提交
69 70
      @token = user.generate_reset_token
    end
71

J
James Lopez 已提交
72
    redirect_to edit_user_password_path(reset_password_token: @token),
73 74 75
      notice: "Please create a password for your new account."
  end

76
  def user_params
77
    params.require(:user).permit(:login, :password, :remember_me, :otp_attempt, :device_response)
78 79
  end

R
Robert Speicher 已提交
80
  def find_user
81
    if session[:otp_user_id]
R
Robert Speicher 已提交
82
      User.find(session[:otp_user_id])
83 84
    elsif user_params[:login]
      User.by_login(user_params[:login])
R
Robert Speicher 已提交
85 86
    end
  end
87

T
Toon Claes 已提交
88 89 90 91 92 93
  def stored_redirect_uri
    @redirect_to ||= stored_location_for(:redirect)
  end

  def store_redirect_uri
    redirect_uri =
94
      if request.referer.present? && (params['redirect_to_referer'] == 'yes')
T
Toon Claes 已提交
95
        URI(request.referer)
96
      else
T
Toon Claes 已提交
97
        URI(request.url)
98 99 100 101
      end

    # Prevent a 'you are already signed in' message directly after signing:
    # we should never redirect to '/users/sign_in' after signing in successfully.
T
Toon Claes 已提交
102 103 104 105 106 107 108 109 110 111 112 113
    return true if redirect_uri.path == new_user_session_path

    redirect_to = redirect_uri.to_s if redirect_allowed_to?(redirect_uri)

    @redirect_to = redirect_to
    store_location_for(:redirect, redirect_to)
  end

  # Overridden in EE
  def redirect_allowed_to?(uri)
    uri.host == Gitlab.config.gitlab.host &&
      uri.port == Gitlab.config.gitlab.port
114
  end
R
Robert Speicher 已提交
115

116
  def two_factor_enabled?
T
Toon Claes 已提交
117
    find_user&.two_factor_enabled?
118 119
  end

120 121 122 123
  def auto_sign_in_with_provider
    provider = Gitlab.config.omniauth.auto_sign_in_with_provider
    return unless provider.present?

124 125 126 127
    # If a "auto_sign_in" query parameter is set to a falsy value, don't auto sign-in.
    # Otherwise, the default is to auto sign-in.
    return if Gitlab::Utils.to_boolean(params[:auto_sign_in]) == false

128 129
    # Auto sign in with an Omniauth provider only if the standard "you need to sign-in" alert is
    # registered or no alert at all. In case of another alert (such as a blocked user), it is safer
130 131
    # to do nothing to prevent redirection loops with certain Omniauth providers.
    return unless flash[:alert].blank? || flash[:alert] == I18n.t('devise.failure.unauthenticated')
132

133
    # Prevent alert from popping up on the first page shown after authentication.
134 135
    flash[:alert] = nil

136
    redirect_to omniauth_authorize_path(:user, provider)
137 138
  end

R
Robert Speicher 已提交
139
  def valid_otp_attempt?(user)
140
    user.validate_and_consume_otp!(user_params[:otp_attempt]) ||
141
      user.invalidate_otp_backup_code!(user_params[:otp_attempt])
142
  end
V
Valery Sizov 已提交
143

144
  def log_audit_event(user, resource, options = {})
145
    Gitlab::AppLogger.info("Successful Login: username=#{resource.username} ip=#{request.remote_ip} method=#{options[:with]} admin=#{resource.admin?}")
146 147
    AuditEventService.new(user, user, options)
      .for_authentication.security_event
V
Valery Sizov 已提交
148
  end
149

150
  def log_user_activity(user)
151
    login_counter.increment
152 153 154
    Users::ActivityService.new(user, 'login').execute
  end

155 156 157
  def load_recaptcha
    Gitlab::Recaptcha.load_configurations!
  end
158 159 160 161 162 163 164 165 166 167

  def authentication_method
    if user_params[:otp_attempt]
      "two-factor"
    elsif user_params[:device_response]
      "two-factor-via-u2f-device"
    else
      "standard"
    end
  end
168
end