Instagram authentication scope param using coldfusion - coldfusion

I have an Instagram application written in Coldfusion 8 that basically pulls in media by tags and then allows people to Like / vote on the photos which is all done via the Instagram API. The Liking part is causing me no end of grief though, as I can get the Authentication and Access_Token without a drama, however the Access_Token doesn't appear to have permission to Like by default. There is an optional param for the Authenticate call "scope" which allows you to pass the permissions allowed for the Access_Token but i cannot work out how to pass this via ColdFusion CFHTTP as a POST.
Here is the preparation for the data to be sent over CFHTTP looping over all params as type="FormField". No matter how I try and present the scope options, either JSON format, string with spaces, string with "+" delimiters it seems to have no effect and the Like operation continues to fail due to permission errors.
<cfscript>
var LOCAL = {};
LOCAL['config'] = {};
LOCAL['returnStruct'] = {};
// prep packet required by the main call method
// the following values are required for EVERY call
LOCAL['config']['method'] = 'POST';
LOCAL['config']['format'] = ARGUMENTS['outputType'];
LOCAL['config']['url'] = VARIABLES.authURL;
// variables required by this method
LOCAL['config']['params'] = {};
LOCAL['config']['params']['client_secret'] = ARGUMENTS.client_secret;
LOCAL['config']['params']['grant_type'] = 'authorization_code';
LOCAL['config']['params']['redirect_uri'] = ARGUMENTS.redirect_uri;
LOCAL['config']['params']['code'] = ARGUMENTS.code;
LOCAL['config']['params']['scope'] = 'likes comments relationships';
</cfscript>

If anyone else is running into the same issues with "scope" not being correctly applied to the return Access_Token it turns out the problem was Instagram Documentation being vague about where this argument should be used. I had tried it every way possible as a POST operation as it suggested during the server-side Authentication, however it appears to only work if sent as GET params and after some playing around I decided to tack the "scope" param onto the 2nd stage of the authentication which is where the Code is requested and that worked! See below
https://api.instagram.com/oauth/authorize/?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=likes+basic
This will present the user with an confirmation message from Instagram to allow the application to perform Likes on behalf of the user and everything else works like a charm after this.

Related

How to specify the database in an ArangoDb AQL query?

