Google api oauth prolog - oauth

I am trying to connect to google oauth. I have used javascript to make a connection to google and get a code, I then understand I need to exchange this code for a token as detailed here: https://developers.google.com/identity/protocols/OAuth2WebServer
The code I have is :
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_session)).
:- use_module(library(http/js_write)).
:- use_module(library(http/http_files)).
:- use_module(library(http/json)).
:- use_module(library(http/http_open)).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_client)).
:- use_module(library(http/http_ssl_plugin)).
post_to_google(Reply,Code,Client_Id,Client_Secret):-
Grant_type=authorization_code,
http_post(
'http://requestb.in/10qo0si1',
%'https://www.googleapis.com/oauth2/v3/token',
form([
code=Code,
client_id=Client_Id,
client_secret=Client_Secret,
redirect_uri='http://localhost:5000/',
grant_type=Grant_type
]),
Reply,
[]
).
If I query post_to_google(R,123,id,secret).
This sends a request to request bin so I can inspect it at (http://requestb.in/10qo0si1?inspect) and I get a response 'ok'.
If I comment out the request bin and replace with the google address I get false. Where I would expect something like { "error": "invalid_request" } or if queried with the correct credentials something like:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
Do I have to do something different because it is https or am I making a mistake somewhere else? Tracing it seems to fail in address/4 for not matching a protocol?

Okay finally worked this step out. If anyone is interested:
Using status_code(_ErrorCode) seemed to resolve the problem with streampair and I needed to set redirect_uri='postmessage' for the request to work.
I also used http_open rather than http_post.
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_error)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_session)).
:- use_module(library(http/js_write)).
:- use_module(library(http/http_files)).
:- use_module(library(http/json)).
:- use_module(library(http/http_open)).
:- use_module(library(http/http_json)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_client)).
:- use_module(library(http/http_ssl_plugin)).
:- use_module('../prolog/google_client').
http:location(files, '/f', []).
:- http_handler('/', home_page, []).
:- http_handler('/gconnect', gconnect, []).
:- http_handler(files(.), http_reply_from_files('test_files', []), [prefix]).
:- dynamic
my_code/1.
server :-
server(5000).
server(Port) :-
http_server(http_dispatch, [port(Port)]),
format("Server should be on port 5000 to work with google settings- is it?").
read_client_secrets(MyWeb,Client_Id,Client_Secret) :-
open('client_secrets.json',read,Stream),
json_read_dict(Stream,Dict),
_{web:MyWeb} :< Dict,
_{
auth_provider_x509_cert_url:Auth_url,
auth_uri:Auth_uri,
client_email:Client_email,
client_id:Client_Id,
client_secret:Client_Secret,
client_x509_cert_url:Client_cert_url,
javascript_origins:Javascript_origins,
redirect_uris: Redirect_uris,
token_uri:Token_Uri
} :<MyWeb,
close(Stream).
post_to_google(Profile,Code,CID,CS):-
ListofData=[
code=Code,
client_id=CID,
client_secret=CS,
redirect_uri='postmessage',
grant_type=authorization_code
],
http_open('https://www.googleapis.com/oauth2/v3/token', In,
[ status_code(_ErrorCode),
method(post),post(form(ListofData))
]),
call_cleanup(json_read_dict(In, Profile),
close(In)).
home_page(Request) :-
reply_html_page(
[title('Oauth Test'),
script([type='text/javascript',
src='//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'],[]),
script([type='text/javascript',
src='//apis.google.com/js/platform.js?onload=start'],[]),
\call_back_script
],
[h1('hello'),
p('test'),
\google_loginButton
]).
gconnect(Request):-
%I need to get the code from the request
http_parameters(Request,[code(Code,[default(default)])]),
read_client_secrets(_MyWeb,Client_Id,Client_Secret),
post_to_google(Reply,Code,Client_Id,Client_Secret),
reply_json(Reply).
call_back_script -->
js_script({|javascript||
console.log("script runs");
function signInCallback(authResult) {
console.log("got to call back");
if (authResult['code']) {
console.log("has code");
console.log(authResult['code']);
$('#signInButton').attr('style','display: none');
$.post("/gconnect",
{code:authResult['code']},
function(data,status){
//console.log("Data: " + data.reply + "\nStatus: " + status);
console.log("Access Token: " + data.access_token + "\nExpires in : " + data.expires_in + "\nToken_type : " + data.token_type + "\nStatus: " + status);
});
/*
$.ajax({
type: 'POST',
url: '/gconnect',
processData:false,
//contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
contentType: 'application/octet-stream; charset=utf-8',
data: {code:authResult['code']},
success: function(result){
console.log("success");
console.log(result);
}
});
*/
}
}
|}).
google_loginButton -->
html([div([id="signInButton"],[
span([
class="g-signin",
data-scope="openid email",
data-clientid="124024716168-p5lvtlj5jinp9u912s3f7v3a5cuvj2g8.apps.googleusercontent.com",
data-redirecturi="postmessage",
data-accesstype="offline",
data-cookiepolicy="single_host_origin",
data-callback="signInCallback",
data-approvalprompt="force"],[])
])]).

