I have a very simple page in Angular2, which contains a google Sign in button. Here is my code :
login.html
<meta name="google-signin-client_id" content="MYID.apps.googleusercontent.com">
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
</script>
<div class="g-signin2 google-connect" data-onsuccess="onSignIn"></div>
login.ts
ngOnInit(){
var script = document.createElement('script');
script.src = 'https://apis.google.com/js/platform.js';
document.body.appendChild(script);
}
// This code simply loads the JS after the page is rendered, since it doesn't work with only the script tag on the top of the HTML
The button is working very well, I can sign in perfectly, but I can't get the user informations. The onSignIn function is not triggering.
I've tried to change the data-onsuccess by multiple directives, I created functions inside my controller, or let the one google provides in my HTML, but I have no output on my console. I can't manage to retrieved the data of a connection. I'd juste like to get basic informations of an user (ID and mail). I can't use Angular2 plugins since i'm developing under Ionic.
Thank you in avance for any help :)
Related
The google signIn is not working properly in my application
When I click the sign In button, it shows my account and after selecting it nothing happens
Its not even going inside the "onSignIn" function which I have called in the "data-onsuccess" in html.
I have also included all the libraries in the head tag.
HTML code for the button
<div class="g-signin2" data-onsuccess="onSignIn" >
Javascript code for SignIn
const onSignIn = (googleUser) =>
{
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
google_email.value=profile.getId();
google_name.value=profile.getName();
}
My Signout is working properly
Attaching the signout code below
HTML code
<div>
<button #click="signOut">Sign out</button>
</div>
JS code
const signOut = () =>
{
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(() =>
{
console.log('User signed out.')
});
}
Please help me in resolving this issue.
Thanks in advance.
I'm currently in the learning phase for how the Google JS Client SDK works, since my boss needs me to learn how to integrate a Sign In button to his site to enable people to Authenticate via Google. I am testing the code for the custom Sign In button, with a touch of added functionality (like a Sign Out button), and in the process I've practically copy/pasted the code from their website. Let me show you the code first and then explain the issue, so that you can understand where the code is failing:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script type="text/javascript">
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}';
var scopes = 'profile email';
function SignOut() {
// I know, sloppy, but the signOut method from Google doesn't work.
window.location = 'https://accounts.google.com/logout';
// Additional code if necessary.
};
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({ 'userId': 'me' });
request.execute(function (response) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = response.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(response.displayName));
document.getElementById('name').appendChild(heading);
alert('User logged in. makeApiCall() has executed.');
})
})
};
function init() {
gapi.client.setApiKey(this.apiKey);
window.setTimeout(checkAuth, 1);
console.log('Up and ready to go.');
};
function checkAuth() {
// Triggers when the page and the SDK loads.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
};
function handleAuthClick(event) {
// Triggers after a user click event to ensure no popup blockers interfere.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
return false;
};
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('SignInBtn');
var signoutButton = document.getElementById('SignOutBtn');
if (authResult && !authResult.error) {
var V = JSON.stringify(authResult);
localStorage.setItem('GoogleAuthResult', V);
console.log(V); // Just for testing...
var authTimeout = (authResult.expires_in - 5 * 60) * 1000; setTimeout(checkAuth, authTimeout); // As recommended by a Google employee in a video, so that the token refreshes.
authorizeButton.style.display = 'none'; // Switching between Sign In and Out buttons.
signoutButton.style.display = 'inline-block';
makeApiCall();
} else {
// Immediate:true failed so user is NOT signed in.
// Make the Sign In button the one visible and prep it
// so that it executes the Immediate:false after user click:
authorizeButton.style.visibility = 'inline-block';
authorizeButton.onclick = handleAuthClick;
signoutButton.style.visibility = 'none';
}
};
</script>
The handleAuthClick function does run on the button click, but after taking the user to the Google Sign In page, when that page brings me back, the browser kinda flickers and the handleAuthResult function does not execute. Therefore, nothing changes in the page after the successful sign in; the button displayed is the Sign In button (Sign Out button not visible) and no information is displayed on the 'name' textNode. This happens on Internet Explorer (11), Firefox (39) and Chrome (44). Also, it happens at home on my laptop (straight connection to the web via Cable broadband) and at work (on Windows 8.1 behind an Active Directory).
I began wondering so I started refreshing the browser page and after a couple of refreshes, since the script runs from the beginning, the immediate:true fires again and voilá: user is connected and API call triggers.
So, on my laptop, I changed the function being called back, in the immediate:false line's callback parameter, to the init() function and that fixed the problem: everything runs smoothly from beginning to end. Yet, this is not the way it is supposed to work. I still don't know what is going on with that line.
This morning, on my computer at work (behind Active Directory), that fix didn't work. I have to refresh the page a couple of times so that the script runs from the beginning and the immediate:true triggers recognizing the user's Signed In state and displaying the proper button on screen.
Any ideas on why does this callback fail?
You need to define your apiKey in the first section of your code
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}'
Maybe thats the problem.
Google ApiKeys
I'm developping a component to easily edit associations in document properties pages.
The visual part of the component is an IFRAME showing the myspaces webscript.
I'm having difficulties to transfer user authentication to the content of the IFRAME. The session is lost, so the browser ask for a new BasicAuthentication.
I can transfer the ticket using the alf_ticket url parameter, but it is not reused for other urls produced by the webscript.
How could I transfer the Alfresco authentication to the webscript included in the IFRAME ?
<script type="text/javascript">
var self = this;
var ticket;
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open("GET", "http://blrkec335927d:8080/alfresco/wcservice/api/login?u=admin&pw=admin", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'json');
self.xmlHttpReq.setRequestHeader('X-Alfresco-Remote-User', 'admin');
xmlHttpReq.onreadystatechange = function() {//Call a function when the state changes.
alert(xmlHttpReq.status);
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200)
{
var xml = xmlHttpReq.responseXML;
var getticket = xml.getElementsByTagName("ticket");
ticket = getticket[0].childNodes[0].nodeValue
var url1 = "http://blrkec335927d:8080/alfresco/wcservice/ui/myspaces?f=0&p=%2FCompany%20Home&alf_ticket="+ticket;
var aa='<iframe bgcolor="#edf6fc" width="100%" height="100%" frameborder=0 src="'+url1+'" />';
document.getElementById('uploaddoc').innerHTML = aa;
}
}
self.xmlHttpReq.send();
</script>
<body>
<span id="pageTitle">${label['ALFRESCO_DOCUMENT']}</span>
<div id="uploaddoc">
</div>
</body>
<span id="footerButtons" style="vertical-align: bottom;"></span>
I am using above code . But still while loading page its asking for username and password. Please help me
First of all, don't use an iFrames for a simple webscript. You're not loading an entire new page which should have his own session.
Just use Client-Side JavaScript to get the JSON backend data en draw your own UI.
In any case you're compelled to use an iFrame, then just create your own myspaces webscript. Copy all the content, rename it and add your alf_ticket behind every generated url.
I am developing a facebook application which required to get below information while load.
Facebook Fan Page URL / Id on which the application has been added.
If the user who is accessing this application from specific page is admin of that page or not.
I am developing this application in ASP.Net and I am using Facebook Graph API.
Any help is highly appreciated.
Let me share some insights
Firstly, I would strongly suggest that you use Microsoft's Facebook C# SDK instead of using plain calls in your .NET project.
Steps
With the current API, you can do this in your ADMIN Page
Ask the user to connect and ask for manage pages permission (manage_page)
with the permisions to manage the pages, you can easily fill up a dropdown with all pages that the user have
Ask the user to add your app to it's own page as a tab using http://facebook.com/add.php?api_key=[API_KEY]&pages=1&page=[PAGE_ID]
Now that you have your app running on the user page, you need a way to check if that page is running inside Facebook as a Tab or not, and what's the Page Id that is running from.
In your App Tab Url page that you specified, ask for the signed_request and verify the Data as it has the ["page"]["id"] that you need so you can check against the saves Page_Id that you should have saved on the ADMIN area when your user adds your app to it's facebook page.
I hope this helps.
Code
To login and request all user pages:
<select class="facebook-page-list" disabled="disabled">
<option>Facebook pages</option></select>
<script>
<!--
FB.init({
appId: 'API_KEY',
cookie: true,
status: true,
xfbml: true
});
FB.api('/me', function (user) {
if (user != null) {
if (user.error) {
$(".fb-login").show();
} else {
// example from Facebook
var image = document.getElementById('image');
image.src = 'https://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
// get all user Pages
facebookGetPages();
}
}
});
function facebookGetPages() {
FB.getLoginStatus(function (response) {
if (response.session) {
access_token = response.session.access_token;
FB.api(
{
method: 'fql.multiquery',
access_token: access_token,
queries: {
query1: 'select page_id from page_admin where type <> "APPLICATION" and uid = ' + response.session.uid,
query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)'
}
}, function (queries) {
if (queries.error_msg)
alert(queries.error_msg);
else {
pages = queries[1].fql_result_set;
$(".facebook-page-list").empty();
for (i = 0; i < pages.length; i++)
$(".facebook-page-list").append("<option value='" + pages[i].page_id + "'>" + pages[i].name + "</option>");
$(".facebook-page-list").attr("disabled", false);
}
});
} else {
// no user session available, someone you dont know
}
});
}
//-->
</script>
To get the Page ID from your app:
ViewBag.signed_request = "can't get id";
dynamic signed_request = FacebookWebContext.Current.SignedRequest;
if(signed_request != null)
{
ViewBag.signed_request = signed_request.Data.page.id;
}
I have written some code using jQuery to use Ajax to get data from another WebForm, and it works fine. I'm copying the code to another project, but it won't work properly. When a class member is clicked, it will give me the ProductID that I have concatenated onto the input ID, but it never alerts the data from the $.get. The test page (/Products/Ajax/Default.aspx) that I have set up simply returns the text "TESTING...". I installed Web Development Helper in IE, and it shows that the request is getting to the test page and that the status is 200 with my correct return text. However, jQuery refreshes my calling page before it will ever show me the data that I'm asking for. Below are the code snippets from my page. Please let me know if there are other code blocks that you need to see. Thank you!
<script type="text/javascript">
$(document).ready(function() {
$(".addtocart_a").click(function() {
var sProdIDFileID = $(this).attr("id");
var aProdIDFileID = sProdIDFileID.split("_");
var sProdID = aProdIDFileID[5];
// *** This alert shows fine -- ProdID: 7
alert("ProdID: " + sProdID);
$.get("/Products/Ajax/Default.aspx", { test: "yes" }, function(data) {
// *** This alert never gets displayed
alert("Data Loaded: " + data);
}, "text");
});
});
</script>
<input src="/images/add_to_cart.png" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$aAddToCart_7" type="image" id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_aAddToCart_7" class="addtocart_a" />
The easiest way is to tell jQuery not to return anything.
$(".addtocart_a").click(function(e){
// REST OF FUNCTION
return false;
});
Good luck! If you need anything else let me know.