Why is Google login returning “immediate_failed” even when user logged somewhere else? - google-plus

I am aware of similar questions but still have the problem:
"immediate_failed" - Could not automatially log in the user
Google login callback always shows "immediate_failed"
Google plus signin "immediate_failed" error
I also understand that the sign in callback is called initially even without request to check if the user is logged somewhere else. The “immediate_failed” is also returned correctly when the user is logged out within the browser from other Google services. However, when the user is in fact logged in Gmail in another Tab, I still receive the same failure in javascript.
This is the plain Google login code example. What could be wrong?. Some information:
Credentials:
Redirect URIs http://localhost:8000/beta/oauth2callback
Javascript Origins http://localhost:8000
Relevant Code (Javascript only sign in, copied and only slightly modified from: https://developers.google.com/+/web/signin/add-button)
Button declaration:
<div class="g-signin" data-callback="loginFinished"
data-clientid="268583......"
data-scope="profile email"
data-cookiepolicy="single_host_origin"
>
Callback:
var loginFinished = function(authResult) {
console.log(authResult)
if (authResult['code']) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// ..
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Error';
}
};
Full code (served locally by Apache on :8000/test0/signin_demo_basic.htm)
<html>
<head>
<title>Google+ Sign-in button demo</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
console.log(authResult)
if (authResult['code']) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Error';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
</script>
<script src="https://plus.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinished"
data-clientid="268583......"
data-scope="profile email"
data-cookiepolicy="single_host_origin"
>
</div>
</div>
<div id="oauth2-results" class="hide"></div>
<div>Reload the example or open in a new window</div>
</body>
</html>

After painfully checking my code and looking for answers I found out that in my Firefox the option to accept third party cookies was disabled. To solve the problem, in Firefox go to Options > Privacy and set "accept third party cookies" to visited. Please inform yourself about what accepting third party cookies implies.

For anybody who has a problem only on IE, set the immediate key within window.gapi.auth.authorize to false and try it out.

Related

JQuery AJAX call gives success, but response undefined

I have a rudimentary page from which I am calling a PHP service--using an AJAX call--to get an RSS feed and display it in a DIV tag.
I have a PHP page that returns the RSS feed as a JSON array. I have confirmed that the service works, as I can run it from the browser and get appropriate output.
But when I run it from the AJAX call, I get success, but undefined response. I have tried putting a callback function, but no joy. I'm sure the solution is pretty simple.
Here is the PHP page (TestService.php)
<?php
header('Content-Type: application/json');
$url = $_REQUEST['sUrl'];
$year = $_REQUEST['getYear'];
$rss = simplexml_load_file($url);
$outlist = array();
//echo json_encode($outlist);
$i = 0;
foreach ($rss->channel->item as $item) {
$i = $i + 1;
$yr = date('Y', strtotime($item->pubDate));
if ($yr == $year && $i < 5) {
$outlist[] = array('title' => $item->title,
'pubDate' => $item->pubDate,
'description' => $item->description);
}
}
//$serializedList = serialized($outlist);
$encodedList = json_encode($outlist);
echo $encodedList;
?>
Here is the HTML (TestPage.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery RSS Demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
//set the initial URL call
var sNewsUrl = "http://rss.cnn.com/rss/cnn_topstories.rss?xml";
var today = new Date();
var curYear = today.getFullYear();
for (var yr = curYear; yr >= 2017; yr--) {
$('#SelectYear').append("<option>" + yr + "</option>");
}
$('#news').html();
$('#news').append("<li>" + sNewsUrl + "</li>");
$.ajax({
type: "POST",
url: "TestService.php",
contentType: "application/json; charset=utf-8",
data: "{ 'sUrl': '" + sNewsUrl + "', 'getYear': '" +
curYear + "' }",
dataType: "json",
success: function (response) {
var jsonData = JSON.parse(response.d);
$('#news').empty();
if (jsonData.length <= 0)
$('#divNews').hide();
else {
$('#divNews').show();
for (var i = 0; i < jsonData.length; i++) {
if (i < 3)
$('#news').append("<li>" +
jsonData[i].pubDate +
" <a href='" + jsonData[i].link
+ "' target='_blank'>" +
jsonData[i].title + "</a>" + "
</li>");
}
}
},
error: function (xhr, status, error) {
//debugger;
alert("Result: " + status + " " + error + " " +
xhr.status + " " + xhr.statusText)
}
});
});
<div id="divNews">
News:<br />
<ul id="news"></ul>
</div>
</body>
</html>

openui5 FileUploader not working

I am trying to upload a file with a simple form. I can choose a file but when I click on "upload" nothing happens.
My FileUploader.view.xml is like:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
My Contoller.controller.js
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
var ControllerController = Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
oFileUploader.upload();
}
});
return ControllerController;
});
When I run this in the debugger I get an Uncaught TypeError:
Uncaught TypeError: Cannot read property '1' of null
at f.handleUploadComplete (FileUploader.controller.js?eval:11)
at f.a.fireEvent (EventProvider-dbg.js:229)
at f.a.fireEvent (Element-dbg.js:427)
at f.fireUploadComplete (ManagedObjectMetadata-dbg.js:426)
at HTMLIFrameElement.eval (FileUploader.js?eval:6)
at HTMLIFrameElement.dispatch (jquery-dbg.js:4737)
at HTMLIFrameElement.c3.handle (jquery-dbg.js:4549)
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
I searched for sample code and it seems my code is ok, but I don't know why I can't upload a file by click on the button.
I solved this problem ! :)
So, instead of using this
var m = /^[(\d\d\d)]:(.)$/.exec(sResponse);
use this in view FileUploader :
sendXHR="true"
After, on controller js you can use for status :
oEvent.getParameter("status")
and for getting answer as a json file :
var jsonfile = JSON.parse(oEvent.getParameter("responseRaw"));
Then access your sent object attributes from server (only when use dataType: 'json')
jsonfile.attribute
I hope this helps a lot!

