EzDevInfo.com

firebase interview questions

Top firebase frequently asked interview questions

How can I login with multiple social services with Firebase?

I want users to be able to authenticate to my Firebase application using multiple different auth providers, such as Facebook, Twitter, or Github. Once authenticated, I want users to have access to the same account no matter which auth method they used.

In other words, I want to merge multiple auth methods into a single account within my app. How can I do this in a Firebase app?


Source: (StackOverflow)

Query based on multiple where clauses in firebase

{
"movies": {
    "movie1": {
        "genre": "comedy",
        "name": "As good as it gets",
        "lead": "Jack Nicholson"
    },
    "movie2": {
        "genre": "Horror",
        "name": "The Shining",
        "lead": "Jack Nicholson"
    },
    "movie3": {
        "genre": "comedy",
        "name": "The Mask",
        "lead": "Jim Carrey"
    }
  }  
 }

I am Firebase newbie. How can I retrieve a result from the data above where genre = 'comedy' AND lead = 'Jack Nicholson' ?

What options do I have? Thanks in advance.


Source: (StackOverflow)

Advertisements

How to handle states when logged in (Ionic, Firebase, AngularJS)?

I am building an app in Ionic and have started to dig into the Firebase Authentication method. So far I have managed to setup a Login through Twitter properly (I can login and logout).

However, how do I set the states of the ionic framework such that only specific states (and thus pages) are shown when Logged in and others when Logged out? The code I have so far is shown below.

Ideally I would have something like a variable:

AuthRequired: true

How do you do this and what is it called?

app.js

   // Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'ngCordova', 'firebase', 'firebase.utils', 'starter.controllers', 'starter.services', 'starter.config', 'starter.auth'])

