Retrieving filtered messages - twilio

var accountSid = 'AC066a9b14a2a701b556491953c1827f84';
var authToken = "{{ auth_token }}";
var client = require('twilio')(accountSid, authToken);
client.messages.list(function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body);
});
});
Twilio says I can filter the messages by using From or To parameter but the document lacks the details. I want to retrieve messages that are sent from 123. How do I do it?

client.messages.list({
from: "34234234",
}, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.friendlyName);
});
});
I had to go to the API playground.

Related

Getting 400 (Bad Request) on a POST request to Strapi

I am trying to post data to my Strapi project from a Flutter app.
I made sure that the permissions are enabled for unauthenticated users.
What is wrong with my request?
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
var reviewObj = jsonEncode({
'review': usrReview,
'rating': usrRating,
});
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
The problem was that the structure of reviewObj was missing something. I had to include 'data' in it for it to work. Here is what the correct body should look like.
var reviewObj = jsonEncode({
'data': {
'review': usrReview,
'rating': usrRating,
}
});
I think this might fix you're problem! I recently ran into this same error a few days ago!
Basically you have to send the body of the POST request as a string.
Here's what it should look like!
Future saveReview(usrReview, usrRating) async {
const endpoint = 'http://localhost:1337/api/reviews';
var url = Uri.parse(endpoint);
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
// Pass the JSON data as a whole string. Then the server should parse it
var reviewObj = '{"review": $usrReview, "rating": $usrRating}';
var response = await http.post(
url,
headers: headers,
body: reviewObj,
);
print(response.statusCode);
}
Give that a try and let me know if that works!

Time triggered Azure function - Bearer token generation to call a protected API

I am trying to write an Azure function which is time triggered and runs every 10 minutes.
The function needs to call an API which expects a bearer token.
How do I generate the token? Since it is time based, I can't have a user to login and give function authorization token by signing into MS Identity platform which can be used to get the access token.
You just need to get the token by the code below in your timer trigger function:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "client_id", "<your app client id>" },
{ "scope", "<scope>" },
{ "username", "<your user name>" },
{ "password", "<your password>" },
{ "grant_type", "password" },
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
var responseString = await response.Content.ReadAsStringAsync();
Then you need to parse responseString(in json type) and use the access token in it to request your api.
Update:
Get token by client credential:
HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "client_id", "<your app client id>" },
{ "scope", "<scope>" },
{ "client_secret", "<your app client secret>" },
{ "grant_type", "client_credentials" },
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://login.microsoftonline.com/<your tenant id>/oauth2/v2.0/token", content);
var responseString = await response.Content.ReadAsStringAsync();
You can use a password grant flow but this requires you to provide user and password to your application. A better approach is to do the Auth outside of your application using device code flow.
See this repo for an example:
https://github.com/blueboxes/devicecodesample

Reg: Angular API Return data with array index "value below was evaluated just now”

i am using Angular for front end. i am using the API request to bring languages and phrases. return data is pushed into declared array variable.
```public data = [];
constructor(private http: HttpClient) {
this.getMyLang();
}
async getMyLang() {
const headers = {
headers: new HttpHeaders({
'X-API-KEY': 'xxxxxx',
})
};
const param = new FormData();
param.append('language', 'en');
await this.http.post('api url', param, headers).subscribe((data1) => {
this.data.push(data1);
});
}```
when i call this method it pushes the data. after console this variable into component am getting following results.
console Screenshot enter code here

Cortana skill authentication

I have enabled the connected service in my Cortana channel (Microsoft) and got the token to the BOT framework.
Now, I want to retrieve the user details from the token by using the registered client id and secret
Sample code in BOT framework:
var authInfo = ((Activity)context.Activity).Entities.FirstOrDefault(e => e.Type.Equals("AuthorizationToken"));
var token = authInfo.Properties["token"].ToString();
Any thoughts?
Check BotAuth out. You can retrieve the token choosing a provider:
const botauth = require("botauth");
const DropboxOAuth2Strategy = require("passport-dropbox-oauth2").Strategy;
...
// Initialize with the strategies we want to use
var auth = new botauth.BotAuthenticator(server, bot, {
secret : "something secret",
baseUrl : "https://" + WEBSITE_HOSTNAME }
);
// Configure the Dropbox authentication provider using the passport-dropbox strategy
auth.provider("dropbox",
function(options) {
return new DropboxOAuth2Strategy(
{
clientID : DROPBOX_APP_ID,
clientSecret : DROPBOX_APP_SECRET,
callbackURL : options.callbackURL
},
function(accessToken, refreshToken, profile, done) {
profile.accessToken = accessToken;
profile.refreshToken = refreshToken;
done(null, profile);
}
);
}
);
If you just want to retrieve user name and ID you can get it from userData object:
UserInfo : { "Name": { "GivenName": "XYZ", "FamilyName": "ABC" }, "Id": "something#outlook.com" }
https://github.com/Microsoft/BotBuilder/issues/3242

Google OAuth Issue

I have a Umbraco website that has google sign in button configured as follows:
At the top of the page (inside the header section) I have the scripts for calling google API:
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '<myapp client Id>.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
redirect_uri: 'http://localhost:40136/umbraco/Surface/AuthSurface/GoogleAuthrizedUser',
scope: 'profile email'
});
});
}
</script>
In the body section of the code I have the google button setup and associated click function:
<script>
function onSignIn(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
console.log("Authorization Code: " + authCode);
$.post("/umbraco/Surface/AuthSurface/GoogleAuthrizedUser", { code: authCode })
.done(function(msg) {
// Success settings
})
.fail(function(xhr, status, error) {
});
} else {
//authResult['code'] is null
//handle the error message.
}
};
</script>
Controller code that handles the call back on the server end:
public class AuthSurfaceController : SurfaceController
{
public ActionResult GoogleAuthrizedUser()
{
string AuthCode = HttpContext.Request["code"];
var info = new GoogleAccessTokenResponse();
var client = new GoogleOAuthClient();
try
{
info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
}
catch (Exception ex)
{
var strMessage = String.Format("<div class=\"info\"><p>{0}</p><p>{1}</p></div>", "Google Login Error",
ex.Message);
return Json(new AjaxOperationResponse(false, strMessage));
}
}
}
On the Serverside I am using Skybrud Social plugin for accessing google apis.
The google authentication happens in the popup and authorizes client with credentials and authResult['code'] has a valid code.
In the controller when I initialize the client and call the function GetAccessTokenFromAuthorizationCode(AuthCode), it returns an exception of 'Invalid Request'
I tried checking this authResult['code'] returned in the javascript function onSignIn in the https://developers.google.com/oauthplayground/
Same error description is shown 'Invalid request'. I am not sure why this is happening. The error returned is "invalid_grant"
Can anyone have a solution to this problem? What am I doing wrong here?
In your surface controller you're initializing a new instance of GoogleOAuthClient, but without setting any of the properties. The GetAccessTokenFromAuthorizationCode method requires the ClientId, ClientSecret and RedirectUri properties to have a value. You can initialize the properties like this:
// Initialize a new instance of the OAuth client
GoogleOAuthClient oauth = new GoogleOAuthClient {
ClientId = "The client ID of your project",
ClientSecret = "The client secret of your project",
RedirectUri = "The return URI (where users should be redirected after the login)"
};
You can read more about authentication in the documentation: http://social.skybrud.dk/google/authentication/ (the approach explained there will however not use any JavaScript)

Resources