Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
fortinet / lib / fortinet.rb
Size: Mime:
# frozen_string_literal: true

require 'fortinet/version'
require 'json'
require 'rest-client'

# Module for interacting with Fortigate firewalls
module Fortinet
  @@debug = false # rubocop:disable Style/ClassVars

  Dir[File.join(__dir__, 'fortinet', '*.rb')].sort.each { |file| require file }

  def self.execute_login(server, username, password)
    RestClient::Request.execute(
      method: :post,
      url: "https://#{server}/logincheck",
      payload: {
        username: username,
        secretkey: password
      },
      verify_ssl: false
    )
  end

  def self.login(server, username, password)
    response = execute_login(server, username, password)

    raise 'Authentication failure' if response.code.to_s != '200'

    @@server = server # rubocop:disable Style/ClassVars
    @@username = username # rubocop:disable Style/ClassVars
    @@password = password # rubocop:disable Style/ClassVars
    @@cookies = response.cookies # rubocop:disable Style/ClassVars
  end

  def self.logout
    self.do('post', '/logout', {}, not_json: true)
  end

  def self.csrf_token
    cookie_key = @@cookies.keys.find { |c| c.start_with?('ccsrftoken') }

    raise StandardError, 'Could not locate CSRF token in cookies' unless cookie_key

    @@cookies[cookie_key]
  end

  def self.execute_rest_request(action, url, payload) # rubocop:disable Metrics/MethodLength
    RestClient::Request.execute(
      method: action.to_sym,
      url: "https://#{@@server}#{url}",
      cookies: @@cookies,
      payload: payload.to_json,
      headers: {
        'Content-Type' => 'application/json',
        'X-CSRFTOKEN' => csrf_token
      },
      verify_ssl: false
    )
  end

  def self.do(action, url, payload = {}, not_json: false)
    puts "[FortinetDo!] #{action} #{url} #{payload}" if @@debug

    raise StandardError, 'Not logged in' unless defined?(@@cookies)

    begin
      response = execute_rest_request(action, url, payload)
    rescue RestClient::Unauthorized
      warn 'Session expired, logging in'
      login(@@server, @@username, @@password)
      response = execute_rest_request(action, url, payload)
    end

    return nil if not_json

    JSON.parse(response)
  end

  def self.debug=(value)
    @@debug = value # rubocop:disable Style/ClassVars
  end
end