I am having serious trouble in using everyauth. All I need is facebook login. For that I am trying to use the example of everyauth. Once I do facebook authentication, how can I check in every page if the user is logged in or not/ get his facebook information. What I have done is
var exp = require('express');
var app = exp.createServer();
var conf = require('/Users/lakeshkansakar/clicker/node_modules/everyauth/example/conf')
var everyauth = require('everyauth');
everyauth.debug = true;
var usersById = {};
var nextUserId = 0;
function addUser (source, sourceUser) {
var user;
user = usersById[++nextUserId] = {id: nextUserId};
user[source] = sourceUser;
return user;
}
var usersByFbId = {};
var usersByTwitId = {};
everyauth.everymodule
.findUserById( function (id, callback) {
callback(null, usersById[id]);
});
everyauth
.facebook
.appId(conf.fb.appId)
.appSecret(conf.fb.appSecret)
.findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
return usersByFbId[fbUserMetadata.id] || (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));;
})
.redirectPath('/');
everyauth
.twitter
.consumerKey(conf.twit.consumerKey)
.consumerSecret(conf.twit.consumerSecret)
.findOrCreateUser( function (sess, accessToken, accessSecret, twitUser) {
return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));;
})
.redirectPath('/');
In every get request, I then tried to check if everyauth.loggedIn is true or not. However, everyauth.loggedIn is shown to be undefined. Why is it so? How to check if the user has logged in using facebook?
Not sure that this will help or not, but I researched both EveryAuth and Passport, and was able to implement Passport for Facebook and Google very quickly. It looks like a much cleaner implementation of authentication.
http://passportjs.org/
Once you are logged In, you will be redirected to "/" as mentioned in .redirectPath('/');.
In the routes for "/", you can check for everyauth.loggedIn.
You can see more details here.. How can I check if a user is already logged in? (everyauth, node.js)
Hope this helps!
Related
I am trying To build a two factor authentication scenario using NodeJS using this an example URL: https://jira.amazone.de/
When you access this page the website will ask you to enter a username and password and in the second step it will ask you for a pin code from google authenticator
my goal is to keep listening to the page and when the user enter the pin code I should read a cookie value to check if the user is signed in or no
I am having a problem to keep listening to the page while the user login
the below code is what I did so far but it will only list the cookie in the first page which is before even the user login
app.get("/ssologin", function (req, res) {
// var url = req.headers["url"];
// var lastChar = url.charAt(url.length - 1);
// if (lastChar == "/") {
// url = url.slice(0, -1);
// }
res.redirect("https://jira.amazone.de")
res.on("finish", () => {
console.log("finshed")
const cookies = parseCookies(req);
console.log(cookies)
})
})
function parseCookies(request) {
const list = {};
const cookieHeader = request.headers?.cookie;
if (!cookieHeader) return list;
cookieHeader.split(`;`).forEach(function (cookie) {
let [name, ...rest] = cookie.split(`=`);
name = name?.trim();
if (!name) return;
const value = rest.join(`=`).trim();
if (!value) return;
list[name] = decodeURIComponent(value);
});
return list;
}
NOTE: The Front end is reactJs I tried to do the whole process through reactjs but I couldn't find a proper npm that is equivalent to Webview in react native
Im almost finishing a job and got a huge problem, I did the login/register using firebase and to call some functions I used in almost the hole project the uid like firebaseAuth.onAuthStateChanged(user => {if(user.uid) do something... the problem is, Im adding the login with Google/Facebook and it doesn't have a uid of the firebase (if Im doing right), there is something to do like when loging with some social midia the firebase register some uid to that user, this is what Im doing:
case this.GOOGLE:
var providerr = new firebase.auth.GoogleAuthProvider();
var result = await firebase.auth().signInWithPopup(providerr);
var user = result.user.providerData;
if(user[0].uid){
let nome = user[0].displayName;
let nome1 = nome.substr(0,nome.indexOf(' '));
let nome2 = nome.substr(nome.indexOf(' ')+1);
let usuario = { nome: "",
sobrenome:"",
email:user[0].email,
telefone:"",
picture:""
}
usuario.nome = nome1?nome1:"";
usuario.sobrenome = nome2?nome2:"";
usuario.picture = user[0].photoURL?user[0].photoURL:"";
usuario.telefone = user[0].phoneNumber?user[0].phoneNumber:"";
firebaseDatabase.ref().child('/profile/' + user[0].uid )
.update(usuario);
return 1;
}
else return -1;
break;
Firebase only stores a list of email+password users. It does not store any data for the users that are signed with social providers (Facebook, Google).
I have created my module modulemy with the following code :
var request = require('request');
var EventEmitter = require('events').EventEmitter;
var User = new EventEmitter();
var userFbInfos = new EventEmitter();
//database and calls the get started conversation.
User['checkUserRegistered'] = function (userID) {
//if registered and have phone number then nothing to do otherwise, get user infos return it and last ask his phonenumber
//Now we consider that the user is not registered. So we get is infos
userFbInfos.getInfos(userID);
userFbInfos.on('gotten', function (err, userInfos) {
User.emit('checked',err, userInfos);
});
}
//This gets user info from Facebook and notifies when the information is gotten via event gotten
//The thing is as node is event driven if you request the user info and run a code before getting that info, the userinfos will be null.
userFbInfos['getInfos'] = function (userID) {
request.get("https://graph.facebook.com/v2.6/" + userID + "?fields=first_name,last_name,locale,gender,timezone,profile_pic&access_token=" + process.env.page_token,
function (err, response, body) {
userFbInfos.emit('gotten',err,JSON.parse(body));
});
}
exports.userFbInfos = userFbInfos;
exports.User = User;
and then in my app.js, I am using it as follow :
modulemy = require('./modulemy.js');
var user = modulemy.User;
//Checking if user is registered.
user.checkUserRegistered('123');
//This variable checks if the event was trigger before already to not execute the code twice.
var called = false;
user.on('checked', function (err, userInfos) {
if (!called){
console.log("Call Checked");
var name = "";
if (typeof (userInfos) != 'undefined') {
name = userInfos['first_name'];
}
console.log("Yes you are there");
called = true;
}
});
The problem is the checked event is being triggered multiple times... I don't understand where the problem is ... I need help.
there might be an issue when receiving the packages from fb. Try to count some variable up if the input data coming from the query is the same as the one from the query before.
In my firebase app when a new user signs up I add their initial data like displayname, emai , photourl to the database under the top level users node. This works fine.
Now when a user post a status, I want to upload the the post to top level statuses node where all user statuses are kept. And simultaneously I want to upload the post to current user's posts node i.e users/currentuser/posts.
I am following the methods shown on official firebase site here.
The problem is when I hit the post button nothing happens and no data is posted to the database
My function that gets invoked when the post button is clicked:
function postStatus(){
var ref = firebase.database().ref("allstatuses");
var user = firebase.auth().currentUser;
var newStatusRef = ref.push();
var newStatusKey = newStatusRef.key();
var statusData = {
status: postInput.val(),
likes: 0,
dislikes: 0
};
var updateUserStatus = {};
updateUserStatus["users/" + user.uid + "/" + newStatusKey] = statusData;
updateUserStatus["allstatuses/" + newStatusKey] = statusData;
if(user){
firebase.database().ref().update(updateUserStatus);
}else{
alert("please login");
}
}
What am I doing wrong?
According to the API reference link it is key not key()
Change this
var newStatusKey = newStatusRef.key();
to
var newStatusKey = newStatusRef.key;
I am having what I hope is an easy to solve problem with the Soundcloud API using JavaScript:
unauthorized, the following code works fine:
var group = 'https://soundcloud.com/groups/chilled';
SC.initialize({
client_id: 'MY_CLIENT_ID',
redirect_uri: 'http://localhost:49957/tn/callback.html'
});
// Resolve works fine and gives number ID of group
SC.resolve(group + '?client_id=' + client_id).then(function (g) {
console.log('Group 1: ' + g.id);
});
after I authorise a user:
SC.connect().then(function () {
return SC.get('/me');
}).then(function (me) {
authUser = me.id
});
// Resolve no longer works and i get 401 unauthorised
SC.resolve(group + '?client_id=' + client_id).then(function (g) {
console.log('Group 1: ' + g.id);
});
can anyone help me to understand what I am doing wrong - I can't seem to find an example to follow anywhere. Driving me potty!
Many thanks in advance,
James
For anyone else out there facing the same issues, I have answered my own question:
Firstly, I was not properly logged in due to an error on Soundcloud's sample code in their callback.html used to return to the site after oAuth client side login flow. In Soundcloud's sample callback.html, the code:
<body onload="window.opener.setTimeout(window.opener.SC.connectCallback, 1)">
must be altered to:
<body onload="window.setTimeout(window.opener.SC.connectCallback, 1)">
This allows the popup to close properly and completes the login flow if the application settings are correctly configured to the same domain (localhost or production, but not a mix of the two).
Further to this callback, i have added the following code:
var params = getSearchParameters();
window.opener.oAuthToken = params.code;
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray(prmstr) {
var params = {};
var prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
In my subsequent pages, I can get any data as a sub-resource of the '/me/...' endpoint now, but anything I used to be able to interrogate via public access is still in accessible. Since I can now iterate through the logged in users groups, I no longer have to resolve the name of a group via the public resource '/resolve/', so my issue is not solved, but avoided in my current development.