If have multiple databases defined on a particular ArangoDB server, how do I specify the database I'd like an AQL query to run against?
Running the query through the REST endpoint that includes the db name (substituted into [DBNAME] below) ie:
/_db/[DBNAME]/_api/cursor
doesn't seem to work. The error message says 'unknown path /_db/[DBNAME]/_api/cursor'
Is this something I have to specify in the query itself?
Also: The query I'm trying to run is:
FOR col in COLLECTIONS() RETURN col.name
Fwiw, I haven't found a way to set the "current" database through the REST API. Also, I'm accessing the REST API from C++ using fuerte.
Tom Regner deserves primary credit here for prompting the enquiry that produced this answer. I am posting my findings here as an answer to help others who might run into this.
I don't know if this is a fuerte bug, shortcoming or just an api caveat that wasn't clear to me... BUT...
In order for the '/_db/[DBNAME/' prefix in an endpoint (eg full endpoint '/_db/[DBNAME/_api/cursor') to be registered and used in the header of a ::arangodb::fuerte::Request, it is NOT sufficient (as of arangodb 3.5.3 and the fuerte version available at the time of this answer) to simply call:
std::unique_ptr<fuerte::Request> request;
const char *endpoint = "/_db/[DBNAME/_api/cursor";
request = fuerte::createRequest(fuerte::RestVerb::Post,endpoint);
// and adding any arguments to the request using a VPackBuilder...
// in this case the query (omitted)
To have the database name included as part of such a request, you must additionally call the following:
request->header.parseArangoPath(endpoint);
Failure to do so seems to result in an error about an 'unknown path'.
Note 1: Simply setting the database member variable, ie
request->header.database = "[DBNAME]";
does not work.
Note 2: that operations without the leading '/_db/[DBNAME]/' prefix, seem to work fine using the 'current' database. (which at least for me, seems to be stuck at '_system' since as far as I can tell, there doesn't seem to be an endpoint to change this via the HTTP REST Api.)
The docs aren't very helpful right now, so just incase someone is looking for a more complete example, then please consider the following code.
EventLoopService eventLoopService;
// adjust the connection for your environment!
std::shared_ptr<Connection> conn = ConnectionBuilder().endpoint("http://localhost:8529")
.authenticationType(AuthenticationType::Basic)
.user(?) // enter a user with access
.password(?) // enter the password
.connect(eventLoopService);
// create the request
std::unique_ptr<Request> request = createRequest(RestVerb::Post, ContentType::VPack);
// enter the database name (ensure the user has access)
request->header.database = ?;
// API endpoint to submit AQL queries
request->header.path = "/_api/cursor";
// Create a payload to be submitted to the API endpoint
VPackBuilder builder;
builder.openObject();
// here is your query
builder.add("query", VPackValue("for col in collections() return col.name"));
builder.close();
// add the payload to the request
request->addVPack(builder.slice());
// send the request (blocking)
std::unique_ptr<Response> response = conn->sendRequest(std::move(request));
// check the response code - it should be 201
unsigned int statusCode = response->statusCode();
// slice has the response data
VPackSlice slice = response->slices().front();
std::cout << slice.get("result").toJson() << std::endl;

PowerBI Failed to execute 'atob' on 'Window' in parsePowerBIAccessToken

Randomly today my powerbi embedded code has been throwing:
DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
at window.atob (eval at <anonymous> (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1326:504), <anonymous>:1:83)
at e.parsePowerBIAccessToken (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331307)
at e.isTokenTenantValid (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:2331046)
at t.isPowerBIAccessTokenValid (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31523)
at t.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:31233)
at m.scope.promptForLogin (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.bundle.min.js:21:25515)
at fn (eval at compile (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1444:307), <anonymous>:4:374)
at m.$digest (https://app.powerbi.com/13.0.11674.244/scripts/reportembed.externals.bundle.min.js:1350:310)
at https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:1626830
at t.i [as _next] (https://app.powerbi.com/13.0.11674.244/scripts/reportEmbed.min.js:1:189984)
I checked the access token and they appear valid. (No different to the ones working yesterday). I added a debug hook into window.atob and it seems like something inside of parsePowerBIAccessToken is passing undefined to atob. I can't figure out why though unless this code changed.
Kind of stuck on how to figure out the issue. (Not helping that Chrome seems to struggle to debug the lines without crashing).
The code path is trying to run the embed token through this code:
e.prototype.parsePowerBIAccessToken = function() {
return JSON.parse(atob(i.powerBIAccessToken.split(".")[1]))
}
Odd because the code is clearly using "tokenType: models.TokenType.Embed," and thus probably shouldn't be going down that code path?
I noticed it works if I'm logged into the MS account though, so it's using cookies.
If you copy and paste the embed URL from a report it'll have autoAuth=true in the URL. You must remove this from the embed URL or it attempts to use your cookies to authenticate. (It'll also try to use the embed token like an access token and execute wrong code, so that's MS's bug).
In my JS code I removed the autoAuth from the embed url and it'll skip trying to use cookies.
embedURL = embedURL.replace(/autoAuth=true&/ig, '');
You should always get the embed URL using the REST APIs.
From the embed for your customers (Embed Token) documentation
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
// You need to provide the workspaceId where the dashboard resides.
ODataResponseListReport reports = await client.Reports.GetReportsInGroupAsync(workspaceId);
// Get the first report in the group.
Report report = reports.Value.FirstOrDefault();
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
EmbedToken tokenResponse = client.Reports.GenerateTokenInGroup(workspaceId, report.Id, generateTokenRequestParameters);
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = report.Id
};
You get the embed URL from the Report object.
The URL you got from powerbi.com is powerbi secure embed and it is not recommended to use this URL for another scenario.
We raised this issue with the PowerBI team. You are supposed to use an API call to get the embed URL for a report. There is an API tester here: https://learn.microsoft.com/en-us/rest/api/power-bi/reports/getreportingroup
Here is a playground for testing embedding: https://microsoft.github.io/PowerBI-JavaScript/demo/v2-demo/index.html

oAuth2.0 authentication in C++

I have a desktop application in which I need to make a user authentication with oAuth2.0.
I looked at the Facebook example but it doesn't really correspond to what I have to do or I don't understand it well.
In fact, I create an O2 instance:
O2* o2Auth;
o2Auth = new o2Auth(this);
o2Auth->setClientId(CLIENT_ID);
o2Auth->setClientSecret(CLIENT_SECRET);
o2Auth->setRequestUrl(REQUEST_URL);
o2Auth->setTokenUrl(TOKEN_URL);
But I don't understand how to authenticate the user with the user name and password. Which function do I have to use to do that?
In Facebook example, there is:
if (argList.contains(OPT_OAUTH_CODE)) {
// Start OAuth
fbdemo_.doOAuth(O2::GrantFlowAuthorizationCode);
} else if (argList.contains(OPT_VALIDATE_TOKEN)) {
fbdemo_.validateToken();
}
where argList is the parameters given to the application but they are not the user name and password.
In the tweeter example, there is :
oxTwitter_->setUsername(username);
oxTwitter_->setPassword(password);
but I didn't find the equivalent in O2.
I think I have to use things like GET and POST functions in the OSRequestor class, but how to link a OSRequestor instance to my O2 instance?
So what do I need to send user name and password to do the authentication with O2?