GitHub API Users

I have a question about GitHub API.
I'm just starting to learn it. Sorry for my mistakes.
I need to get a list of users using GitHub API. But I cannot figure out how to do it :(
I would be extremely grateful to you for your help!
That is what we have now:
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html">
<title>GITHUB - API Test</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="ghapidata"></div>
<script type="text/javascript">
$(function() {
$('#ghapidata').html('Loading...');
var username = $('#ghusername').val();
var requri = 'https://api.github.com/users/' + "Test";
var repouri = 'https://api.github.com/users/' + "Test" + '/repos';
requestJSON(requri, function(json) {
var fullname = json.name;
var username = json.login;
var aviurl = json.avatar_url;
var profileurl = json.html_url;
var location = json.location;
var followersnum = json.followers;
var followingnum = json.following;
var reposnum = json.public_repos;
var email = json.email;
if (fullname == undefined) {
fullname = username;
}
var outhtml = '<h2>'+ 'Username:' + fullname + ' <span class="smallname">(#' + username + ')</span></h2>';
outhtml = outhtml + '<img src="' + aviurl + '" width="80" height="80" alt="' + username + '">';
outhtml = outhtml + '<p>Subscribers: ' + followersnum + ' - Subscribe: ' + followingnum +'</p>';
outhtml = outhtml + '<div class="clearfix">';
var repositories;
$.getJSON(repouri, function(json) {
repositories = json;
outputPageContent();
});
function outputPageContent() {
outhtml = outhtml + '</ul></div>';
$('#ghapidata').html(outhtml);
}
});
function requestJSON(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback.call(null, xhr.responseJSON);
}
});
}
});
</script>
</body>
</html>
Unless your html is hosted somewhere on api.github.com, or you take other specific steps, this won't work.
Read up on Same-Origin policy:
In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, hostname, and port number.1 This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.
For security reasons, a browser will not allow javascript to make requests to other domains unless explicitly allowed.
See also:
JSON Get request using JQuery (cross-domain)
Ways to circumvent the same-origin policy
Example of using github API from javascript

Render HTML with images using PhantomJS

I am trying to create a PDF from HTML text using PhantomJS (version 1.9.7). I've written a very simple script (made more complicated by error callbacks etc.)
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stdout.write(msgStack.join('\n'));
phantom.exit(1);
};
var page = require('webpage').create();
page.viewportSize = { width: 800, height: 600 };
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
page.render('tmp.pdf');
setTimeout(function() {
phantom.exit();
}, 5000);
I set up the page, assign the simple HTML string to the content property and render it to a PDF.
This script doesn't produce any output.
I've narrowed the problem down to the <img> element, when that is removed a PDF is generated as expected. I can see from the callback functions that the image is requested, a response is received, and there are no errors reported. I've tried rendering to a PNG which also yields no output.
I've explored the possibility of this being a proxy issue, however the raserize.js example works without any problems.
You have to call render when the page is fully loaded. Remember that loading a page via page.open or page.content is always async.
Change your code to this
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
setTimeout(function() {
page.render('tmp.pdf');
phantom.exit();
}, 5000);

Debugging PhantomJS webpage.open failures

In PhantomJS, webpage.open takes a callback with a status parameter that's set to 'success' or 'fail'. According to the docs, it wll be "'success' if no network errors occurred, otherwise 'fail'." Is there a way to see the underlying network error that caused the failure?
The url I'm trying to load works fine when I put it in my browser, and when I take a screenshot after getting the 'fail' message I see the page that I was on before I called webpage.open (so I can't just ignore the fail). I'm using Phantom for testing, so ideally I'd like a robust way of easily getting a helpful error messsage when webpage.open fails (or better yet have it never fail!)
Found this post which explains how to set up callbacks to get at the underlying reason for the failure: http://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/
Based on the that page, you could print out errors as follows:
page.onResourceError = function(resourceError) {
console.error(resourceError.url + ': ' + resourceError.errorString);
};
The page goes on to show an example of detailed logging for phantoms
var system = require('system');
page.onResourceRequested = function (request) {
system.stderr.writeLine('= onResourceRequested()');
system.stderr.writeLine(' request: ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
system.stderr.writeLine('= onResourceReceived()' );
system.stderr.writeLine(' id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};
page.onLoadStarted = function() {
system.stderr.writeLine('= onLoadStarted()');
var currentUrl = page.evaluate(function() {
return window.location.href;
});
system.stderr.writeLine(' leaving url: ' + currentUrl);
};
page.onLoadFinished = function(status) {
system.stderr.writeLine('= onLoadFinished()');
system.stderr.writeLine(' status: ' + status);
};
page.onNavigationRequested = function(url, type, willNavigate, main) {
system.stderr.writeLine('= onNavigationRequested');
system.stderr.writeLine(' destination_url: ' + url);
system.stderr.writeLine(' type (cause): ' + type);
system.stderr.writeLine(' will navigate: ' + willNavigate);
system.stderr.writeLine(' from page\'s main frame: ' + main);
};
page.onResourceError = function(resourceError) {
system.stderr.writeLine('= onResourceError()');
system.stderr.writeLine(' - unable to load url: "' + resourceError.url + '"');
system.stderr.writeLine(' - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
};
page.onError = function(msg, trace) {
system.stderr.writeLine('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
system.stderr.writeLine(msgStack.join('\n'));
};