Live Example at firebaselink.hightechtele.com
This code demonstrates implementation of Authenticate with Firebase Anonymously Using JavaScript paired with Authenticate with Firebase Using Email Link in JavaScript.
Users can add an apple to their shopping cart without having authenticated. This functionality is enabled by creation of an anonymous account and corresponding Firestore record with realtime listener attached.
Anonymous users can authenticate via an email link and have their shopping cart merged with their new authenticated account's cart via account linking, account deletion, and Firestore record deletion.
NOTE: An actual shopping cart implementation would likely include a cart field conatining the id of a cart which would be stored in a separate collection, i.e., this is an oversimplified shopping cart implementation.
- Account linking and Firestore record merging and finally deletion of orphaned account and record are explicitly coded.
- URL query parameters in the email link are consumed and quickly stripped / erased from the URL bar via JavaScript.
- Anonymous user accounts and associated Firestore records are orphaned upon signout, therefore we prompt anonymous users to confirm signout.
Firebase's Firestore, Hosting, and Authentication systems. This code utilizes the async / await coding pattern therefore browser code shuold include a polyfill such as Babel's polyfill.js.
Paste your Firebase web project's specific configuration parameters into the top of the script.js
file.
Enable Anonymous and Email/Password authentication methods in your Firebase project.
Edit the Action URL in the Authentication Template at firebase.google.com's Console. Strip off extraneous paths leaving the homepage only.
Test the behavior of the authentication system.
- Sign in with no apples in cart.
- Close page/browser then return to page. Are you still signed in?
- Sign Out.
- While signed out, add an apple (or several) to your cart. Notice you are now signed in as anonymous.
- Try and sign out. Notice you are prompted that you will lose changes, i.e. your apples/cart if you signout.
- From the anonymous state with apples in your cart, click sign in. What is your user uid after you have authenticated?
- Check your Firebase Console. Are the orphaned user account and Firestore record deleted?
- Sign in while already signed in. Notice how nothing changes.
- Sign in (using same email) from another device. Are your apples there in your cart?
- High Tech Telecom LLC - High Tech Telecom LLC
It's free. No warranty.