require 'rotp'

module Devise # :nodoc:
  module Models # :nodoc:

    module GoogleAuthenticatable

      def self.included(base) # :nodoc:
        base.extend ClassMethods

        base.class_eval do
          before_validation :assign_auth_secret, :on => :create
          include InstanceMethods
        end
      end

      module InstanceMethods # :nodoc:
        def get_qr
          decrypted_gauth_secret
        end

        def decrypted_gauth_secret
          if kms_encrypted?
            key_name, credentials = self.class.kms_key_credentials
            encrypted_secret = Base64.decode64(gauth_secret)
            ::DeviseGoogleAuthenticator::KmsService.new(credentials, key_name)
                                                   .decrypt(encrypted_secret)
          else
            gauth_secret
          end
        end

        def decrypted_one_time_reset_key
          ensure_one_time_reset_key_defined

          if kms_encrypted?
            key_name, credentials = self.class.kms_key_credentials
            encrypted_reset_key = Base64.decode64(one_time_reset_key)
            ::DeviseGoogleAuthenticator::KmsService.new(credentials, key_name)
                                                   .decrypt(encrypted_reset_key)
          else
            one_time_reset_key
          end
        end

        def set_gauth_enabled(params)
          self.update_without_password(params)
        end

        def assign_tmp
          self.update_attributes(:gauth_tmp => ROTP::Base32.random_base32(32), :gauth_tmp_datetime => DateTime.now)
          self.gauth_tmp
        end

        def validate_token(token)
          return false if self.gauth_tmp_datetime.nil?
          if self.gauth_tmp_datetime < self.class.ga_timeout.ago
            return false
          else

            valid_vals = []
            valid_vals << ROTP::TOTP.new(self.get_qr).at(Time.now)
            (1..self.class.ga_timedrift).each do |cc|
              valid_vals << ROTP::TOTP.new(self.get_qr).at(Time.now.ago(30*cc))
              valid_vals << ROTP::TOTP.new(self.get_qr).at(Time.now.in(30*cc))
            end

            if valid_vals.include?(token.to_i)
              return true
            else
              return false
            end
          end
        end

        def gauth_enabled?
          # Active_record seems to handle determining the status better this way
          if self.gauth_enabled.respond_to?("to_i")
            if self.gauth_enabled.to_i != 0
              return true
            else
              return false
            end
          # Mongoid does NOT have a .to_i for the Boolean return value, hence, we can just return it
          else
            return self.gauth_enabled
          end
        end

        def require_token?(cookie)
          if self.class.ga_remembertime.nil? || cookie.blank?
            return true
          end
          array = cookie.to_s.split ','
          if array.count != 2
            return true
          end
          last_logged_in_authentication_key = array[0]
          last_logged_in_time = array[1].to_i
          return last_logged_in_authentication_key != self.first_authentication_key || (Time.now.to_i - last_logged_in_time) > self.class.ga_remembertime.to_i
        end

        def first_authentication_key
          public_send(self.class.authentication_keys.first)
        end

        def skip_validation? request
          if self.class.ga_skip_validation_if.is_a? Proc
            case self.class.ga_skip_validation_if.arity
            when 0
              self.class.ga_skip_validation_if.call
            when 1
              self.class.ga_skip_validation_if.call self
            when 2
              self.class.ga_skip_validation_if.call self, request
            else
              raise ArgumentError.new("too many required arguments for ga_skip_validation_if (#{self.class.ga_skip_validation.if.arity} instead of 0..2)")
            end
          else
            self.class.ga_skip_validation_if
          end
        end

        def assign_one_time_reset_key
          ensure_one_time_reset_key_defined

          reset_key = rand(36**8).to_s[0...8]
          if self.class.kms_encryption_enabled?
            encrypted_reset_key =
              ::DeviseGoogleAuthenticator::KmsService.new(self.class.ga_kms_credentials,
                                                          self.class.ga_kms_key_name)
                                                     .encrypt(reset_key)
            self.gauth_secret_version = 1
            self.one_time_reset_key = Base64.encode64(encrypted_reset_key)
          else
            self.gauth_secret_version = 0
            self.one_time_reset_key = reset_key
          end
        end

        private

        def assign_auth_secret
          secret = ROTP::Base32.random_base32(64)
          if self.class.kms_encryption_enabled?
            encrypted_secret =
              ::DeviseGoogleAuthenticator::KmsService.new(self.class.ga_kms_credentials,
                                                          self.class.ga_kms_key_name)
                                                     .encrypt(secret)
            self.gauth_secret_version = 1
            self.gauth_secret = Base64.encode64(encrypted_secret)
          else
            self.gauth_secret_version = 0
            self.gauth_secret = secret
          end
        end

        def kms_encrypted?
          (gauth_secret_version || 0).positive?
        end

        def ensure_one_time_reset_key_defined
          return if has_attribute?(:one_time_reset_key)

          raise "The one_time_reset_key attribute has not been defined for the #{self.class.name} class"
        end
      end

      module ClassMethods # :nodoc:
        def find_by_gauth_tmp(gauth_tmp)
          where(gauth_tmp: gauth_tmp).first
        end

        def kms_encryption_enabled?
          ga_kms_key_name.present? && ga_kms_credentials.present?
        end

        def kms_key_credentials
          raise 'The kms key name has not been delivered' if ga_kms_key_name.blank?
          raise 'The kms credentials have not been delivered' if ga_kms_credentials.blank?

          [ga_kms_key_name, ga_kms_credentials]
        end

        ::Devise::Models.config(self, :ga_timeout, :ga_timedrift, :ga_remembertime,
                                :ga_remember_optional, :ga_appname, :ga_bypass_signup,
                                :ga_skip_validation_if, :ga_kms_key_name, :ga_kms_credentials)
      end
    end
  end
end
