Angular 5 Google Signin into component - javascript

I've implemented Client Google Signin using my API Key into my html page. When I insert all the necessay tags and functions into index.html it works perfectly, but when it comes to insert the Google Signin button into a component, it is not even shown.
So, if this is how it works in a simple html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Signin out Demo</title>
<script src="https://apis.google.com/js/platform.js" async defer>
</script>
<meta name="google-signin-client_id" content="myprivateid.apps.googleusercontent.com">
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div><br />
Sign out
<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.
console.log(profile);
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
</body>
</html>
If I want to insert into an Angular component and leave the things as similar as I can I would left the meta-tag and the google script into the index.html and then insert the button in a component. It is not even shown. What am I getting wrong?
<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/platform.js" async defer>
</script>
<meta name="google-signin-client_id" content="myprivateid.apps.googleusercontent.com">
</head>
<body>
<app-root></app-root>
</body>
</html>
and in the specific template of the component in which I want the button to appear I insert:
<div class="g-signin2" data-onsuccess="onSignIn"></div><br />
Sign out
Apart from the little javascript code I must add, the button is not even shown.
How can I fix it without installing other npm components?

Related

javascript fetch command does not display the content on the html page

I have a simple text file in the same directory as HTML file , I used the fetch command in javascript to display the text file content in the page div section when the loading of the page finish
however, my code doesn't work and nothing has been displayed, my question is does the fetch command suitable for such a task or should I use filereader ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript" defer>
const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"
console.log(myfile);
async function getTextFile1() {
try {
const response = await fetch(myfile, { mode: 'no-cors' });
const fileText = await response.text();
//console.log(window.location);
//console.log(window.location.href);
const tagElement = document.getElementById("about_layer");
tagElement.innerText = fileText;
} catch (error) {
console.log(error);
}
}
window.onload = getTextFile1;
</script>
</head>
<body>
<div >should be placed here </div>
<div id="about_layer">
</div>
</body>
</html>
There is nothing wrong with your code , just try running your html file using development server .
You can use Live Server visual studio code extension for that.

How to redirect user to another page when logged into Firebase Auth in javascript?