Related

Intercept messages in Swagger UI

I am trying to intercept response messages in Swagger using this code:
var full = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
var ui = SwaggerUIBundle({
url: full + "/swagger/v2/swagger.json",
responseInterceptor: function (resp) {
console.log('#response');
return resp;
},
onComplete: function () {
console.log('#onComplete');
}
});
The problem is the response interceptor is called only once (for the https://localhost:5001/swagger/v2/swagger.json file) and it is not called for any API messages.
Is it possible to intercept all swagger API messages?
According to this post it should be possible: https://stackoverflow.com/a/46892528/1882699, but this does not work for me for some reason.
This configuration of Swagger UI works for me is in this post.
The difference is this line:
dom_id: '#swagger-ui',
When this line is used the interceptor intercepts every message. Without this line the interceptor catches only the first message.

How to clear the address in a message?

I can add a reply-to address to a message using this code:
msgReplyTo= {'ReplyTo':[{'EmailAddress':
{'Address': sA,'Name': sN }}]};
msgReplyTo = JSON.stringify(msgReplyTo);
$.ajax({
url: MessageUrl,
type : 'PATCH',
headers: { 'Authorization': 'Bearer ' +
accessToken, 'Content-Type':
'application/json' },
data : msgReplyTo
}).success(function (response)
{
...
Now I want to clear the Reply-to address. What syntax should I use?
Thanks,
Victor Ivanidze
According to your description, I assume you want to update the message and clear the replay to address.
Based on my test, we can set the replay to like this:
`"replyTo":[
]`
and using the update endpoint https://graph.microsoft.com/v1.0/me/messages/{id} to clear the replay-to address

XML API calling not working with cordova-plugin-advanced-http latest version in ionic3

I am using cordova-plugin-advanced-http plugin for API calling and all JSON enabled API working fine but I have one XML embedded API which is working fine in Postman but while I call it from ionic its param not getting at the server end.
Below is my code for XML API:
Type 1:
let headers = {
"Content-type": 'text/xml; charset=utf-8',
"Authorization": token,
};
let xmlBody =
'<ServiceRequest>' +
'<CaseNumber>' + caseNumber +
'</CaseNumber>' +
'</ServiceRequest>'
this.httpPlugin.setDataSerializer('utf8');
this.httpPlugin.post('https://test.com/Service', xmlBody, headers).then((response) => {
console.log("XML Response : ", JSON.stringify(response.data));
xml2js.parseString(response.data, function (err, result) {
console.log("XML parser success:", result);
console.log("XML parser error:", err);
if (result) {
resolve(result);
} else {
reject(err);
}
});
}).catch(error => {
if (error.status == 403) {
console.log("Token expired : " + JSON.stringify(error));
} else {
console.log("Error : " + error.error);
console.log("Error " + JSON.stringify(error));
reject(error);
}
});
Type 2:
let xmlBody = '<ServiceRequest>' +
'<CaseNumber>' + caseNumber +
'</CaseNumber>' +
'</ServiceRequest>';
console.log("XML Body", xmlBody)
// this.httpPlugin.setRequestTimeout(60);
this.httpPlugin.setDataSerializer('utf8');
this.httpPlugin.setHeader('*', 'authorization', token);
this.httpPlugin.setHeader('*', 'Content-Type', "application/x-www-form-urlencoded");
this.httpPlugin.post('https://test.com/Service', xmlBody, {}).then((response) => {
console.log("XML Response : ", JSON.stringify(response.data));
xml2js.parseString(response.data, function (err, result) {
console.log("XML parser success:", result);
console.log("XML parser error:", err);
if (result) {
resolve(result);
} else {
reject(err);
}
});
}).catch(error => {
if (error.status == 403) {
console.log("Token expired : " + JSON.stringify(error));
} else {
console.log("Error : " + error.error);
console.log("Error " + JSON.stringify(error));
reject(error);
}
});
All the time it's throwing errors from the server and with the same request, I am able to get data in postman as well as Native iOS code.
I referred this issue on GitHub but still no success.
Something I am missing though it's not able to get data on the server.
Help me to solve this issue.
After struggling a lot on this issue I found a solution to clean my request cookies.
In the HTTP Advanced plugin, there is one method to clear my cookies.
clearCookies()
Clear all cookies.
Use this method before calling any API.
So what it will do clear all my cookies and my issue related to old cookies will be solved in this way.
constructor(
public storage: Storage,
public httpPlugin: HTTP,
private platform: Platform
) {
// enable SSL pinning
httpPlugin.setSSLCertMode("pinned");
//Clear old cookies
httpPlugin.clearCookies();
}
The above code solves my issue.
Thanks all for your quick guidance and suggestions.
comment on this if this is not the right way to clear my old request data.

404 Error on Google Sheets API from HTTP Request

I am trying to append some data to a Google Sheets spreadsheet using a HTML POST Request. I am having some difficulty in solving the 404 error I get when sending the request. My request code is shown below:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == XMLHttpRequest.DONE) {
alert(httpRequest.status);
}
}
var params = {
"values": [
[
"value1",
"value2"
]
]
}
httpRequest.open('POST', 'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + 'values/Sheet1!B2:L2:append', true)
httpRequest.setRequestHeader('Authorization', 'Bearer ' + accessToken);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(JSON.stringify(params));
I have gained the necessary permissions in the access token, since I am able to create sheets, but I think there might be an issue with my url. Thanks in advance!
From the documentation sheets.append
https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}:append
I think you are missing a / before values
'https://sheets.googleapis.com/v4/spreadsheets/' + spreadsheetID + '/values/Sheet1!B2:L2:append', true)
Try testing it using the Try this api on the documentation page here

