Accessing ProcessMaker BPM framework's APIs from external apllication - ajax

I have followed the tutorial from the PM docs (http://wiki.processmaker.com/3.1/OAuth_2.0) and have not success accessing the access token.
Currently I am using the trial version of PM and I would like to access the APIs in my java application js file, but the browser returns the following error "XMLHttpRequest cannot load 'myPMServerAddress' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.".
Any help??
I registered my apps server (http://localhost:8100) within the Website box of the (User Applications -> +New) form and my code looks as followed:
var restServer = 'https://trial.processmaker.com/';
var workspace = 'sysmyWorkspace/';
var jqxhr = $.ajax({
type: "POST",
url: restServer + workspace + 'oauth2/token',
data: {
grant_type : 'password',
scope : '*',
client_id : 'myClientId',
client_secret: 'myClientSecret',
username : 'admin',
password : 'myPassword'
}
})
.done( function(data) {
if (data.error) {
alert("Error in login!\nError: " + data.error + "\nDescription: " + data.error_description);
}
else if (data.access_token) {
alert("data access token received!");
var d = new Date();
d.setTime(d.getTime() + 60*60*1000);
document.cookie = "access_token=" + data.access_token + "; expires=" + d.toUTCString();
document.cookie = "refresh_token=" + data.refresh_token; //refresh token doesn't expire
}
else {
alert(JSON.stringify(data, null, 4));
}
})
.fail(function(data, statusText, xhr) {
alert("Failed to connect.\nHTTP status code: " + xhr.status + ' ' + statusText);
});
});

You need to disable CORS in client side
for Ubuntu:
google-chrome --disable-web-security --user-data-dir
for Ms Windows:
Go into the command prompt and go into the folder where Chrome.exe is and type
chrome.exe --disable-web-security
I can test that with no errors.

Related

GET request from NetSuite to Oracle EPM, but faced with "Authorization Required - You are not authorized to access the requested resource

Error: "Authorization Required - You are not authorized to access the requested resource. Check the supplied credentials (e.g., username and password)."
Using the same exact headers and URL, I am successfully able to make the request get through via Postman and Powershell. But when doing the call via SuiteScript, I get the auth error. I am thinking it may have something to do with me constructing the headers.
Here is the code I used via NetSuite Debugger:
require(['N/https', 'N/encode'], function(https, encode) {
function fetchCSVdata() {
var authObj = encode.convert({
string : "username:password",
inputEncoding : encode.Encoding.UTF_8,
outputEncoding : encode.Encoding.BASE_64
});
var psswd = 'Basic ' + authObj;
var headerObj = {'Authorization' : psswd};
var response = https.get({
url: 'https://<bleep>.pbcs.us6.oraclecloud.com/interop/rest/11.1.2.3.600/applicationsnapshots/DemandPlan_ExportItemPlan.csv/contents',
headers: headerObj
});
return response.body;
};
var x = fetchCSVdata();
log.debug("error", x);
});
Looking at some working code of mine it is different than yours but I don't see the error.
var authstring = encode.convert({string: 'username:password',
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64});
var headerObj = {Authorization: 'Basic '+ authstring };
var response = https.get({url: 'https://webservices.XXX.com', headers: headerObj});

How to get the raw content of an outlook email message with Office JS API?

