summaryrefslogtreecommitdiff
path: root/lib/gitlab/auth/activity.rb
blob: 988ff19619340b224d566f39117bbc28c7211bd2 (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
# frozen_string_literal: true

module Gitlab
  module Auth
    ##
    # Metrics and logging for user authentication activity.
    #
    class Activity
      extend Gitlab::Utils::StrongMemoize

      COUNTERS = {
        user_authenticated: 'Counter of successful authentication events',
        user_unauthenticated: 'Counter of authentication failures',
        user_not_found: 'Counter of 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_session_destroyed: 'Counter of user sessions being destroyed',
        user_two_factor_authenticated: 'Counter of two factor authentications',
        user_sessionless_authentication: 'Counter of sessionless authentications',
        user_blocked: 'Counter of sign in attempts when user is blocked'
      }.freeze

      def initialize(opts)
        @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
      end

      def user_authenticated!
        self.class.user_authenticated_counter_increment!

        case @opts[:message]
        when :two_factor_authenticated
          self.class.user_two_factor_authenticated_counter_increment!
        end
      end

      def user_session_override!
        self.class.user_session_override_counter_increment!

        case @opts[:message]
        when :sessionless_sign_in
          self.class.user_sessionless_authentication_counter_increment!
        end
      end

      def user_blocked!
        self.class.user_blocked_counter_increment!
      end

      def user_session_destroyed!
        self.class.user_session_destroyed_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