Last active
October 14, 2020 18:45
-
-
Save shal/7c0b43f0cab273530760510f3f5fb9ec to your computer and use it in GitHub Desktop.
Peatio Websocket API script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# Author: Ali Shanaakh <[email protected]> | |
require 'rubygems' | |
require 'websocket-client-simple' | |
require 'active_support/all' | |
require 'jwt' | |
# Create valid JWT | |
def jwt(email, uid, level, state) | |
key = OpenSSL::PKey.read(Base64.urlsafe_decode64(ENV.fetch('JWT_PRIVATE_KEY'))) | |
payload = { | |
iat: Time.now.to_i, | |
exp: 10.minutes.from_now.to_i, | |
jti: SecureRandom.uuid, | |
sub: 'session', | |
iss: 'barong', | |
aud: ['peatio'], | |
email: email, | |
uid: uid, | |
level: level, | |
state: state | |
} | |
JWT.encode(payload, key, ENV.fetch('JWT_ALGORITHM')) | |
end | |
# | |
# Host and port of the websocket server. | |
# | |
host = ENV.fetch('WS_HOST', 'localhost') | |
port = ENV.fetch('WS_PORT', '8080') | |
payload = { | |
x: 'x', y: 'y', z: 'z', | |
email: '[email protected]' | |
} | |
# Create websocket connection. | |
ws = WebSocket::Client::Simple.connect("ws://#{host}:#{port}") | |
# Called on messaged from websocket server. | |
ws.on(:message) do |msg| | |
puts msg.data | |
end | |
# Called if connection to server has been opened. | |
ws.on(:open) do | |
# Authenticate. | |
auth = jwt('[email protected]', '[email protected]', 3, 'active') | |
msg = "{ \"jwt\": \"Bearer #{auth}\"}" | |
ws.send msg | |
end | |
# Called if connection to server has been closed. | |
ws.on(:close) do |err| | |
p err | |
exit 1 | |
end | |
# Called if any server error occured. | |
ws.on(:error) do |err| | |
p err | |
end | |
loop {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, how are you? tanks for the example!, where can I obtain the jwt private key?