I work on a domain management software through the OVH's API.
I use nodejs and node-webkit and I downloaded the official Node.js wrapper for OVH.
Then, I followed the documentation here: https://www.npmjs.com/package/ovh and here: https://eu.api.ovh.com/g934.first_step_with_api, and I came with the following code:
// set the ovh object with the right configuration
var ovh = require('ovh')({
endpoint: 'ovh-eu',
appKey: 'APP_KEY', // replace it with my key
appSecret: 'APP_SECRET' // replace it with my key
});
ovh.request('POST', '/auth/credential', {
// set access rules
'accessRules': [
{'method': 'GET', 'path': '/*'},
{'method': 'POST', 'path': '/*'},
{'method': 'PUT', 'path': '/*'},
{'method': 'DELETE', 'path': '/*'},
]
}, function (error, credential) {
// print the error if the request failed, else, print the response
console.log(error || credential);
// set the consumerKey in the ovh object
ovh.consumerKey = credential.consumerKey;
// connect on the credential.validationUrl to validate the consumerKey
console.log(credential.validationUrl);
testMe();
});
function testMe() {
/*
This fonction test a request every second
to check if the user connected himself
*/
ovh.requestPromised('GET', '/me')
.then (function (me) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
}
)
.catch (function (err) {
console.log(err);
// while the user is not connected, retry the request
setTimeout(testMe, 1000);
}
);
}
Well, when I execute this, everything is fine until I try to connect through the url, the testMe function keeps telling me an error and I don't get the welcome message.
In order to fix my problem, I tried to use different way to write my code and even checked in OVH's module sources if the signature was right before and after hashing, but it all seems to be good...
If someone already had this issue or if anybody see a error in my code, I would really appreciate your help. Thanks
you've got a syntax error :
then (function (response) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
})
try this instead (renamed the parameter):
then (function (me) {
// if the user is connected, tell him welcome
console.log('Welcome ' + me.firstname);
})
Anyway, it it doesn't work properly please tell us the error you are getting.
Related
I am trying to stub out a route using cypress 5.2. I have a simple function to do that:
function mockAlertsResponses(){
cy.route({
method: "GET",
url: "/api/polling/alerts/statistics*",
response: {
total: 2,
...
}
});
}
In one set of tests, this works just fine:
describe("admin and read only permissions", () => {
it ("all action bar items are enabled with admin permissions", () => {
cy.login("user", "password");
mockAlertsResponses();
// Click alert to enable all buttons
cy.get("#1-checkbox").click()
cy.get("#mark-alert-button").should("be.enabled");
cy.get("#delete-alert-button").should("be.enabled");
});
// ... a few more similar tests
});
However, in another set of tests, I use the same function:
it("Logs in and out", () => {
cy.login("username", "password");
mockAlertsResponses()
cy.get("#vine-appbar").should("be.visible");
cy.get("#info-button").click();
cy.get("#info-menu-logout").click();
cy.get("#login-button");
cy.get("#vine-appbar").should("not.be.visible");
});
In this second set of tests, the routes are not stubbing properly, leading to errors and test failures. Here, you can see the route is not stubbed, but rather throws a 500 error:
I'm not sure what could be interfering here. I'm a bit new to cypress and I'm not even sure where to begin debugging this. Might the cy.server calls be interfering? Please let me know what more information we'd need to figure out why one set of stubs works and another doesn't.
If you're wondering, the login function has a call to cy.server and has its own cy.route as well:
Cypress.Commands.add("login", (username, password, admin = true) => {
const response = admin ? <jwt1> : <jwt2>
cy.server();
cy.route({
method: "POST",
url: "/api/login",
response
});
cy.visit("/logout");
cy.visit("/");
cy.wait(100);
cy.get("#login-error").should("not.be.visible");
cy.get("#login-username").type(username);
cy.get("#login-password").type(password);
cy.get("#login-button").click();
});
I am trying to develop a bot for FB Messenger and I'm always getting stuck with their documentation. Currently, I tried to add a Greeting Text and a Get_Started button in JavaScript, so I will be able to modify it easily. It seems like most of their documentation is in PHP or they just telling you to add it by sending a POST request using CURL, which worked for me, but again, it's not so modular.
I can't find proper documentation in JavaScript. and the only one is this:
https://www.techiediaries.com/build-messenger-bot-nodejs/
But I can't find the place where you actually call the greeting or get started functions.
there is also this https://github.com/fbsamples/original-coast-clothing
but I still can't find where they trigger the Greetings and the Get_Started postbacks. Only the json file where they store it /locales/en_US.json "profile".
My code currently has
// Accepts POST requests at /webhook endpoint
app.post('/webhook', (req, res) => {
// Parse the request body from the POST
let body = req.body;
// Check the webhook event is from a Page subscription
if (body.object === 'page') {
// Iterate over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {
// Get the webhook event. entry.messaging is an array, but
// will only ever contain one event, so we get index 0
let webhook_event = entry.messaging[0];
console.log(webhook_event);
// Get the sender PSID
let sender_psid = webhook_event.sender.id;
console.log('Sender PSID: ' + sender_psid);
// Check if the event is a message or postback and
// pass the event to the appropriate handler function
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
}
});
// Return a '200 OK' response to all events
res.status(200).send('EVENT_RECEIVED');
} else {
// Return a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
function setupGreetingText(res){
var messageData = {
"greeting":[
{
"locale":"default",
"text":"Greeting text for default local !"
}, {
"locale":"en_US",
"text":"Greeting text for en_US local !"
}
]};
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": 'POST',
"headers": {'Content-Type': 'application/json'},
"form": messageData
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
res.send(body);
} else {
// TODO: Handle errors
res.send(body);
}
});
}
but I still dont know how to trigger it.
Examples on the documentation look like this. This is how you break it down. Final result can be found below.
curl -X POST -H "Content-Type: application/json" -d '{
"get_started": {"payload": "<postback_payload>"}
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>"
Third word is the type of request you'll send and should be defined inside the method property.
Between the curly braces, is how the content inside the json property should be formatted.
The link on the last line is the link you should provide to the uri property minus the query part ?access_token=<PAGE_ACCESS_TOKEN>
SendAPI's uri is https://graph.facebook.com/v8.0/me/messages (you're using this)
MessengerProfileAPI's uri is https://graph.facebook.com/v2.6/me/messenger_profile (use this instead)
In the end, your request function should look something like this:
request(
{
"uri": "https://graph.facebook.com/v2.6/me/messenger_profile",
"qs": { "access_token": process.env.PAGE_ACCESS_TOKEN },
"method": "POST",
"json": {
"get_started": {"payload": "start"}
},
},
(err) => {
if (!err) {
console.log('request sent!');
} else {
console.error("Unable to send message:" + err);
}
}
);
Even though its been almost 3 months since this question has been asked. I hope this will still come useful.
Was struggling and frustrated as you trying to implement the examples on facebook for developers documentation but I finally got to understand it after some looking and observation at other developers webhook on github.
I'm developing a SPA app in React that needs to integrate with AzureAD and the GraphAPI (implicit flow).
My question is very similar to: ADAL.js - Obtaining Microsoft Graph Access Token with id_token ... but the answer doesn't show me enough code to get me on my way.
So far, using just adal.js (v1.0.14), I can login & get an id_token, but I can't figure out how to use it to get access to make Graph API calls.
UPDATE: I know I'm correctly registered with the Azure portal, because I was able to login and get recent docs without adal.js or any lib ... just using home-made ajax calls.
Here's my code, which does the login/redirect, and then tries to get my recent docs:
// Initial setup
var adalCfg = {
instance : 'https://login.microsoftonline.com/',
tenant : 'common',
clientId : 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
postLogoutRedirectUri : window.location.origin,
extraQueryParameter : 'scope=Mail.ReadWrite+Files.Read+Files.ReadWrite+User.ReadBasic.All' // Is this the proper way to specify what resources I need access to?
};
var authContext = new Adal(adalCfg);
if(!authContext.getCachedUser()) {
authContext.login(); // redirects MS login page successfully
}
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash); // Checks if the URL fragment contains access token, id token or error_description.
if(isCallback) {
authContext.handleWindowCallback(); // extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result.
}
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST); // redirects back to /
}
// Try to get my recent docs - FAILS with InvalidAuthenticationToken error
// UDPATED authContext.acquireToken(authContext.config.clientId, function (error, token) {
authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
$.ajax({
url: 'https://graph.microsoft.com/v1.0/me/drive/recent',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['value']);
});
});
What have I got wrong?
Update 2: I changed acquireToken per Fei's answer, but now when adal silently gets an access token for my resource, it fails to pass it to my API call.
Updated code:
adalCfg.endpoints.graphApiUri = "https://graph.microsoft.com";
authContext.acquireToken(adalCfg.endpoints.graphApiUri, function (errorDesc, token, error) {
console.log('errorDesc = ' + errorDesc)
console.log('token = ' + token)
console.log('error = ' + error)
$.ajax({
url: adalCfg.endpoints.graphApiUri + '/v1.0/me/drive/recent',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['value']);
});
});
And console output:
Token not being captured
The image shows the req for a token, which appears to succeed, because the next GET contains the access_token in the hash. However, acquireToken passes a null token to my Graph API call.
However, if I manually grab the access token out of the hash, I can successfully make the Graph API call.
Why doesn't adal pass the access token to my API call? It came back and is valid.
To call the Microsoft Graph, we need to get the specific token for this resource. Based on the code you were acquire the token using the authContext.config.clientId.
If you register the app on Azure portal, to get the access token for the Microsoft Graph, you need to replace authContext.config.clientId with https://graph.microsoft.com.
And to call the REST sucessfully, we need to make sure having the enough permission. For example, to list recent files, one of the following scopes is required:Files.Read,Files.ReadWrite,Files.Read.All,Files.ReadWrite.All,Sites.Read.All,Sites.ReadWrite.All(refer here).
Update
<html>
<head>
<script src="\node_modules\jquery\dist\jquery.js"></script>
<script src="node_modules\adal-angular\lib\adal.js"></script>
</head>
<body>
<button id="login"> login</button>
<button id="clickMe">click me</button>
<script>
$(function () {
var endpoints = {
"https://graph.microsoft.com": "https://graph.microsoft.com"
};
window.config = {
tenant: 'xxxx.onmicrosoft.com',
clientId: 'xxxxxxxxxxxxxxxxx',
endpoints: endpoints
};
window.authContext = new AuthenticationContext(config);
$("#login").click(function () {
window.authContext.login();
});
$("#clickMe").click(function () {
var user = window.authContext.getCachedUser();
console.log(user);
window.authContext.acquireToken('https://graph.microsoft.com', function (error, token) {
console.log(error);
console.log(token);
$.ajax({
url: 'https://graph.microsoft.com/v1.0/me/',
headers:{'authorization':'Bearer '+ token},
type:'GET',
dataType:'json'
}).done(function(res) {
console.log(res['userPrincipalName']);
});
});
}
);
function init(){
if(window.location.hash!="")
window.authContext.handleWindowCallback(window.location.hash);
}
init();
});
</script>
</body>
</html>
The user will click on a button that will invoke the Parse Cloud function sendText()
I've tried both Live Twilio and Testing Twilio accSID and authToken
I first initialize my Twilio by:
var Twilio = require('twilio');
Twilio.initialize('accountSid', 'authToken'); //put in my corresponding <<
then I set the Parse function by:
Parse.Cloud.define('sendText', function(request, response) {
Twilio.sendSMS({
From: '+1234567890', //From Number
To: "+0987654321", //To Number
Body: "Start using Parse and Twilio!" //Message <<
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
}
It would be great to have someone tell me if something here is wrong or if there are other approaches in sending SMS through Twilio via Parse Cloud.
On the SMS Summary on Twilio, it does not even know any SMS being sent out.
Going on...
The button that calls this cloud function is:
<button type="button" class="page-scroll btn btn-xl" onclick="saveData()">CONFIRM</button>
and the js function that is called saveData() is:
function saveData() {
booking.save({
something: something,
}, {
success: function (booking) {
window.location.href = 'final.php';
Parse.Cloud.run('sendText',
{
something: something
});
},
error: function (booking, error) {
alert('Failed to save');
}
});
}
NO ERROR LOG
Twilio developer evangelist here.
You seem to be using an old Parse module which is no longer supported by us. The new module however uses a newer version of our Node module.
Some documentation for it can be found here
It also has some sample code to do what you're trying to do.
// Require and initialize the Twilio module with your credentials
var client = require('twilio')('ACCOUNT_SID', 'AUTH_TOKEN');
// Send an SMS message
client.sendSms({
to:'+0987654321',
from: '+1234567890',
body: 'Hello world!'
}, function(err, responseData) {
if (err) {
console.log(err);
} else {
console.log(responseData.from);
console.log(responseData.body);
}
}
);
I think you will find your SMS will be sent using this version of the code. Notice how the initialization is different.
Although I have verified that the file does exist and is accessible, the email that is sent attaches an empty file. I have tried 3 different ways to attach the file, all that return success from the send json response. The code I'm currently using is as follows. The rk object is simply a namespace.
console.log(call.recording);
var email = new rk.sendgrid.Email({
to: '4namlet#gmail.com',
from: rk.config.email_address,
subject: 'RoadKid Feedback',
text: 'Someone left feedback on your driver.'//,
//files: [
// {
// contentType: 'audio/mpeg',
// url: call.recording
// }
//]
});
email.addFile({
filename: 'feedback.mp3',
contentType: 'audio/mpeg',
url: call.recording
});
rk.sendgrid.send(email, function(err, json) {
if (err) { return console.error(err); }
console.log(json);
});
An example url value is:
http://api.twilio.com/2010-04-01/Accounts/AC4a36110ce12a9cd68a947c87a3a6ab36/Recordings/RE568ecf17e4960105cd131507d49e182f.mp3
Turns out Sendgrid was working fine. (thanks guys for the quick response!) It was a scoping issue. For some reason call.recording was getting clobbered or called weird or something. After the console log I added a:
var recording_url = call.recording;
and theeen...
url: recording_url
And it all worked. :-/