Authenticate a third-party application with Ruby on Rails
When you need to use the Vantage API and Ruby on Rails to implement third-party authentication, you can use this example to help you.
About this task
Ruby is the base of the Ruby on Rails application development framework. Ruby is an
open source, general-purpose programming language. This example includes
test.rb
and api_client.rb
example Ruby source
code files that together show how to authorize your application and then locate and
select the organization associated with this application programming interface (API)
key.
Procedure
-
In the terminal, enter your command. For example:
require_relative './api_client.rb' ENV['VANTAGE_KEY_NAME'] = 'AK123456' ENV['VANTAGE_KEY_TOKEN'] = 'abcabcabc' ENV['VANTAGE_DOMAIN'] = 'https://VANTAGE_URL' client = Vantage::ApiClient.new acme_id = client.get_organization_id 'Acme' client.set_active_organization acme_id sensors = client.list path: 'sensors' puts sensors.count
-
The above test.rb example requires api_client.rb:
require 'httparty' module Vantage class ApiClient def initialize authenticate end def authenticate auth = HTTParty.post("#{api_endpoint}/keys/sign_in", body: { key_name: ENV['KEY_NAME'], key_token: ENV['KEY_TOKEN'] }. to_json, headers: { 'Content-Type': 'application/json' }) raise StandardError, 'no auth token returned' unless auth. headers['authorization'] @token = auth.headers['authorization'] @headers = {} end def api_endpoint "https://#{ENV['VANTAGE_DOMAIN']}/api/v1" end def headers @headers.merge({ 'Authorization': @token, 'Content-Type': 'application/json' }) end def get_organization_id(organization_name) org_id = nil list(path: 'admin/organizations').each do |org| org_id = org['id'] if organization_name == org['attributes']['name'] end org_id end def set_active_organization(id) @headers = { 'Vantage-Org': id } end def list(path:) resp = HTTParty.get("#{api_endpoint}/#{path}", headers: headers) resp['data'] end end end