Firebase & Backbone: Trouble using uid as a key - javascript

I created logins and unique todo lists per user using Firebase and TodoMVC as proof of concept for another project. I'm using Firebase and Google to log users in and when things are working, they get a unique persistent todo list.
Everything works (I think) when the user is already logged into Google via their browser.
The problem happens when they aren't. Instead of their todo list, or a blank one under their user id, they see the todo list of an undefined user until they hit refresh, then things work again. The Firebase url doesn't see their uid until they hit refresh. If you're logged in to Google, you can replicate the error by opening an incognito window.
You can see the errors in my code at http://lacyjpr.github.io/todo-backbone, and my repo at https://github.com/lacyjpr/todo-backbone
This is my authentication code:
// Authenticate with Google
var ref = new Firebase(<firebase url>);
ref.onAuth(function(authData) {
if (authData) {
console.log("Authenticated successfully");
} else {
// Try to authenticate with Google via OAuth redirection
ref.authWithOAuthRedirect("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
}
});
}
})
// Create a callback which logs the current auth state
function authDataCallback(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
uid = authData.uid;
} else {
console.log("User is logged out");
}
}
This is the code that gets the UID to use as a firebase key:
// Get the uid of the user so we can save data on a per user basis
var ref = new Firebase(<firebase url>);
var authData = ref.getAuth();
if (authData) {
var uid = authData.uid;
console.log(uid);
}
// The collection of todos is backed by firebase instead of localstorage
var TodoList = Backbone.Firebase.Collection.extend({
// Reference to this collection's model.
model: app.Todo,
// Save all of the todos to firebase
url: <firebase url> + uid,
Thanks in advance for any advice you can offer!

You're calling .getAuth() before a user is authenticated.
Your app heavily relies on the uid to work properly. So in your case you would want to kick off the Backbone portion of the app once user has successfully authenticated.
You could modify your app.js to only kick off if the user is authenticated.
// js/app.js
var app = app || {};
var ENTER_KEY = 13;
$(function() {
var ref = new Firebase(<firebase url>);
var authData = ref.getAuth();
if (authData) {
ref.authWithOAuthRedirect("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
// kick off app
new app.AppView();
}
});
} else {
new app.AppView();
}
});
While this will work, it isn't the ideal solution. But there is no other option since you don't have a login screen.
Ideally, you'd want to provide the user a place to login, and then you'd have access the .getAuth() value.
Also, don't worry about storing the uid on the window. .getAuth() is the cached user, so there's no network call to get the data.

Related

Send verification email before logging in

This is the code that i'm practicing in to create a new user. I can receive the email verification and confirm it however, the site will still logged me in even if I have not yet confirmed my email yet.
try{
const { user } = await auth.createUserWithEmailAndPassword(email,password);
await user.sendEmailVerification();
await handleUserProfile(user, { displayName});
this.setState({
...initialSate
});
}catch(err){
console.log(err);
}
}
This is the handleUserProfile in another js file.
export const handleUserProfile = async (userAuth, additionalData) => {
if (!userAuth) return;
const {uid} = userAuth;
const userRef = firestore.doc(`users/${uid}`);
//create new user
const snapshot = await userRef.get();
if (!snapshot.exists){
const { displayName, email} = userAuth;
const timestamp = new Date();
//if the user exist does not exist
try{
await userRef.set({
displayName,
email,
createdDate: timestamp,
...additionalData
});
}catch(err){
console.log(err);
}
}
return userRef;
};
Everything is explained in the firebase documentation.
There you have the corresponding code snippets to try.
You would need to narrow down your question with some of this trials.
Even you have the chance to check if user opens the link from a differenc device from which waas signed up.
I think this is the snippet you might need:
// Confirm the link is a sign-in with email link.
if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
// Additional state parameters can also be passed via URL.
// This can be used to continue the user's intended action before triggering
// the sign-in operation.
// Get the email if available. This should be available if the user completes
// the flow on the same device where they started it.
var email = window.localStorage.getItem('emailForSignIn');
if (!email) {
// User opened the link on a different device. To prevent session fixation
// attacks, ask the user to provide the associated email again. For example:
email = window.prompt('Please provide your email for confirmation');
}
// The client SDK will parse the code from the link for you.
firebase.auth().signInWithEmailLink(email, window.location.href)
.then((result) => {
// Clear email from storage.
window.localStorage.removeItem('emailForSignIn');
// You can access the new user via result.user
// Additional user info profile not available via:
// result.additionalUserInfo.profile == null
// You can check if the user is new or existing:
// result.additionalUserInfo.isNewUser
})
.catch((error) => {
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
});
}
The site will still logged me in even if I have not yet confirmed my
email yet.
Yes this is how it is implemented in Firebase: there is nothing, out of the box, that prevents a user with a non-verified email to authenticate to your app.
You should manage that yourself, by:
Checking the email is verified in the back-end security rules (Firestore, Cloud Storage, etc..). For example with a function like:
function isVerifiedEmailUser() {
return request.auth.token.email_verified == true;
}
Possibly redirect and logout the user from your app if his/her email is not verified. For example, right after signing-up, as follows:
try {
const { user } = await auth.createUserWithEmailAndPassword(email,password);
await user.sendEmailVerification();
if (user.emailVerified) {
// display the content, redirect to another page, etc...
} else {
auth.signOut(); // Maybe call that after showing an error message
}
} catch(err){
console.log(err);
}
}
plus, potentially, something similar with signInWithEmailAndPassword() and onAuthStateChanged().

