summaryrefslogtreecommitdiff
path: root/lib/gitlab/auth/activity.rb
blob: 334c4794ea71ac9005b13c7604c876d923cd0928 (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
module Gitlab
  module Auth
    ##
    # Metrics and logging for user authentication activity.
    #
    class Activity
      extend Gitlab::Utils::StrongMemoize

      COUNTERS = {
        user_authenticated: 'Counter of total successful authentication events',
        user_unauthenticated: 'Counter of total authentication failures',
        user_not_found: 'Counter of total failed log-ins when user is unknown',
        user_password_invalid: 'Counter of failed log-ins with invalid password',
        user_session_override: 'Counter of manual log-ins and sessions overrides',
        user_two_factor_authenticated: 'Counter of two factor authentications',
        user_blocked: 'Counter of total sign in attempts when user is blocked',
        user_signed_out: 'Counter of total user sign out events'
      }.freeze

      def initialize(user, opts)
        @user = user
        @opts = opts
      end

      def user_authentication_failed!
        self.class.user_unauthenticated_counter_increment!

        case @opts[:message]
        when :not_found_in_database
          self.class.user_not_found_counter_increment!
        when :invalid
          self.class.user_password_invalid_counter_increment!
        end

        if @user.present? && @user.blocked?
          self.class.user_blocked_counter_increment!
        end
      end

      def user_authenticated!
        self.class.user_authenticated_counter_increment!
      end

      def user_session_override!
        self.class.user_authenticated_counter_increment!
        self.class.user_session_override_counter_increment!

        if @opts[:message] == :two_factor_authenticated
          self.class.user_two_factor_authenticated_counter_increment!
        end
      end

      def user_signed_out!
        self.class.user_signed_out_counter_increment!
      end

      def self.each_counter
        COUNTERS.each_pair do |metric, description|
          yield "#{metric}_counter", metric, description
        end
      end

      each_counter do |counter, metric, description|
        define_singleton_method(counter) do
          strong_memoize(counter) do
            Gitlab::Metrics.counter("gitlab_auth_#{metric}_total".to_sym, description)
          end
        end

        define_singleton_method("#{counter}_increment!") do
          public_send(counter).increment # rubocop:disable GitlabSecurity/PublicSend
        end
      end
    end
  end
end