.run(function($ionicPlatform, Auth, $rootScope) {


  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });



  //stateChange event
  $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
      if (toState.authRequired && !Auth.isAuthenticated()){ //Assuming the AuthService holds authentication logic
        // User isn’t authenticated
        $state.transitionTo("login");
        event.preventDefault(); 
      }
  });





})

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "templates/tabs.html"
  })

  // Each tab has its own nav history stack:

  .state('tab.dash', {
    url: '/dash',
    views: {
      'tab-dash': {
        templateUrl: 'templates/tab-dash.html',
        controller: 'DashCtrl',
        authRequired: true
      },
    }
  })

  .state('tab.chats', {
      url: '/chats',
      views: {
        'tab-chats': {
          templateUrl: 'templates/tab-chats.html',
          controller: 'ChatsCtrl',
           authRequired: true
        }
      }
    })
    .state('tab.chat-detail', {
      url: '/chats/:chatId',
      views: {
        'tab-chats': {
          templateUrl: 'templates/chat-detail.html',
          controller: 'ChatDetailCtrl',
           authRequired: true
        }
      }
    })

  .state('tab.friends', {
      url: '/friends',
      views: {
        'tab-friends': {
          templateUrl: 'templates/tab-friends.html',
          controller: 'FriendsCtrl',
           authRequired: true
        }
      }
    })
    .state('tab.friend-detail', {
      url: '/friend/:friendId',
      views: {
        'tab-friends': {
          templateUrl: 'templates/friend-detail.html',
          controller: 'FriendDetailCtrl',
           authRequired: true
        }
      }
    })

  .state('tab.account', {
    url: '/account',
    views: {
      'tab-account': {
        templateUrl: 'templates/tab-account.html',
        controller: 'AccountCtrl',
           authRequired: true
      }
    }
  })

  .state('tab.example', {
    url: '/example',
    views: {
      'tab-example': {
        templateUrl: 'templates/tab-example.html',
        controller: 'ExampleCtrl',
           authRequired: true
      }
    }
  })


  .state('tab.overview', {
    url: '/overview',
    views: {
      'tab-overview': {
        templateUrl: 'templates/tab-overview.html',
        controller: 'OverviewCtrl',
           authRequired: true
      }
    }
  })

  .state('tab.login', {
    url: '/login',
    views: {
      'tab-login': {
        templateUrl: 'templates/tab-login.html',
        controller: 'LoginCtrl',
           authRequired: true
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/dash');

})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link rel='nofollow' href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link rel='nofollow' href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link rel='nofollow' href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>


    <!-- firebase and simple login -->
    <script src="https://cdn.firebase.com/libs/angularfire/0.9.1/angularfire.min.js"></script>
    <script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>


    <!-- cordova script (this will be a 404 during development) -->
    <script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>



  </head>
  <body ng-app="starter">
    <!--
      The nav bar that will be updated as we navigate between views.
    -->
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>
    </ion-nav-bar>
    <!--
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).


    -->

    <ion-nav-view animation="slide-left-right"></ion-nav-view>



  </body>
</html>

Source: (StackOverflow)

Firebase data structure and url

I'm new in Firebase and nosql so bear with me to use reference to sql. So my question is how to structure the data in firebase?

In firebase, is that mean every "new firebase" = "new Database" or "table" in mysql?

If in my real time web app, I have users and comments. In mysql, i will create a users and a comments table then link them together.

How do I structure this in firebase?

Thank in adv


Source: (StackOverflow)

Does firebase handle push notifications?

I am investigating whether firebase and angularfire are a good fit for my upcoming project.

One of the requirements are for users to be notified when the app is closed on new private messages sent to user, ie. push notifications.

Does firebase handle this?


Source: (StackOverflow)

Firebase .NET access

If I want to use Firebase now from .NET in C#, what is your suggestion as the best way to handle the callbacks? I see your current client library is using WebSockets. Can you offer a small example of how best to set this up in C#?


Source: (StackOverflow)

How do you authenticate a server to Firebase?

I have an app written on Firebase. Security rules and client side code aren't quite enough to make my app work. I need to connect a server to do a few tasks:

  • Cleaning up denormalized data that's challenging to clean up using onDisconnect handlers
  • Building additional indexes of my data that go beyond what I can do with queries

Source: (StackOverflow)

What's the best way of structuring data on firebase?

I am new to firebase and I want to know what's the best way of structuring data on it.

I have a simple example:

There are Applicants and Applications on my project. 1 applicant can have several applications . How can I relate this 2 objects on firebase? Does it work like a relational database? Or the approach needs to be completely different in terms of data design?


Source: (StackOverflow)

How does Firebase handle cross origin issues?

Looking through the Firebase FAQ I can't see how cross domain issues are handled. Obviously, we don't want to serve on the Firebase domain, is it CORS, hidden iFrame, other? Would we need to create a sub-domain that points at the IP of the sharing server?


Source: (StackOverflow)

Is there any way to do email confirmation for Firebase user creation and/or password reset?

Question says it all. In Firebase, how do I confirm email when a user creates an account, or, for that matter, do password reset via email.

I could ask more broadly: is there any way to send emails out from Firebase? E.g. notifications, etc. This isn't the kind of thing you would usually do client-side.


Source: (StackOverflow)

Database-style Queries with Firebase

Is there a fast way to perform database-style queries with Firebase?

For example:

Given a firebase reference users with fields user_id, name, and age, what would be the best way to do a query similar to this:

SELECT name FROM users WHERE `user_id`=147;

and

SELECT COUNT(*) FROM users WHERE age=21;

Source: (StackOverflow)

Firebase: How do I update multiple resources atomically?

Firebase allows for a resource to be updated transactionally. As I understand it, the client does this buy sending requests to the server saying "If the old value is X, make the new value Y". If there is contention the server could reject multiple updates form the client until one is accepted.

Now, what if I want to update multiple resources atomically?

What happens if the first update is accepted, and then the client is disconnected prior to the second update being accepted. Is there any way to enclose multiple updates in an atomic transaction? If not, is there an idiomatic solution to this problem?


Source: (StackOverflow)

Firebase.push failed: first argument contains an invalid key ($$hashKey)

I recently started learning AngularJS+Firebase. I'm trying to write in my firebase an object like this:

{
    title: "Personal Information",
    say: [
        [{ "eng": "What's", "ukr": "Що є" }, { "eng": "your", "ukr": "твоє" }, { "eng": "surname?", "ukr": "прізвище?" }],
        [{ "eng": "Smith", "ukr": "Сміт" }],
        [{ "eng": "What's", "ukr": "Що є" }, { "eng": "your", "ukr": "твоє" }, { "eng": "first", "ukr": "перше" }, { "eng": "name?", "ukr": "ім'я?(не фамілія)" }]
    ]
}

with line:

lessondata.add($scope.topic);

where 'lessondata' is service created with angularFireCollection() and $scope.topic - object bound to my UI. But got the following error: Firebase.push failed: first argument contains an invalid key ($$hashKey) in property 'say.0.0'. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"


As I understood Firebase do not allow to use 0 as a key even if it's a key in an attached array for which zero key is natural. So should I change my object structure in some hardcoded instance or I miss something? Thanks in advance!


Source: (StackOverflow)

Proper authorization rules for protected content in firebase

Is there a best practice approach to proper authorization rules for protected content in a firebase app

  • using firepad specifically
  • By protected content I mean where a user creates a document and only shares it with certain other users).
  • Also I need to be able to query firebase for all documents that i have access to (docs that I created and docs other users shared with me)

Some of my research thus far:

Method 1: Secret URL

  • I need to know the URL to be able to view/edit the document

  • Not real authorization, as any logged in user that has access to that URL could edit/modify it.

  • Cant index all the docs i have access to

Method 2: Using firebase authorization rules to add users to a document and check if user is document.users before reading/writing.

Taken From: Protected content in Firebase possible?

{

"documents": {

   "$documents_id": {

       // any friend can read my post

       ".read":  "auth.id === data.child('owner').val() || root.child('users/'+data.child.owner.val()+'/users/'+auth.id).exists()",

       // any friend can edit my post
       ".write": "auth.id === data.child('owner').val() || root.child('users/'+data.child.owner.val()+'/users/'+auth.id).exists()"

   },

   users:{

   // List of user.ids that have access to this document

   }

}

}

Pros:

  • Proper authorization/authentication. Only authenticated users who have been granted access can view/edit.

Cons:

  • Cannot query for all documents a user is allowed to edit (those that I own or have been shared with me) (Is this assumption correct?)

Method 3: Firebase authorization rules (method 2), plus a redundant store of users with array of document_ids each users has access to. This user store would only be used to query all the documents a user has access to. ie:

{
"documents": {
   "$documents_id": {
       // any friend can read my post
       ".read":  "auth.id === data.child('owner').val() || root.child('users/'+data.child.owner.val()+'/users/'+auth.id).exists()",
       // any friend can edit my post
       ".write": "auth.id === data.child('owner').val() || root.child('users/'+data.child.owner.val()+'/users/'+auth.id).exists()"
   }
},
"users":{
    "$user":{
        ".read": "auth.id=$user.id",
        ".write": "auth.id=$user.id"
        "$documents":{
            // All the documents i have access to. This list gets ammended whenever I am granted/stripped access to a document.
        }
    }
}
}

Pros:

  • Proper authentication/authorization

Cons:

  • Duplicate data, have to deal with synchronization issues between two data stores. This just doesnt seem like a good idea.

Method 4: Groups

Using groups per Granting access to Firebase locations to a group of users

  • We have a group for every document in data store

  • Cant easily query firebase for all the docs a user can access

Is there a better way to do this?


Source: (StackOverflow)

In Firebase when using push() How do I pull the unique ID

I'm attempting to add/remove entries from a Firebase database. I want to list them in a table to be added/modified/removed (front end) but I need a way to uniquely identify each entry in order to modify/remove. Firebase adds a unique identifier by default when using push(), but I didn't see anything referencing how to select this unique identifier in the API documentation. Can this even be done? Should I be using set() instead so I'm creating the unique ID?

I've put this quick example together using their tutorial:

<div id='messagesDiv'></div>
<input type='text' class="td-field" id='nameInput' placeholder='Name'>
<input type='text' class="td-field" id='messageInput' placeholder='Message'>
<input type='text' class="td-field" id='categoryInput' placeholder='Category'>
<input type='text' class="td-field" id='enabledInput' placeholder='Enabled'>
<input type='text' class="td-field" id='approvedInput' placeholder='Approved'>
<input type='Button' class="td-field" id='Submit' Value="Revove" onclick="msgRef.remove()">

<script>
var myDataRef = new Firebase('https://unique.firebase.com/');

  $('.td-field').keypress(function (e) {
    if (e.keyCode == 13) {
      var name     = $('#nameInput').val();
      var text     = $('#messageInput').val();
      var category = $('#categoryInput').val();
      var enabled  = $('#enabledInput').val();
      var approved = $('#approvedInput').val();
      myDataRef.push({name: name, text: text, category: category, enabled: enabled, approved: approved });
      $('#messageInput').val('');
    }
  });
  myDataRef.on('child_added', function(snapshot) {
    var message = snapshot.val();
    displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
  });
  function displayChatMessage(name, text, category, enabled, approved, ) {
    $('<div/>').text(text).prepend($('<em/>').text(name+' : '+category +' : '+enabled +' : '+approved+ ' : ' )).appendTo($('#messagesDiv'));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
  };
</script>

Now lets assume I have three rows of data:

fred : 1 : 1 : 1 : test message 1
fred : 1 : 1 : 1 : test message 2
fred : 1 : 1 : 1 : test message 3

How do I go about uniquely identifying row 2?

in the Firebase Database they look like this:

-DatabaseName
    -IuxeSuSiNy6xiahCXa0
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 1"
    -IuxeTjwWOhV0lyEP5hf
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 2"
    -IuxeUWgBMTH4Xk9QADM
        approved: "1"
        category: "1"
        enabled: "1"
        name: "Fred"
        text: "test message 3"

Source: (StackOverflow)