httr authentication login/password in "xtb" API - r

I need to authenticate and get prices using this api
I have no experience with api so my attempt to login gives an error
login <- "vikov98261#jesdoit.com"
pass <- "QazQaz123"
library(httr)
resp <- POST("xapi.xtb.com",
body=list(userId = login,
password = pass) )
Error in curl::curl_fetch_memory(url, handle = handle) :
Failed to connect to xapi.xtb.com port 80: Timed out
Can someone show me how to do it right.
I would like an example of how the login request works.
And also I would like an example of how to get the prices of any currency

Their API documentation uses WebSocket syntax, so I assume xapi.xtb.com may only be used by the clients. I, for once, only managed to get WebSocket to work.
In order to make this work in r you would need a WebSocket client library for r, such as websocket. Once you have that:
1. Define connection
ws <- WebSocket$new("wss://ws.xtb.com/demo")
2. Log in
WebSocket clients work with events. The 'open' event is generated once the connection is established and the 'message' events are generated when messages are received. You need to write handlers for them to orchestrate the way you want to use the XTB API.
The first event will be 'open', so use that to send the login command.
ws$onOpen(function(event) {
ws$send({
"command":"login",
"arguments": {
"userId":"1000",
"password":"PASSWORD",
"appId":"test",
"appName":"test"
}
})
})
3. Your logic
The response to your login command will trigger a 'message' event, the output of which you will need to handle in your code.
ws$onMessage( <your-code-goes-here> )
The easiest way would probably be to send new commands based on what is the structure of the received message, although it can get really complicated with many commands.
4. Connect
After all handles have been defined, don't forget to connect.
ws$connect()

Related

Error in Oauth2.0 authentication in R using HTTR (failed to connect: connection refused)

I am trying to create a simple app (in R) using GroupMe's API, which utilizes OAuth2.0. The documentation can be found here. However, I'm getting stuck on the first step of authentication/token generation for a user. See below for my code and the response I get:
access_key = ****
client_id = ****
gendpoint <- oauth_endpoint(
authorize = glue("https://oauth.groupme.com/oauth/login_dialog?client_id={client_id}"),
access = glue("http://localhost:1410/?access_token={access_key}")
)
gapp <- oauth_app(
"pingme",
key = client_id,
secret = access_key
)
t <- oauth2.0_token(
endpoint = gendpoint,
app = gapp
)
The above code is sufficient to bring in the login page, which presumably allows me to enter my credentials to obtain a token. However, when I enter my credentials, I get the following error message in R:
Authentication complete.
Error in curl::curl_fetch_memory(url, handle = handle) :
Failed to connect to localhost port 1410: Connection refused
So it looks like my authentication/login credentials worked, but somewhere an error prevented me from actually generating the token.
Could someone help me with this? This is my first time using the OAuth2.0 framework so I'm very confused. Thanks in advance!

Is there a mistake in the token validation documentation? Or am I getting this wrong?