Reddit API Add Friend Endpoint /api/friend

Whenever I attempt to make a PUT Request to Reddit API in order to add a friend, it fails and claims a JSON Parse Error 'JSON_PARSE_ERROR'. Nothing I do is working. Here is how I form the request.
Endpoint: /api/v1/me/friends/username
>>> Endpoint URL: PUT https://oauth.reddit.com/api/v1/me/friends/micheal
Authorization: Bearer <Access_Token>
// The response given:
{"fields": ["json"], "explanation": "unable to parse JSON data", "reason": "JSON_PARSE_ERROR"}
I have also tried the /api/friend/username endpoint and nothing works.
I had exactly the same problem, and your question led me to the solution.
The endpoint is expecting a json payload ACTUALLY NAMED "json." I'm not sure what language you're using, this is what it looks like in Node:
var options = {
url: 'https://oauth.reddit.com/api/v1/me/friends/mynewfriend',
headers: {
'User-Agent': 'Appname/1.0 by username',
'Authorization': "bearer " + <Access_Token>
},
json: {
'name': 'mynewfriend',
'notes': 'whatever notes you want to put',
}
};
request.put(options, function(error, response, body) {
blah blah blah
}
the json itself is described in https://www.reddit.com/dev/api/#PUT_api_v1_me_friends_{username}

Resources