Checkout page signs out the user

The only way I check if user if logged in to my web app is using the following on the frontend
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
However, I have a cloud-function that I use in order to process a payment, it looks like the following
app.post("/payment", function (req, res) {
const orderId = new Date().getTime();
mollieClient.payments
.create({
amount: {
value: req.body.amount.amount,
currency: req.body.amount.currency,
},
description: req.body.description,
//redirectUrl: `http://localhost:5500/project/order.html?id=${orderId}`,
redirectUrl: `https://......web.app/order.html?id=${orderId}`,
webhookUrl: .....
})
.then((payment) => {
res.send({
redirectUrl: payment.getCheckoutUrl(),
});
return payment.getCheckoutUrl();
})
My problem is regarding the redirect URL, the redirect to order page is supposed to display information about that order, but it does not display anything because I set that only logged in users can see it. My question is why does it log out the user. I tried both to redirect to 'localhost' and 'URL-of-deployed-firebase-app' and in both cases it logs out the user. I thought by intuition that Firebase stores auth information to local storage because I can enter to any page I want without have to login. But I think this is not the case here. I am not using any let token = result.credential.accessToken tokens to keep track of auth status. What is the problem here and how should I proceed?
Here is Order page
function getOrderDetails() {
const url = new URL(window.location.href);
let orderId = url.searchParams.get("id");
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("User logged in " + user);
firebase
.firestore()
.doc(`orders/${orderId}`)
.get()
.then((doc) => {
let orderSelected = {
category: doc.data().category,
delivery: doc.data().delivery,
description: doc.data().description,
price: doc.data().price,
title: doc.data().title,
quantity: doc.data().quantity,
};
// set textContent of divs
} else {
console.log("User not logged in " + user);
}
});
}
getOrderDetails();
On a new page it takes time to restore the user credentials, as it may require a call to the server. So it is normal that your onAuthStateChanged() listener first is called with null and only after that with the actual user. So you will have to handle the flow in a way that deals with the initial null, for example by waiting a few seconds before assuming that the user session isn't restored.
Alternatively, you can store a marker value in local storage yourself to indicate the was signed in recently, and then on the next page use that to assume the restore will succeed.

How to set the user as logged in on firebase.auth(node.js)?

I have an app using sign in with a custom token, written on webpack observes. What I want to do now is mark the user after successful login by custom token as logged on firebase auth and firebase firestore, where I have the collections with users, and document for each user with data and some uid. I don't know how to to that.
Here is my code:
generateToken(uid) {
const uid = 'some-uid';
this.trigger(this.signals.action.onGenerateToken);
firebase.admin.auth().createCustomToken(uid)
.then((customToken) => {
console.log(customToken);
})
.catch(function (error){
if (error.Code === 'auth/invalid-custom-token') {
alert('The token you provided is not valid.');
}
else {
this.trigger(this.signals.error.onGenerateToken);
}
})
}
login(uid) {
firebase.auth().signInWithCustomToken(token)
.then(function() {
var user = firebase.auth().currentUser;
if (user) {
//mark the user as active (logged) after successful login on firebase auth and firebase firestore
};
this.trigger(this.signals.success.onLogin);
})
.catch(function(error) {
if (errorCode === 'auth/too-many-requests') {
this.trigger(this.signals.error.tooManyRequests);
}
else {
this.trigger(this.signals.error.userDisabled);
}
});
}
If I understand your question correctly, first create a reference to your user document, then call update() on the reference and pass in an object containing the properties you want to update and their new values.
let userRef = firebase.database().ref('users/' + userId);
userRef.update({active:true});
Check the firebase docs for more info on how to read and write to firebase.

AngularFire $save() not a function

I've seen other posts about problems with $save(), but I couldn't relate it to my code. I have a profile controller with an updateProfile() method that ultimately attempts to save the new data to the database after it has been changed.
I have defined my profile controller as follows:
angular.module('angularfireSlackApp')
.controller('ProfileCtrl', function($state, md5, profile) {
var profileCtrl = this;
var currentUser = firebase.auth().currentUser;
profileCtrl.profile = profile;
// Retrieves the user's email from input field, hashes it, and saves the data to the database
profileCtrl.updateProfile = function() {
console.log(profileCtrl.profile); // Profile object exists and is populated as expected
profileCtrl.profile.emailHash = md5.createHash(currentUser.email);
profileCtrl.profile.$save();
}
});
My user service:
angular.module('angularfireSlackApp')
// Provides a means of retrieving User data or list of all Users
.factory('Users', function($firebaseArray, $firebaseObject) {
// Provides a means of retrieving User data or list of all Users
// Create a reference to users that can be used to retrieve an array of users
var usersRef = firebase.database().ref("users");
users = $firebaseArray(usersRef);
var Users = {
// Returns a firebase object of a specific user's profile
getProfile: function(uid) {
return $firebaseObject(usersRef.child(uid));
},
// Returns the display name of a specific user
getDisplayName: function(uid) {
return users.$getRecord(uid).displayName;
},
// Returns the Gravatar url that corresponds to the user
getGravatar: function(uid) {
return 'www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
},
// Returns a firebase array of users
all: users
};
return Users;
});
Profile state from main app:
.state('profile', {
url: '/profile',
controller: 'ProfileCtrl as profileCtrl',
templateUrl: 'users/profile.html',
resolve: {
auth: function($state) {
firebase.auth().onAuthStateChanged(function(user) {
if (user == null) {
$state.go('home');
console.log("In auth but user NOT valid");
} else {
console.log("In auth and user valid");
}
});
},
profile: function(Users) {
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log("In profile and user valid");
return Users.getProfile(user.uid).$loaded();
} else {
console.log("In profile but user NOT valid");
}
});
}
}
});
console.log:
For some reason I'm getting an error that profileCtrl.profile.$save() is not a function. I know that the profileCtrl.profile object is legitimate and that I'm using $save() appropriately, but I just can't figure out what else could be the problem.
My gut feeling is that I'm missing something simple, but I'm brand new to AngularJS and Firebase so I wouldn't be surprised.
In the resolve of your "profile" state you are not returning anything.
You should fix it to:
auth: function($state, $firebaseAuth) {
return $firebaseAuth().$onAuthStateChanged().then(function(user) {
if (!user) {
$state.go('home');
console.log("In auth but user NOT valid");
} else {
console.log("In auth and user valid");
}
}); // classic situation to use $requiresAuth()
},
profile: function(Users, $firebaseAuth) {
return $firebaseAuth().$requireSignIn();
}
Moreover, your service shouldn't keep the reference to the $firebaseArray but create it for each controller that wants to use it.
The down-side is you'll have to make some changes, but the up-side is a more predictable, maintainable code:
var Users = {
// Returns a firebase object of a specific user's profile
getProfile: function(uid) {
return $firebaseObject(usersRef.child(uid));
},
// Returns the display name of a specific user
getDisplayName: function(uid) {
// This is actually an issue to get the name synchronously, but I see no reason why not using the Firebase SDK and fetch a-sync
//return users.$getRecord(uid).displayName;
return usersRef.child(uid)
.child('displayName')
.once('value')
.then(function (snap) {
return snap.val();
});
},
// Returns the Gravatar url that corresponds to the user
getGravatar: function(uid) {
// Again fetch a-synchronously
//return 'www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
return usersRef.child(uid)
.child('emailHash')
.once('value')
.then(function (snap) {
return 'www.gravatar.com/avatar/' + snap.val();
});
},
// Returns a firebase array of users
all: function () {
return $firebaseArray(usersRef);
}
};
Also refer to the new AngularFire docs: API reference