I have a web page with the Firebase Auth services for javascript (web). In my index.html is the login:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index Page</title>
<!-- The Firebase JS SDK and SDKs for Firebase products are here -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="loginContainer">
<div id="titleContainer">
<h1>Login</h1>
</div>
<div id="elementsContent">
<input class="txtBox" id="txtPassword" type="password" placeholder="Password">
<button class="btn btn-action" id="btnLogin">Submit</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Main Page</title>
<!-- The Firebase JS SDK and SDKs for Firebase products are here -->
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="formContainer">
<h1>Welcome!</h1>
<button id="btnLogout" class="btn hide">Logout</button>
</div>
<script src="app.js"></script>
</body>
</html>
app.js
(function() {
// My web app's Firebase configuration are here -------------------
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// References
var database = firebase.database();
var auth = firebase.auth();
// Get elements
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnLogout = document.getElementById('btnLogout');
// Add login event
btnLogin.addEventListener('click', e => {
// Get email and pass
database.ref('emailChild').on('value', function(snapshot) {
var email = snapshot.val();
console.log(email);
const pass = txtPassword.value;
// Sign in
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
});
btnLogout.addEventListener('click', e => {
auth.signOut();
});
// Add event listener
auth.onAuthStateChanged(user => {
if(user) {
console.log(user);
} else {
console.log('not logged in');
}
});
}());
What I want to do and I don't know how to do it is the following:
When you log in, redirect to the main.html page.
In main.html I have a button to log out. I would like the button to redirect to index.html.
In my login there is only the textbox for the password, the email I retrieved from the database and there is no option to sign up. I am the only user (just to put the code in context).
You can redirect using location.href = 'url'
After signing up successfully redirect to index page using
location.href = 'main.html'
You should do that after promise is resolved like so.
promise.then(() => { location.href = 'main.html' }
Similarly after clicking the logout button
location.href = 'index.html'
!!! Take care of the relative and absolute urls

LinkedIn Javascript SDK Retrieve Profiles

I am trying to retrieve any Profile data with the LinkedIn SDK right now. I am only able to retrieve my own data. Is there a way to retrieve like any Profile data or search for profiles with xyz Name and Show the results? I can't find usefull Information about this, neither in the offical documentation or elsewhere.
<!DOCTYPE html>
<html>
<head>
<title>LinkedIn Javascript Api Hello World</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: xxxxxxxxxxxxxx
onLoad: onLinkedInLoad
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad(){
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
var member = profiles.values[0];
//var id=member.id;
//var firstName=member.firstName;
//var lastName=member.lastName;
//var photo=member.pictureUrl;
//var headline=member.headline;
document.getElementById("profiles").innerHTML =
"<p id=\"" + member.id + "\">Hello " + member.firstName + " " + member.lastName + "</p>";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="profiles"></div>
</body>
</html>
Thank you in advance.
There are only 2 ways to do:
Use Oauth2. This means you have to get access token before you search profile by API.
Refer to this, you must be one of Linkedin Partners.

Google+ API doesnt return access_token Javascript

We have an application that relies upon Google to authenticate its users against our google apps account and then do some serverside verification and group lookups.
Recently google changed the name of the object that held the access_token variable which we require to authenticate. In the docs (https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile) it says that access_token is available from the getAuthResponse() method, however when i use this it comes back as undefined. Inspecting the object after console.log() reveals all the other fields mentioned except access_token. I'm worried that Google will change the object again in the future and leave us without our application.
Here is the code.
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<meta name="google-signin-client_id" content="XXX.apps.googleusercontent.com">
<script>
//This happens after the user has authenticated with Google and has been passed
//back to the page
function onSignIn(googleUser) {
//Check to see whether the user is trying to sign out.
if (window.location.href.indexOf("signOut=1") !== -1) {
//Sign them out of the application.
signOut();
//redirect them to the same page, without the signOut query string so they can log back in if want
window.location.href='googlesigninform.html'
return false;
}
//Grab the token, access token and email.
var _id = googleUser.getAuthResponse().id_token; //This works
var _accessToken = googleUser.Ka.access_token; //This works but changed from googleUser.B.access_token
var profile = googleUser.getBasicProfile(); //Works
console.log(googleUser.access_token); //Undefined
console.log(googleUser.getAuthResponse().access_token);//Undefined
//Make a post request to the API
makePostRequest(_id, _accessToken, profile.getEmail());
}
What is the correct way to access the access_token variable?
If you need to use access token you are using the wrong type of google signin flow.
You should follow this page: https://developers.google.com/identity/sign-in/web/server-side-flow
What you did implement is google Sign-In to identify users (https://developers.google.com/identity/sign-in/web/)
Which only provides a unique id per user because it is meant to authenticate the user for your own service and not to give an access token to use for other Google services later on.
I believe your problem is that your application is lacking the necessary google-signin-scope.
To answer your question i created an app from the ground using the Google Developer Console. The application is very simple like the one this this tutorial.
The entire application consists of a simple HTML that loads the google API and has a callback called onSignIn (like yours).
Here's the entide code of the application:
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="PLACE_YOUR_ID_HERE.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
var response = googleUser.getAuthResponse(),
idToken = response['id_token'],
accessToken = response['access_token'];
console.dir('id token: ' + idToken);
console.dir('access token: ' + accessToken);
}
</script>
</body>
</html>
As you can see, the difference between my app and yours is that yours is lacking the first META attribute.
Well i have a hack work around that gets the access_token from the variable.
function findAccessToken(googleUser) {
var returnValue;
Object.getOwnPropertyNames(googleUser).forEach(function (val, idx, array) {
console.log(val + ' -> ' + googleUser[val]);
Object.getOwnPropertyNames(googleUser[val]).forEach(function (vals, idxs, arrays) {
if (vals === "access_token") {
console.log("true");
returnValue = googleUser[val][vals];
}
});
});
return returnValue;
}
Surely this can't be the most elegant solution. If someone could point in the righter direction that would be good.
Here is the code for sign in using google.
<html lang="en">
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log("Name: " + profile.getName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
</body>
</html>
Try this
var _access_token = GoogleUser.getAuthResponse().access_token

Initiating the Google+ Sign-In flow with JavaScript not working

I'm following the current tutorial and for some reason when ever I click on the Sign in with Google button nothing seems to happen and I'm not entirely sure why. Here is the code:
<html>
<head>
<title></title>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<meta name="google-signin-clientid" content="782332402251-os0n348u3v5vaq5kff87f5pc65ib6i19.apps.googleusercontent.com" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
<meta name="google-signin-cookiepolicy" content="single_host_origin" />
<script src="https://apis.google.com/js/client:platform.js?onload=render" async defer>
/* Executed when the APIs finish loading */
function render()
{
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
});
}
function signinCallback(authResult)
{
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<button id="signinButton">Sign in with Google</button>
</body>
</html>
Any idea where I'm going wrong?
Looks like a mistake in the tutorial. Emedding Javascript within a script tag with a src attribute is not valid in HTML5. You need to move your code into a separate script tag.
<script type="text/javascript">
// your code here
</script>
See here - http://jsfiddle.net/7umb41z2/

Categories