how to retrive User name/login name from gmail? - javascript

I am using google login for custom website. here i wrote the code for it
var sOAuthServiceEndPoint = "https://accounts.google.com/o/oauth2/auth?scope=http://gdata.youtube.com https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email&response_type=token&";
var sOAuthRedirectURL = "http://example.com/testpage/test.html";
var termsAndCondURL = "termsandcondition.html";
var sOAuthClientID = "294016263542.apps.googleusercontent.com";
var sAuthenticationURL = sOAuthServiceEndPoint + "redirect_uri=" + sOAuthRedirectURL + "&client_id=" + sOAuthClientID;
even i got an access token using below function
function fnOnLoad() {
//alert("Form Loaded");
var sAccessToken = '';
var params = {}, queryString = location.hash.substring(1),regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if(params.error){
if(params.error == "access_denied"){
sAccessToken = "access_denied";
alert(sAccessToken);
}
}else{
sAccessToken = params.access_token;
alert(sAccessToken);
}
window.opener.fnAuthorisationSuccess(sAccessToken);
window.close();
}
It's working succesfully and redirect into the other page where I want. but my problem is how to retrive user login name..?
I am using javascript for it.
Thanks in Advance

This can be found in the documentation.
After your application acquires an access token and has (if necessary) verified it, you can use that access token when making requests to a Google API. If the https://www.googleapis.com/auth/userinfo.profile scope was included in the access token request, then you may use the access token to acquire the user's basic profile information by calling the UserInfo endpoint.
Endpoint: https://www.googleapis.com/oauth2/v1/userinfo
Returns basic user profile information, including name, userid, gender, birthdate, photo, locale, and timezone. If the https://www.googleapis.com/auth/userinfo.email scope was present in the request, then the user's email will also be present in the response. If the email has been verified, then there is also a field that indicates the email is a verified address.

Related

Is there a way to get a firebase-authenticated github user's username

I'm essentially trying to have a website which authenticates the user's GitHub account through firebase, and then saves their username in a database - I specifically need the username for this. I have the authentication working but it seems that firebase doesn't have a way to access the username, only things such as the email, display name, etc. Currently I just want to save the username as a variable
I've come across this: https://developer.github.com/v3/users/#get-the-authenticated-user
I assume "login" is the username?
I'm relatively new to things though, and can't find any clear examples of how I would access this information with my token from firebase.
For reference, I have an index.html, linked to app.js, which contains all of my authentication code.
var provider = new firebase.auth.GithubAuthProvider();
provider.addScope('read:user');
//get elements
const authenticateBtn = document.getElementById('authbtn');
//add login event
authenticateBtn.addEventListener('click', e=>{
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
//what I want to get
//var Username = ;
//some data I am able to get
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
//where I want to print the username
//console.log(userName);
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
})
I really just need a beginners explanation of if what I want to do is possible and if so, exactly what code I'd need where in my project.
Thanks!
So I ended up getting some help from a friend, here is my solution:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
var username;
var obj;
const Http = new XMLHttpRequest();
Http.open("GET", "https://api.github.com/user?access_token="+token);
Http.send();
Http.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
obj = JSON.parse(Http.responseText);
username = obj.login;
console.log(username);
}
}
}

Firebase signInwithRedirect() always goes to localhost instead of my App