In this section of the sign-in guide,
https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library,
There is this code snippet
# Specify the CLIENT_ID of the app that accesses the backend:
id_token.verify_oauth2_token(token, requests.Request(),CLIENT_ID)
This correctly validates the token when I pass my server's client ID, but fails when I pass the android app's client it.
However, the comment suggests that it should be the android app's client ID that should get passed here! And that also makes more sense from a security perspective.
Further down, I can find the following Python code sample
# Or, if multiple clients access the backend server:
# idinfo = id_token.verify_oauth2_token(token, requests.Request())
# if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
# raise ValueError('Could not verify audience.')
I have played around a bit and it seems to me that idinfo["aud"] key carries the client ID of the server, where as idinfo["azp"] carries the client ID of the client.
If I understand it right, in this line we are supposed to verify the client id of the android app client!
So it should read:
if idinfo['azp'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
raise ValueError('Could not verify audience.')
I feel like I must be getting something wrong here, but what is it?

SSE with Leshan LWM2M Demo Server

I am trying to do an http api that interact with a Leshan Demo Server.
I was trying to handle the OBSERVE in LWM2M, but I need to handle the notification with http.
I discovered that leshan notify using SSE. So I was trying to implement the sse client in python using requests and sseclient.
This is my code:
response= requests.post(url_request , "format=TLV" , stream= True)
client = sseclient.SSEClient(response)
for event in client.events():
print(json.loads(event.data))
I tried to run my script but it seems like the stream is not opening and it close immediately without waiting for the answer of the server, even if requests by default implement keep_alive for TCP connection under HTTP and the stream is True.
Does someone know why?
Reading the sseclient documentation, the correct way so use SSEClient seems to be :
from sseclient import SSEClient
messages = SSEClient('http://example.com/sse_stream/')
for msg in messages:
do_something_useful(msg)
Reading the answer on Leshan Github, the stream URL for Leshan Server Demo seems to be http://your.leshan.server.org/event?ep=your_device_endpoint_name
So I tried that :
from sseclient import SSEClient
messages = SSEClient('http://localhost:8080/event?ep=my_device')
for msg in messages:
print (msg.event, msg.data)
And it works for me 🎉 ! Getting this kind of results when I observe the temperature instance of Leshan Client Demo :
(u'NOTIFICATION', u'{"ep":"my_device","res":"/3303/0","val":{"id":0,"resources":[{"id":5601,"value":-18.9},{"id":5602,"value":31.2},{"id":5700,"value":-18.4},{"id":5701,"value":"cel"}]}}')
(u'COAPLOG', u'{"timestamp":1592296453808,"incoming":true,"type":"CON","code":"POST","mId":29886,"token":"889372029F81C124","options":"Uri-Path: \\"rd\\", \\"reWfKIgPYD\\"","ep":"my_device"}')
(u'COAPLOG', u'{"timestamp":1592296453809,"incoming":false,"type":"ACK","code":"2.04","mId":29886,"token":"889372029F81C124","ep":"my_device"}')
(u'UPDATED', u'{"registration":{"endpoint":"my_device","registrationId":"reWfKIgPYD","registrationDate":"2020-06-16T10:02:25+02:00","lastUpdate":"2020-06-16T10:34:13+02:00","address":"127.0.0.1:44400","lwM2mVersion":"1.0","lifetime":300,"bindingMode":"U","rootPath":"/","objectLinks":[{"url":"/","attributes":{"rt":"\\"oma.lwm2m\\""}},{"url":"/1/0","attributes":{}},{"url":"/3/0","attributes":{}},{"url":"/6/0","attributes":{}},{"url":"/3303/0","attributes":{}}],"secure":false,"additionalRegistrationAttributes":{}},"update":{"registrationId":"reWfKIgPYD","identity":{"peerAddress":{}},"additionalAttributes":{}}}')
(u'COAPLOG', u'{"timestamp":1592296455150,"incoming":true,"type":"NON","code":"2.05","mId":29887,"token":"3998C5DE2588F835","options":"Content-Format: \\"application/vnd.oma.lwm2m+tlv\\" - Observe: 2979","payload":"Hex:e3164563656ce8164408c03199999999999ae815e108c032e66666666666e815e208403f333333333333","ep":"my_device"}')
If you are interested by notification only, just add a if msg.event == 'NOTIFICATION': block.

Why can't I defer sending a message for a one-way client

What is the rationale behind the following exception when trying to Defer the sending of a message on a one-way client:
System.InvalidOperationException "Cannot use ourselves as timeout manager because we're a one-way client"
A one-way client is a Rebus client that is not capable of receiving messages, so it has no input queue.
The way await bus.Defer(...) works, is by sending a message with some special headers to a "timeout manager", which by default is the endpoint that defers the message.
But since a one-way client has no input queue, it has no place to send the deferred message to.
You can make a one-way client defer messages by configuring an external timeout manager like this:
Configure.With(...)
.(...)
.Options(o => o.UseExternalTimeoutManager(anotherQueue))
.Start();
which will then cause the client to send the deferred message to that queue.
Moreover, you would have to manually set the rbs2-defer-recipient header to some other input queue, so that the timeout manager knows where to send the message when it is time to be consumed(*).
I hope that explains it :) please let me know if it is not clear.
*) This is actually not the case with Rebus 4, because bus.Defer uses the normal endpoint mappings to route messages.
If Rebus.AzureServiceBus is used there is more simple (or hacky) way to send delayed messages.
You have to specify 2 headers: rbs2-deferred-until and rbs2-defer-recipient and call Publish method like in the example.
var deferredUntil = DateTimeOffset.UtcNow.AddDays(1);
var headers = new Dictionary<string, string>();
headers.Add(Headers.DeferredUntil, deferredUntil.ToString("O", CultureInfo.InvariantCulture));
headers.Add(Headers.DeferredRecipient, #"Rebus requires this ¯\_(ツ)_/¯");
await bus.Publish(new SomeMessage(), headers);
Note: rbs2-defer-recipient is required by Rebus so any dummy values are okay.
Be careful, it looks like a workaround so it may not work after Rebus.AzureServiceBus update. It works for me in 5.0.1.

External use of Meteor method? (to receive SMS from Nexmo)

In my Meteor application I want to receive text messages through Nexmo. How do I create the callback function? I'm thinking of something like
Meteor.methods
'receive_sms': (values) ->
console.log values
But http://hitchticker.meteor.com/receive_sms doesn't really work of course. I can see my method is working when I do Meteor.call('receive_sms', 'test') in my browser, but the network debugger is not really giving me a lot of useful information. The Meteor docs aren't very helpful either.
How do I access the method from elsewhere?
Iron Router and then server side routes. Something like:
Router.route('/download/:file', function () {
// NodeJS request object
var request = this.request;
// NodeJS response object
var response = this.response;
this.response.end('file download content\n');
}, {where: 'server'});
In order to receive sms from nexmo you should make the callback (incoming url) available over the internet. Nexmo won’t be able to call localhost to send the incoming sms messages.
Here are some resources to tunnel request over the internet to localhost.
https://ngrok.com/
http://localtunnel.me/
https://pagekite.net/

Resources