Firebase — event listeners and user verification flow.
After working with basic Firebase queries for a while, I’ve started to dig deeper into the framework, and have been trying to get a feel for another important feature of it — listeners. Some of the syntax can be confusing at first, but gradually it has been making more sense to me, and I’m also starting to think about some of the powerful potential of listeners for things such as change tracking, notifications, and user verification flows.
Basically listeners in Firebase, allow for an app to have a constant way of checking whether something has been changed in the FB data, and if so call functions or react to changes.
The main listener method in FB is on(), which also comes with three types of events to listen to ->
child_changed, child_added, child_removed
https://www.firebase.com/docs/web/api/query/on.html
In the example below, listeners are being used to see whether there are changes to the user data store, and notify us if something has occurred.
users.on(‘child_changed’, function(snap) {
console.log(‘child changed in users!’, snap.val());
})
users.on(‘child_added’, function(snap) {
console.log(‘child added in users!’, snap.val());
})
users.on(‘child_removed’, function(snap) {
console.log(‘child_removed in users!’, snap.val());
})I think that listeners are powerful in terms of keeping track of things that are changing in the data, and perhaps notifying users of certain changes or creating user verification flows that are independent of the client side of the app.
For example, in a recent app that I’ve been working with, there is the client side which uses a Cordova plugin (url scheme): https://github.com/EddyVerbruggen/Custom-URL-scheme
The plugin allows users to access the app via a URL/ token, and in order to have a secure method of verifying that the token has been entered we can use a global handleOpenUrl function at the top of app.js:
function handleOpenURL(url) {
var body = document.getElementsByTagName(“body”)[0];
var root = angular.element(body)
.scope();
root.reportAppLaunched(url);
};Basically when the user clicks on the link with a token, it redirects them to the app, and after being redirected, the app calls reportAppLaunched(url) from $rootScope, and parses the URL, and also sets the token at a temporary location on their user/settings path in Firebase. Once the location has been set in Firebase, the backend/node server which is constantly running can listen for the change using:
users.on(‘child_changed’, function(snap) {
makeComparison(snap.val());
})and once it sees the change, it can securely compare the user token that has been entered on the backend to the secure token stored in the backend, and if it is a match, the user will be added to the verified list, and be able to access the app.