Sha256: a365da7eb9b9013b707f047da3aa37f15e7f72c80383e80931b19f1fa3f5f0ea

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

require 'kingsman/hooks/trackable'

module Kingsman
  module Models
    # Track information about your user sign in. It tracks the following columns:
    #
    # * sign_in_count      - Increased every time a sign in is made (by form, openid, oauth)
    # * current_sign_in_at - A timestamp updated when the user signs in
    # * last_sign_in_at    - Holds the timestamp of the previous sign in
    # * current_sign_in_ip - The remote ip updated when the user sign in
    # * last_sign_in_ip    - Holds the remote ip of the previous sign in
    #
    module Trackable
      def self.required_fields(klass)
        [:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count]
      end

      def update_tracked_fields(request)
        old_current, new_current = self.current_sign_in_at, Time.now.utc
        self.last_sign_in_at     = old_current || new_current
        self.current_sign_in_at  = new_current

        old_current, new_current = self.current_sign_in_ip, extract_ip_from(request)
        self.last_sign_in_ip     = old_current || new_current
        self.current_sign_in_ip  = new_current

        self.sign_in_count ||= 0
        self.sign_in_count += 1
      end

      def update_tracked_fields!(request)
        # We have to check if the user is already persisted before running
        # `save` here because invalid users can be saved if we don't.
        # See https://github.com/heartcombo/kingsman/issues/4673 for more details.
        return if new_record?

        update_tracked_fields(request)
        save(validate: false)
      end

      protected

      def extract_ip_from(request)
        request.remote_ip
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
kingsman-0.1.1 lib/kingsman/models/trackable.rb
kingsman-0.1.0 lib/kingsman/models/trackable.rb