Firebase Authentication with Web component and HTML

MIT provide a firebase component for working with key:value pairs on the realtime database, however there is no component for authenticating a user on firebase, or for giving authenticated read write permission. There are extensions (paid and free) for this. However, it is quite possible to sign up, sign in and sign out an authenticated user, and provide read write to secure rules, using the web component and some html in a webviewer.

HTML


<!DOCTYPE html>

<html>

<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>

<meta charset="utf-8">


<head>

  <title>FB-AUTH-AI2</title>

  

  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>

  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>

  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>

 

</head>


<body>


<script>

var user;


//get webviewstring list from app

var wvstr = window.AppInventor.getWebViewString();


//set the firebase configuration from webviewstring

var firebaseConfig = {

  apiKey: wvstr.split(",")[0],

  authDomain: wvstr.split(",")[1],

  databaseURL: wvstr.split(",")[2],

  projectId: wvstr.split(",")[3],

  storageBucket: wvstr.split(",")[4],

};


//getemail and password from user for create or login

var email = wvstr.split(",")[6];

var pass = wvstr.split(",")[7];


//initialise firebase

firebase.initializeApp(firebaseConfig);

var auth = firebase.auth();

var db = firebase.database();


//login user

if ( wvstr.split(",")[5]  == 'SIGNIN' ) {

  auth.signInWithEmailAndPassword(email,pass);

 var user = auth.currentUser;

};


//signup user

if ( wvstr.split(",")[5]  == 'SIGNUP' ) {

 auth.createUserWithEmailAndPassword(email,pass);

 var user = auth.currentUser; 

}


//signout user

if ( wvstr.split(",")[5]  == 'SIGNOUT' ) {

 auth.signOut(); 

}


//check auth status of user

auth.onAuthStateChanged(function(user) {

 if (user) {

  window.AppInventor.setWebViewString(JSON.stringify(user));

 } else {

     window.AppInventor.setWebViewString('user signed out');

 }

});


</script>

</body>


</html>

In essence, we send all the data required by the html file to it via the webviewstring as a list. The html file then configures firebase, then gets the method (SIGNUP or SIGNIN) from the webviewstring list to activate the correct function. The auth status of the user is checked, and this info is sent back to the app through the webviewstring. The app picks up the idToken and uses this to authenticate REST interaction with the secure area of the database.

BLOCKS


Please note the different method used to set the development and compiled urls for the html file in assets