Meteor: Login over DDP and retrieve current user object in seperate Meteor app

First a little background:
I am working on an seperate mobile application that is connected with the main app. The connection is succesfully initiated and I can retrieve all collections, through subscriptions:
Remote = DDP.connect('http://localhost:3000/');
Meteor.users = new Meteor.Collection('users', {
connection: Remote
});
Remote.subscribe('users', true);
Now I want to make sure users can log in through the interface of the second app. After installing the accounts-password and the meteor-ddp-login package, I should be able to authenticate with the main app by using the next piece of code in the client side.
var Remote = DDP.connect('http://localhost:3000/');
DDP.loginWithPassword(Remote, {
username: username
}, password, function(error) {
if (!error) {
console.log(username + " is logged in!");
} else {
console.log(error);
}
});
Well, so far so good. No errors appear and the console logs a success message. Now the question comes:
How can I retrieve the user object of the user who just logged in.
I've set up several publish functions in the main app, but the user data does not become available to the client in the second app (other collections work fine, but Meteor.user() is undefined).
And also: How can I authenticate users who login with Facebook/Google/Twitter
Came across this, I had a similar need recently. Following code works in Meteor version 1.2.0.2
if (Meteor.isClient) {
Meteor.startup(function(){
//Seems that without this, on page refresh, it doesn't work.
//COMMENT: Ideally this should not be needed if the core takes care of this use case of a different connection for Accounts
//hack block 1***********
var token = Accounts._storedLoginToken();
if(token) {
Meteor.loginWithToken(token, function(err){
// this is going to throw error if we logged out
if(err)
console.log(err);
else
console.log('loginWithToken');
});//loginWithToken
}
//hack block 1***********
});//startup function
var connection = DDP.connect("http://localhost:3060");
Accounts.connection= connection;
//COMMENT: Ideally this should not be needed if the core takes care of this use case of a different connection for Accounts
//hack block 2***********
Accounts.users = new Meteor.Collection('users', {
connection: connection
});
//hack block 2***********
Tracker.autorun(function () {
//No code which directly affects the functionality. Just for testing
console.log(Meteor.user());
Accounts.connection.call('user',function(err,result){
if(err)
console.log(err);
if(result){
console.log(result);
if(result._id === Meteor.user()._id){
console.log("Server and client shows that the same user has logged in");
} else {console.log("Server and client shows different users");}
}
})
});
Template.register.events({
'submit #register-form' : function(e, t) {
e.preventDefault();
var email = t.find('#account-email').value
, password = t.find('#account-password').value;
Accounts.createUser({email:email,password:password}, function(err,result){
if (err) {
// Inform the user that account creation failed
console.log(err);
} else {
// Success. Account has been created and the user
// has logged in successfully.
console.log("registered user");
console.log('response is '+ result);
console.log(Meteor.user());
}
});//createUser
return false;
}
});//register
Template.login.events({
'submit #login-form': function(e,t){
e.preventDefault();
var email = t.find('#login-email').value
, password = t.find('#login-password').value;
Meteor.loginWithPassword(email, password, function(err){
if (err)
console.log(err);
else
// The user has been logged in.
console.log('logged in successfully');
});
return false;
}
});//login
Template.statusloggedin.events({
'click #logout': function(e,t){
e.preventDefault();
Meteor.logout();
return false;
}
});//logout
}

Categories

Resources