OTRS Webservice as Requestor Test

I'm new to OTRS (3.2) and also new to PERL but I have been given the task of setting up OTRS so that it will make a call to our remote webservice so a record can be created on our end when a ticket is set as "Closed".
I set up various dynamic fields so the customer service rep can fill in additional data that will be passed into the webservice call along with ticket details.
I couldn't get the webservice call to trigger when the ticket was "Closed" but I did get it to trigger when the "priority" was changed so I'm just using that now to test the webservice.
I'm just using the Test.pm and TestSimple.pm files that were included with OTRS.
When I look at the Debugger for the Webserice, I can see that the calls were being made:
$VAR1 = {
'TicketID' => '6'
};
My webservice currently just has one method "create" which just returns true for testing.
however I get the following from the Test.pm
"Got no TicketNumber (2014-09-02 09:20:42, error)"
and the following from the TestSimple.pm
"Error in SOAP call: 404 Not Found at /TARGET/SHARE/var/otrs/Kernel/GenericInterface/Transport/HTTP/SOAP.pm line 578 (2014-09-02 09:20:43, error)
I've spent countless hours on Google but couldn't find anything on this. All I could find is code for the Test.pm and TestSimple.pm but nothing really helpful to help me create a custom invoker for my needs and configure the webservice in OTRS to get it to work.
Does anyone have any sample invokers that I can look at to see how to set it up?
Basically I need to pass the ticket information along with my custom dynamic fields to my webservice. From there I can create the record on my end and do whatever processing.
I'm not sure how to setup the Invoker to pass the necessary ticket fields and dynamic fields and how to make it call a specific method in my remote webservice.
I guess getting the Test.pm and TestSimple.pm to work is the first step then I can modify those for my needs. I have not used PERL at all so any help is greatly appreciated.
I'm also struggling with similar set of requirements too. I've also never programmed in PERL, but I can tell you at least that the "Got no TicketNumber" in the Test.pm is right from the PrepareRequest method, there you can see this block of code:
# we need a TicketNumber
if ( !IsStringWithData( $Param{Data}->{TicketNumber} ) ) {
return $Self->{DebuggerObject}->Error( Summary => 'Got no TicketNumber' );
}
You should change all references to TicketNumber to TicketID, or remove the validation whatsoever (also there is mapping to ReturnedData variable).
Invoking specific methods on your WS interface is quite simple (but poorly documented). The Invoker name that you specify in the "OTRS as requester" section of web service configuration corresponds to the WS method that will be called. So if you have WS interface with a method called "create" just name the Invoker "create" too.
As far as the gathering of dynamic field goes, can't help you on that one yet, sorry.
Cheers

Failing to fetch CategorizedFacebookType

I have an application which I developed about a year ago and I'm
fetching facebook accounts like this:
facebookClient = new DefaultFacebookClient(access_token);
Connection<CategorizedFacebookType> con = facebookClient.fetchConnection("me/accounts", CategorizedFacebookType.class);
fbAccounts = con.getData();
It worked fine until about a month ago, but now it returns the
fbAccounts list empty. Why is that?
I was hoping moving from restfb-1.6.2.jar to restfb-1.6.9.jar would
help but no luck, it comes up empty on both.
What am I missing?
EDIT, to provide the code for another error I have with this API. The following code used to work:
String id = page.getFbPageID(); // (a valid facebook page id)
FBInsightsDaily daily = new FBInsightsDaily(); // an object holding some insights values
try {
Parameter param = Parameter.with("asdf", "asdf"); // seems like the param is required
JsonObject allValues = facebookClient.executeMultiquery(createQueries(date, id), JsonObject.class, param);
daily.setPageActiveUsersDaily((Integer)(((JsonArray)allValues.opt("page_active_users_daily")).getJsonObject(0)).opt("value"));
...
This throws the following exception:
com.restfb.json.JsonException: JsonArray[0] not found.
at com.restfb.json.JsonArray.get(JsonArray.java:252)
at com.restfb.json.JsonArray.getJsonObject(JsonArray.java:341)
Again, this used to work fine but now throws this.
You need the manage_pages permission from the user to access their list of adminned pages - a year ago I'm not sure you did - check that you're obtaining that permission from your users
{edit}
Some of the insights metrics were also deprecated, the specific values you're checking may no longer exist - https://developers.facebook.com/docs/reference/fql/insights/ should have the details of what is available now
Try to check your queries manually in the Graph API Explorer to eliminate any issues in your code and hopefully get more detailed error messages that your SDK may be swallowing