From 3bb6715e871d5d943d41d510222f083772d91b48 Mon Sep 17 00:00:00 2001 From: ADandyGuyInSpace <61507189+ADandyGuyInSpace@users.noreply.github.com> Date: Fri, 18 Oct 2024 11:21:42 -0500 Subject: [PATCH] Handle jwt response (#96) * feat: Handle JWT responses by wrapping them in a JSON object * fix: Handle JWT responses to prevent method_missing error in TelnyxResponse * feat: Update create method definition for token action in TelephonyCredential * bump version --- VERSION | 2 +- lib/telnyx/telephony_credential.rb | 11 ++++++----- lib/telnyx/telnyx_response.rb | 14 +++++++++++++- lib/telnyx/version.rb | 2 +- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/VERSION b/VERSION index 75a22a2..b0f2dcb 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.0.3 +3.0.4 diff --git a/lib/telnyx/telephony_credential.rb b/lib/telnyx/telephony_credential.rb index 7a6ec6e..8153185 100644 --- a/lib/telnyx/telephony_credential.rb +++ b/lib/telnyx/telephony_credential.rb @@ -16,12 +16,13 @@ class TelephonyCredential < APIResource instance_methods: { create: action } end - %w[token].each do |action| - nested_resource_class_methods action, - path: %W[#{action}], - operations: [:create], - instance_methods: { create: action } + # Manually create JSON response object from JWT when calling token + def create_token(params = {}, opts = {}) + url = "#{resource_url}/token" + resp, opts = request(:post, url, params, opts) + Util.convert_to_telnyx_object(resp.data, opts) end + # Additional action to list tags def self.tags(params = {}, opts = {}) opts = Util.normalize_opts(opts) diff --git a/lib/telnyx/telnyx_response.rb b/lib/telnyx/telnyx_response.rb index f399003..0dff546 100644 --- a/lib/telnyx/telnyx_response.rb +++ b/lib/telnyx/telnyx_response.rb @@ -26,7 +26,7 @@ class TelnyxResponse # This may throw JSON::ParserError if the response body is not valid JSON. def self.from_faraday_hash(http_resp) resp = TelnyxResponse.new - resp.data = JSON.parse(preprocess_response(http_resp[:body]), symbolize_names: true) + resp.data = parse_response_body(http_resp[:body]) resp.http_body = http_resp[:body] resp.http_headers = http_resp[:headers] resp.http_status = http_resp[:status] @@ -34,6 +34,18 @@ def self.from_faraday_hash(http_resp) resp end + def self.parse_response_body(body) + if jwt_format?(body) + { token: body } + else + JSON.parse(preprocess_response(body), symbolize_names: true) + end + end + + def self.jwt_format?(body) + body.count(".") == 2 && body.split(".").all? { |segment| segment.match?(/\A[a-zA-Z0-9_-]+\z/) } + end + # Initializes a TelnyxResponse object from a Faraday HTTP response object. # # This may throw JSON::ParserError if the response body is not valid JSON. diff --git a/lib/telnyx/version.rb b/lib/telnyx/version.rb index 26107e8..9c83c59 100644 --- a/lib/telnyx/version.rb +++ b/lib/telnyx/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Telnyx - VERSION = "3.0.3".freeze + VERSION = "3.0.4".freeze end