CONTEXT
I'm working on Xcode (ios app) on an angularJS/ionic app, trying to use Firebase auth functions to login using Facebook.
To do that i'm using signInWithRedirect() and getRedirectResult(), it seems working until my code gets to getRedirectResult(), no errors shown but after access acceptance facebook is redirecting me on Safari to : localhost:8080/var/containers/Bundle/Application/******/testApp.app/www/index.html#/login instead of my app login page.
I setup the facebook app on the Developper Facebook website and set https://testApp-32338.firebaseapp.com/__/auth/handler into OAuth URI field.
QUESTION
Is there a file in Xcode or somewhere (.XML or something), where i must write something about this redirect ? How to use Facebook to sign in my ionic/ios app ?
Here is my code :
//********** EDIT 1 CODE **********//
function loginFacebook ()
{
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday, email, public_profile');
firebase.auth().signInWithRedirect(provider);
// The only console.log() i can see in the console
console.log("0");
firebase.auth().getRedirectResult().then(function(result) {
console.log("1");
if (result.credential) {
console.log("2");
var user = result.user;
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
console.log("3");
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
Edit 1 : (02/11/2018)
According to Firebase it seems to be a known problem, probably wkwebview is the main cause of this issue on an IOS/ionic app. In this link : https://ionicframework.com/docs/wkwebview/ ionic is speaking about "Cross-Origin Resource Sharing" (CORS), I'm really not familiar with this how could i "trap" the signInWithRedirect() result to change it to the required url ? Is this will fix my problem ? Is someone was already able to cope with this issue ?
Edit 2 : (02/12/2018)
Trying a new method, using the cordova-facebook4-plugin, everything seems working, even the redirect part to my app and collecting datas (name, birthday, token...etc). The unknown part is how to link my results to the firebase auth provider ? In Firebase doc (https://firebase.google.com/docs/auth/web/facebook-login) the method is to use signInWithRedirect() (see my first edit) or signInWithPopUp() (which is not working on phone app), there is a signInWithCustomToken(), but it doesn't work when i'm putting inside the Facebook given token. I also tried the universal-links method with unfortunately, same results. How do you guys would do this ? Is someone achieved the connexion between cordova-facebook4-plugin and Firebase ?
//********** EDIT 2 CODE **********//
function loginFacebook()
{
var fbLoginSuccess = function (userData) {
console.log("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getAccessToken(function(token) {
console.log("Token: " + token);
// What to do with this Token to link to Firebase ???
});
}
facebookConnectPlugin.login(["public_profile", "user_birthday"], fbLoginSuccess,
function (error) {
console.error(error)
}
);
}
Edit 3 : (02/14/2018) It's Working !!!
Finally is it working, thanks a lot to #mootrichard ! Here is my final working code :
//********** EDIT 3 CODE FINAL **********//
// SIGNIN WITH FACEBOOK4
function loginFacebook()
{
var provider = new firebase.auth.FacebookAuthProvider();
var fbLoginSuccess = function (userData) {
console.log("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getAccessToken(function(token) {
console.log("Token: " + token);
connectProvider(token);
});
}
facebookConnectPlugin.login(["public_profile", "user_birthday"], fbLoginSuccess,
function (error) {
console.error(error)
}
);
//CONNECT FACEBOOK TO THE FIREBASE PROVIDER
function connectProvider(access_token)
{
// Build Firebase credential with the Facebook access token.
var credential = firebase.auth.FacebookAuthProvider.credential(access_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).then(function(result) {
var firstName = result.displayName.split(' ').slice(0, -1).join(' ');
var lastName = result.displayName.split(' ').slice(-1).join(' ');
console.log("The firstName is : ", JSON.stringify(firstName));
console.log("The lastName is : ", JSON.stringify(lastName));
$state.go("anOtherPage");
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
I think you want to look at one of Firebase's advanced guides. Since you already have your token, you can simply create the Facebook Credentials using:
// Build Firebase credential with the Facebook access token.
var credential = firebase.auth.FacebookAuthProvider.credential(access_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
You can see their example at https://firebase.google.com/docs/auth/web/facebook-login#advanced-authenticate-with-firebase-in-nodejs.

Firebase web get provider data (gender and birthday ) in Google and Facebook

Herer is my Google part
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().languageCode = 'zh-TW';
provider.addScope('profile');
provider.addScope('https://www.googleapis.com/auth/userinfo.profile');
provider.addScope('https://www.googleapis.com/auth/userinfo.email');
provider.addScope('https://www.googleapis.com/auth/plus.login');
provider.addScope('https://www.googleapis.com/auth/plus.me');
provider.addScope('https://www.googleapis.com/auth/user.birthday.read');
provider.addScope('email');
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log(result.user)
}).catch(function(error) {
app.message.register = error.message;
});
Herer is my Facebook part
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');
firebase.auth().languageCode = 'zh-TW';
firebase.auth().signInWithPopup(provider).then(function(result) {
console.log(result.user)
}).catch(function(error) {
});
Those two part are not get the gender and birthday in console.log(result.user) is there missing some setting ? or having the wrong part? Any idea?
The access tokens returned result.credential.accessToken will provide access to these additional scopes. You would need to query the Google/Facebook API with that access token to get this data (specific to the additional requested scopes). By the way, some additional user info is now returned specific to IdP. Check content of result.additionalUserInfo.profile.

Node.JS Express to HTML data transfer

I am creating a login application with node.js, I seem to have ran into a knowledge deficit in the area of transferring strings from the server to html.
I posted my current code at jsfiddle.
My application verifies the credentials to the mysql table then generates a basic token that contains the username password and the ip address of the user.
In the last block of code, where the client html posts to the server, I have two segments where you see send to basic user page and send to admin page.
I have attempted to research this subject, but i get nothing pertinent to the situation. can anyone guide me in the right direction on sending the user to the admin or user page while sending the token alongside of it?
As well, how can the express server send data to the client, for example
on the page, I want the database to hold pertinant information regarding the user, like address and phone number. How can this information be transmitted from the server to the client via html?
app.post('/', urlencodedParser, function (req, res) {
var date = new Date();
con.query("SELECT * from users WHERE username=" + con.escape(req.body.username) + " AND password=" + con.escape(req.body.password), function (err, rows, fields) {
if (err) {
console.log(err);
} else {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if (rows == '' && rows == '') {
console.log('User Failed to login to the server with #'.red + con.escape(req.body.username) + ':' + con.escape(req.body.password));
res.sendFile(__dirname + '/admin/failure.html');
} else {
var isadmin = rows[0].admin;
var cryptomap = [req.body.username + ',' + req.body.password + ',' + ip];
var strcryptomap = cryptomap.toString(); // convert array to string
var token = encrypt(strcryptomap);
console.log(token + ' SENT'.red);
var backto = decrypt(token); //decr
var arr = backto.toString().split(","); // SPLITTING STRING TO SATISFY /VERIFY *************************************************
console.log(arr[0] + ' has valid token, encryption succsessful'.green);
con.query('UPDATE users SET crypto=' + con.escape(token) + 'WHERE username=' + con.escape(req.body.username), function (err, rows, fields) {
if (err) {
res.send(500);
} else {
console.log('Updated Crypto for ' + req.body.username);
if (isadmin == 0) {
// send to basic user page
res.send('USER');
} else {
//send to admin user page
res.sendto('http://google.com/?' + token);
}
}
});
}
}
});
});
To start, I'll answer the actual question you are asking.
The way I normally handle what you are trying to accomplish, is by using an ajax POST from the front end with the users credentials(https of course, never send credentials using http), have the server authenticate the user, create the token and respond to the ajax post with the token. From here, if the authentication was successful and the server responded with a token and whatever other information you wanted to get, you have a few options for storing it, I personally use cookies. After the token is stored, let the front end handle the redirect.
Having said all of that, I would definitely read up on authentication principles and the different ways your system can be attacked. I see a couple of red flags dealing with pretty basic authentication ideas/strategies.
Edit : Here is an example AJAX post to a login API endpoint that responds with a token and saves the username and token to cookies. Obviously your result data in the success function may be organized differently than mine but can be accessed in the same way. You can send whatever data you would like back in this result object and redirect accordingly
var loginData = {
username : $('#loginUsername').val(),
password : $('#loginPassword').val()
}
$.ajax({
type : "POST",
url : [your-endpoint-url],
data : loginData ,
success : function(result) {
setCookie('appUN', result.username);
setCookie('appTok', result.token);
location.href = '/dashboard';
},
error : function(result) {
location.href = '/login/Error';
}
});
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + 10800000);
var expires = "expires="+d.toUTCString();
var path = "path=/";
document.cookie = cname + "=" + cvalue + "; " + expires + ";" + path;
}
To actually send the data back to the client from the server, in your API endpoint, you would do all of your logic to check the users credentials and if their credentials were valid, you could create a token and return something like
res.json({
username: username,
token: token
});
and this JSON object will be available in the success function as shown above.
If the users credentials were invalid, you could return something like
res.status(400).json({Message : "The username or password is incorrect"});
and because of the 400 status, it will be caught by the error function of your AJAX request

How do you pass a dynamically built string as a http header in HTTP.call with meteor?

I'm stuck having to use a legacy web service that takes a username and password and returns xml indicating if the credentials are valid. The legacy service requires me to pass an http header with the request that contains the user's password. So, to get it to work, I had to hard code the password (actualUserPassword) in the header as follows:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var result = HTTP.call("GET", urlToCall, {headers:{"token:appname:127.0.0.1:actualUserPassword":""}});
This works when I hard code the proper password for the user on the server, but what I really need to do is build that header dynamically using the password variable, like this:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var headerString = "token:appname:127.0.0.1:" + password;
var result = HTTP.call("GET", urlToCall, {headers: {headerString: ""}});
When I do this, the auth server does not see the header coming in. What is wrong? I'm just trying to replace the hard coded string: "token:appname:127.0.0.1:actualUserPassword" with a string variable I built using the actual password passed in.
It's a javascript Object key problem. Try this instead:
var urlToCall = "https://ourlegacyauthserver/auth?uid=" + username);
var headerString = "token:appname:127.0.0.1:" + password;
var headerObject = {};
headerObject[headerString] = "";
var result = HTTP.call("GET", urlToCall, {headers: headerObject});

Categories

Resources