Class: SelfSDK::JwtService

Inherits:
Object
  • Object
show all
Defined in:
lib/jwt_service.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id, app_key) ⇒ JwtService

Jwt initializer

Parameters:

  • app_id (string)

    the app id.

  • app_key (string)

    the app api key provided by developer portal.



14
15
16
17
# File 'lib/jwt_service.rb', line 14

def initialize(app_id, app_key)
  @id = app_id
  @key = app_key
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



8
9
10
# File 'lib/jwt_service.rb', line 8

def id
  @id
end

#keyObject (readonly)

Returns the value of attribute key.



8
9
10
# File 'lib/jwt_service.rb', line 8

def key
  @key
end

Instance Method Details

#auth_tokenObject

Generates the auth_token based on the app’s private key.



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/jwt_service.rb', line 72

def auth_token
  payload = header + "." + encode({
    jti: SecureRandom.uuid,
    cid: SecureRandom.uuid,
    typ: 'auth.token',
    iat: (SelfSDK::Time.now - 5).to_i,
    exp: (SelfSDK::Time.now + 60).to_i,
    iss: @id,
    sub: @id}.to_json)
  signature = sign(payload)
  "#{payload}.#{signature}"
end

#decode(input) ⇒ Object

Base64 decodes the input string

Parameters:

  • input (string)

    the string to be decoded.



49
50
51
# File 'lib/jwt_service.rb', line 49

def decode(input)
  Base64.urlsafe_decode64(input)
end

#encode(input) ⇒ Object

Encodes the input with base64

Parameters:

  • input (string)

    the string to be encoded.



42
43
44
# File 'lib/jwt_service.rb', line 42

def encode(input)
  Base64.urlsafe_encode64(input, padding: false)
end

#parse(input) ⇒ Object



35
36
37
# File 'lib/jwt_service.rb', line 35

def parse(input)
  JSON.parse(input, symbolize_names: true)
end

#prepare(input) ⇒ Object

Prepares a jwt object based on an input

Parameters:

  • input (string)

    input to be prepared



22
23
24
# File 'lib/jwt_service.rb', line 22

def prepare(input)
  signed(input).to_json
end

#sign(input) ⇒ Object

Signs the given input with the configured Ed25519 key.

Parameters:

  • input (string)

    the string to be signed.



56
57
58
59
60
# File 'lib/jwt_service.rb', line 56

def sign(input)
  signing_key = Ed25519::SigningKey.new(decode(@key))
  signature = signing_key.sign(input)
  encode(signature)
end

#signed(input) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/jwt_service.rb', line 26

def signed(input)
  payload = encode(input.to_json)
  {
    payload: payload,
    protected: header,
    signature: sign("#{header}.#{payload}")
  }
end

#verify(payload, key) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/jwt_service.rb', line 62

def verify(payload, key)
  verify_key = Ed25519::VerifyKey.new(decode(key))
  if verify_key.verify(decode(payload[:signature]), "#{payload[:protected]}.#{payload[:payload]}")
    return true
  end
rescue StandardError
  false
end