I'm trying to check if the sender used a proxy email address. Comparing the from and sender properties isn't enough, so I thought of checking the raw message source itself.
How do you get the raw message source with Office JS API?
If you're just looking for a prebuilt solution to see and analyze message headers in Outlook and OWA, you can use Message Header Analyzer. If you're building your own add-in, you can borrow source from there.
Basically, you have two options:
EWS
Rest
In both cases, what you want to retrieve is PR_TRANSPORT_MESSAGE_HEADER, aka 0x007D. The EWS request will look something like this:
function getHeadersRequest(id) {
// Return a GetItem EWS operation request for the headers of the specified item.
return "<GetItem xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>" +
" <ItemShape>" +
" <t:BaseShape>IdOnly</t:BaseShape>" +
" <t:BodyType>Text</t:BodyType>" +
" <t:AdditionalProperties>" +
// PR_TRANSPORT_MESSAGE_HEADERS
" <t:ExtendedFieldURI PropertyTag='0x007D' PropertyType='String' />" +
" </t:AdditionalProperties>" +
" </ItemShape>" +
" <ItemIds><t:ItemId Id='" + id + "'/></ItemIds>" +
"</GetItem>";
}
And you'll submit it through a call to makeEwsRequestAsync
var mailbox = Office.context.mailbox;
var request = getHeadersRequest(mailbox.item.itemId);
var envelope = getSoapEnvelope(request);
mailbox.makeEwsRequestAsync(envelope, function (asyncResult) {
callbackEws(asyncResult, headersLoadedCallback);
});
To do the same from rest, you first need to get the rest ID for the item:
function getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
// itemId is already REST-formatted
return Office.context.mailbox.item.itemId;
} else {
// Convert to an item ID for API v2.0
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
And then send the request through AJAX:
var getMessageUrl = getRestUrl(accessToken) +
"/api/v2.0/me/messages/" +
itemId +
// PR_TRANSPORT_MESSAGE_HEADERS
"?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";
$.ajax({
url: getMessageUrl,
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken,
"Accept": "application/json; odata.metadata=none"
}
}).done(function (item) {
The MHA source gives more context.

spotify application requests authorization

I am trying to get 'access token' from spotify with the following code.
var encoded = btoa(client_id+':'+client_secret);
function myOnClick() {
console.log('clikced!');
$.ajax({
url: 'https://accounts.spotify.com/api/token',
type: 'POST',
data: {
grant_type : "client_credentials",
'Content-Type' : 'application/x-www-form-urlencoded'
},
headers: {
Authorization: 'Basic ' + encoded
},
dataType: 'json'
}).always((data)=> console.log(data));
}
however I keep getting errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://accounts.spotify.com/api/token.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
and
readyState: 0, status: 0
Arielle from Spotify here.
Looks like you're using the Client Credentials Flow, which is one of 3 Authentication flows you can use with the Spotify API. (You can check out all 3 here)
Client Credentials is meant for server-side use only, and should not be used on the front-end, as it requires a client secret which you shouldn't be exposing!
You should use the Implicit Grant flow, which is made for use in the browser, instead. It's easy to get up and running, too!
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
'user-read-birthdate',
'user-read-email',
'user-read-private'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}
Gist: https://gist.github.com/arirawr/f08a1e17db3a1f65ada2c17592757049
And here's an example on Glitch, that you can "Remix" to make a copy and start making your app: https://glitch.com/edit/#!/spotify-implicit-grant
Hope that helps - happy hacking! 👩🏼‍💻
const result = await axios({
url: this.apiLoginUrl,
method: 'post',
data: "grant_type=client_credentials",
headers: {
'Authorization': `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString('base64')}`,
},
});

Phantomjs if proxy not respond

Script test.js:
var page = require('webpage').create();
var url = args[1];
page.open(url, function (status) {
console.log(status);
phantom.exit();
});
Run script:
phantomjs --proxy=1.1.1.1:22 test.js 'http://nonexistent_site.com'
1.1.1.1:22 - nonexistent server
http://nonexistent_site.com - nonexistent site
How can I determine in PhantomJS which one is not responding - a proxy or a site?
You can catch network timeouts with page.onResourceTimeout callback:
page.onResourceTimeout = function(request) {
console.log('Response (#' + request.id + '): ' + JSON.stringify(request));
};
You can also set your own timeout:
page.settings.resourceTimeout = 3000; // ms
To intercept network errors you can register page.onResourceError callback:
page.onResourceError = function(resourceError) {
console.log('Unable to load resource #' + resourceError.id + ' URL:' + resourceError.url);
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
With this in place, non-existent host will trigger Host not found error.
But if you use a non-working proxy, you will always end up with error Network timeout on resource first, even if target host does not exist.
So if you want to check proxies :) I'd suggest just to page.open hosts that are 100% working, for example, set up a simple static web page on the very server that you are operating from.
Also there is a node.js module: proxy-checker

How to keep the session with angular-http-auth?

I use angular-http-auth for authentication in an angular-js app.
here is the login function inside the login controller :
$scope.login = function() {
var credentials = Base64.encode($scope.username + ':' + $scope.password);
var config = { headers: { 'Authorization': 'Basic ' + credentials } };
$http.get('url/to/json/user', config)
.success(function() {
$http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
authService.loginConfirmed();
console.log('login success');
})
.error(function() {
console.log('login failed');
});
}
(base64 is an encrypting service coming from here)
the problem: If the user is already logged-in and he opens a new tab or if he reloads the page, he has to log-in again.
How can is it possible to avoid that and to keep the session open if the user reloads the page or comes from an external link ?
You can use either cookies or the html5 datastore to save the credentials or the base64 string with the credentials. You can then load them from there and parse them to $http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
Hope it helps.

Resources