Skip to content

Commit

Permalink
Merge pull request #126 from plivo/jwt
Browse files Browse the repository at this point in the history
add jwt helpers
  • Loading branch information
nixonsam authored May 28, 2020
2 parents 6073b7f + 305b348 commit f216faf
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Change Log

## [4.8.0](https://github.com/plivo/plivo-ruby/releases/tag/v4.8.0) (2020-05-28)
- Add JWT helper functions.

## [4.7.1](https://github.com/plivo/plivo-ruby/releases/tag/v4.7.1) (2020-05-06)
- Fix Send MMS with existing media_ids.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ The Plivo Ruby SDK makes it simpler to integrate communications into your Ruby a
Add this line to your application's Gemfile:

```ruby
gem 'plivo', '>= 4.7.1'
gem 'plivo', '>= 4.8.0'
```

And then execute:
Expand Down
23 changes: 23 additions & 0 deletions examples/jwt.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require 'rubygems'
require 'plivo'

include Plivo

AUTH_ID = 'MADADADADADADADADADA'
AUTH_TOKEN = 'AUTH_TOKEN'

begin
acctkn = Plivo::Token::AccessToken.new(
AUTH_ID,
AUTH_TOKEN,
'{username}',
'{uid}'
)
# update token validity (from, lifetime, till)
acctkn.update_validity(Time.now, 300)
# add voice grants (incoming, outgoing)
acctkn.add_voice_grants(Plivo::Token::VoiceGrants.new(true, true))
puts acctkn.to_jwt
rescue ValidationError => e
puts 'Exception: ' + e.message
end
1 change: 1 addition & 0 deletions lib/plivo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
require_relative 'plivo/resources'
require_relative 'plivo/rest_client'
require_relative 'plivo/xml'
require_relative 'plivo/jwt'
require_relative 'plivo/phlo_client'
require_relative 'plivo/base_client'

Expand Down
120 changes: 120 additions & 0 deletions lib/plivo/jwt.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# frozen_string_literal: true

require 'openssl'
require 'uri'
require 'base64'
require 'date'
require 'jwt'

module Plivo
module Token
include Utils

class VoiceGrants
attr_reader :incoming_allow, :outgoing_allow

def initialize(incoming = nil, outgoing = nil)
Utils.valid_param?(:incoming, incoming, [TrueClass, FalseClass], false)
Utils.valid_param?(:outgoing, outgoing, [TrueClass, FalseClass], false)
@incoming_allow = incoming
@outgoing_allow = outgoing
end

def to_hash
hash = {}
instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
hash
end
end

class AccessToken
attr_reader :uid, :username, :valid_from, :lifetime, :grants
def initialize(auth_id = nil, auth_token = nil, username = nil, uid = nil)
configure_credentials(auth_id, auth_token)
Utils.valid_param?(:username, username, [String, Symbol], true)
@username = username

Utils.valid_param?(:uid, uid, [String, Symbol], false)
uid ||= username + '-' + Time.now.to_i
@uid = uid
update_validity
end

def update_validity(valid_from = nil, lifetime = nil, valid_till = nil)
Utils.valid_param?(:valid_from, valid_from, [Time, Integer], false)
Utils.valid_param?(:lifetime, lifetime, [Integer], false)
Utils.valid_param?(:valid_till, valid_till, [Time, Integer], false)

if valid_from.nil?
@lifetime = lifetime || 84_600
@valid_from = if valid_till.nil?
Time.now
else
Time.at(valid_till.to_i - @lifetime).utc
end

elsif valid_till.nil?
@lifetime = lifetime || 84_600
@valid_from = valid_from
else
unless lifetime.nil?
raise Exceptions::ValidationError, 'use any 2 of valid_from, lifetime and valid_till'
end

@valid_from = valid_from
@lifetime = valid_till.to_i - valid_from.to_i
end

return unless @lifetime < 180 || @lifetime > 84_600

raise Exceptions::ValidationError, 'validity out of [180, 84600] seconds'
end

def auth_id
@auth_credentials[:auth_id]
end

def add_voice_grants(grants)
Utils.valid_param?(:grants, grants, [VoiceGrants], true)
@grants = grants
end

def to_jwt
payload = {
jti: uid,
sub: username,
iss: auth_id,
nbf: valid_from.to_i,
exp: valid_from.to_i + lifetime,
grants: {
voice: grants.to_hash || {}
}
}
JWT.encode payload, key, 'HS256', {typ: 'JWT', cty: 'plivo;v=1'}
end

private

def key
@auth_credentials[:auth_token]
end

def configure_credentials(auth_id, auth_token)
# Fetches and sets the right credentials
auth_id ||= ENV['PLIVO_AUTH_ID']
auth_token ||= ENV['PLIVO_AUTH_TOKEN']

raise Exceptions::AuthenticationError, 'Couldn\'t find auth credentials' unless
auth_id && auth_token

raise Exceptions::AuthenticationError, "Invalid auth_id: '#{auth_id}'" unless
Utils.valid_account?(auth_id)

@auth_credentials = {
auth_id: auth_id,
auth_token: auth_token
}
end
end
end
end
2 changes: 1 addition & 1 deletion lib/plivo/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Plivo
VERSION = '4.7.1'.freeze
VERSION = '4.8.0'.freeze
end
1 change: 1 addition & 0 deletions plivo.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Gem::Specification.new do |spec|
spec.add_dependency 'faraday', '~> 0.9'
spec.add_dependency 'faraday_middleware', '~> 0.12.2'
spec.add_dependency 'htmlentities'
spec.add_dependency 'jwt'

spec.add_development_dependency 'bundler', '>= 1.14', '<3.0'
spec.add_development_dependency 'rake', '~> 10.0'
Expand Down
16 changes: 16 additions & 0 deletions spec/jwt_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require 'rspec'
require 'plivo'

describe 'Jwt test' do
it 'should succeed' do
acctkn = Plivo::Token::AccessToken.new(
'MADADADADADADADADADA',
'qwerty',
'username',
'username-12345'
)
acctkn.update_validity(12121212, nil, 12121512)
acctkn.add_voice_grants(Plivo::Token::VoiceGrants.new(true, true))
expect(acctkn.to_jwt).to eql('eyJ0eXAiOiJKV1QiLCJjdHkiOiJwbGl2bzt2PTEiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJ1c2VybmFtZS0xMjM0NSIsInN1YiI6InVzZXJuYW1lIiwiaXNzIjoiTUFEQURBREFEQURBREFEQURBREEiLCJuYmYiOjEyMTIxMjEyLCJleHAiOjEyMTIxNTEyLCJncmFudHMiOnsidm9pY2UiOnsiaW5jb21pbmdfYWxsb3ciOnRydWUsIm91dGdvaW5nX2FsbG93Ijp0cnVlfX19.9DchOxw0llIy5bOrXCcbQ5NVQoy2S5480zGzihPK9l8')
end
end

0 comments on commit f216faf

Please sign in to comment.