Firebase login Facebook / Google - UID - javascript

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).

Related

How to query database or call model function from active admin javascript file (ruby on rails)

In my active admin app I have a push_announcement.rb view where I can filter who I want to send the notifications to.
Inside active_admin.js, after getting all of the form variables what I want to do is to be able to query the database to show in a dialog how many users this announcement will be sent to before confirming.
So, is it possible to query from the javascript file or to have it call some other ruby function elsewhere to query for me?
active_admin.js:
$('form #push_announcement_submit_action input[type=submit]').click(() => {
let userIds = $('textarea#push_announcement_user_ids').val()
let create_within = $('input#push_announcement_create_within').val()
let last_active_within = $('input#push_announcement_last_active_within').val()
let gender = $('select#push_announcement_gender').val()
let prefecture_ids = $('input#push_announcement_prefecture_ids').val()
let userList = []
// QUERY THE DATABASE AND GET THE USER COUNT
return confirm('Send to ' + userList.length + ' users')
})
I have this function inside my PushAnnouncement model which would be perfect if I could reach it:
def target_users
users = User.active.includes(:notification_setting)
users = users.where(id: user_ids.gsub(/[[:space:]]/, '').split(',')) if user_ids?
users = users.where('created_at > ?', create_within.days.ago.beginning_of_day) if create_within?
users = users.where('last_active_at > ?',
last_active_within ? last_active_within.days.ago.beginning_of_day : 1.month)
users = users.joins(:profile).merge(Profile.where(gender: gender)) if gender?
users = users.joins(:profile).merge(Profile.where(residence_prefecture: prefecture_ids.gsub(' ', '').split(','))) \
if prefecture_ids?
users
end

Building an a two factor authentication login scenario in Reactjs/NodeJS

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

Searching Through Firebase for Data

I am trying to get data out of my firebase for a specific user via the realtime database. Whenever a user signs up and new piece is added to the stripe_customers piece of the database. How can I get the customer_id for each customer?
Current Customer -
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
Current Database Layout - Database Layout
Thanks!
I am not sure whether I understand you clear, but it seems it is quite easy something like:
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var dbRef = firebase.database().ref('stripe_customer/' + userId + '/customer_id');
dbRef.once('value', snapshot=> {
if (snapshot.exists()){
var custumerId = snapshot.val().customer_id;
_goAheadWithCustomerId(custumerId);
}
})
_goAheadWithCustomerId(c){
console.log('Customer Id is :', c);
}

Writing data to completely separate locations simultaneously using update()

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;

Concerns in using everyauth

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!

Categories