Google+ Using Firebase With Angular, Authentication, and MVC

Peter Bromberg's .NET Blog All Things Programming

Using Firebase With Angular, Authentication, and MVC

26. July 2013 10:50 by admin in Angular, Firebase, Jquery
 

Firebase lets you create fully interactive apps with just frontend code. Stop thinking about servers and databases and focus on your application logic and your customers.

Apps built with Firebase respond immediately to data changes as they occur, bringing a whole new level of interactivity to your users.

Data stored in Firebase is directly accessible from the client. This means you can build dynamic, data-driven websites without worrying about servers or server code.

Firebase also supports authentication via a number of providers including Persona (BrowserID), Facebook, and Twitter.  Here is a demo “ToDo” MVC app using firebase as the back end.

First, the login page:

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">
  <title>Firebase Simple Login</title>
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/reset.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/text.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/960.css">
  <link rel="stylesheet" href="http://firebase.github.io/firebase-simple-login/css/style.css">
  <script type="text/javascript" async="" src="js/ga.js"></script><script type="text/javascript" src="js/prettify.js"></script><style type="text/css">
                                                                                                                                                                                     </style>
</head>
<body onload="prettyPrint();">

  <div class="header">
    <div id=loggy class="ribbon"></div>
  </div>
&nbsp;<div class="container_12">

    <div class="grid_12">
      <br>
      <div class="box">
        &nbsp;</div>
    </div>

    <div class="clear"></div>
    <div class="grid_4">
      <br>
      <div class="box">
        <fieldset>
          <legend class="bold">Supported Providers</legend>
          <div class="content">
            <p>
              Click any of the links below to log in.
            </p>
            <div class="example facebook">
              <div class="icon"></div>
              <div class="description">
                <h4>Facebook</h4>
                <p><a href="javascript:login('facebook');">Log In »</a></p>
              </div>
            </div>
            <div class="example persona">
                <div class="icon">
                </div>
                <div class="description">
                    <h4>Persona</h4>
                    <p><a href="javascript:login('persona');">Log In »</a></p>
                </div>
            </div>
            <div class="example twitter">
              <div class="icon"></div>
              <div class="description">
                <h4>Twitter</h4>
                <p><a href="javascript:login('twitter');">Log In »</a></p>
              </div>
            </div>
            <div class="example password">
              <div class="description">
              </div>
            </div>
          </div>
        </fieldset>
      </div>
    </div>
    <div class="grid_8">
      <br>
      <div class="box">
        &nbsp;</div>

    </div>

    <div class="clear"></div>
    <div class="grid_12">
      <img src="js/hr.png">
    </div>

    <div id="contact">
      <div class="clear"></div>
      <div class="grid_4 prefix_4 suffix_4 center">
        <br>
      </div>

      <div class="clear"></div>
      <div class="grid_5 prefix_1 center">
      </div>
      <div class="grid_5 suffix_1 center">
      </div>
    </div>
  </div>

  <script type="text/javascript" src="js/firebase.js"></script>
  <script type="text/javascript" src="js/firebase-simple-login.js"></script>
  <script type="text/javascript" src="js/include.js"></script>
  <script type="text/javascript">
    var href = document.location.href;
    // FirebaseSimpleLogin demo instantiation
    var firebaseRef = new Firebase("https://peterbromberg.firebaseio.com");
    var auth = new FirebaseSimpleLogin(firebaseRef, function(error, user) {
      if (error) {
        // an error occurred while attempting login
        alert(error);
      } else if (user) {
        // user authenticated with Firebase, redirect to the app
        window.location.href='ToDo.html?id=' +user.id;

      // Log out so we can log in again with a different provider.
      // auth.logout();
      } else {
        // user is logged out
      }
    });
    function login(provider) {
      auth.login(provider);
    }

  </script>
<iframe style="display: none;"></iframe><iframe src="js/lp.htm" style="display: none;"></iframe></body></html>

 

I am showing the facebook, Twitter, and Persona login options. The live demo I’ll send you to at the end only has Persona enabled,

but it is a fully working app. What I do is after getting the user authenticated, I suffix the firebase endpoint with their User Id,

which is usually your email as the path. This ensures that each user has their own data store and cannot see others’.

Next is the ToDoctrl.js script, which loads in the todo.html page that we are redirected to from above:

/*global todomvc */
'use strict';

/**
* The main controller for the app. The controller:
* - retrieves and persist the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', ['$scope', '$location', 'angularFire', 'filterFilter',
    function TodoCtrl($scope, $location, angularFire, filterFilter) {
        //  this is mine, suggest you get your own free firebase url here: https://www.firebase.com/pricing.html
        var url = "'https://peterbromberg.firebaseIO.com/todomvc" + getQueryVariable('id');
        url = url.replace(',', '');
        var promise = angularFire(url, $scope, 'todos');

        $scope.newTodo = '';
        $scope.editedTodo = null;

        if ($location.path() === '') {
            $location.path('/');
        }
        $scope.location = $location;

        promise.then(function(todos) {
            startWatch($scope, filterFilter);
        });
    }
]);

function startWatch($scope, filter) {
    $scope.$watch('todos', function () {
        $scope.remainingCount = filter($scope.todos, {completed: false}).length;
        $scope.completedCount = $scope.todos.length - $scope.remainingCount;
        $scope.allChecked = !$scope.remainingCount;
    }, true);

    $scope.$watch('location.path()', function (path) {
        $scope.statusFilter = (path === '/active') ?
            { completed: false } : (path === '/completed') ?
            { completed: true } : null;
    });

    $scope.addTodo = function () {
        if (!$scope.newTodo.length) {
            return;
        }

        $scope.todos.push({
            title: $scope.newTodo,
            completed: false
        });

        $scope.newTodo = '';
    };

    $scope.editTodo = function (todo) {
        $scope.editedTodo = todo;
    };

    $scope.doneEditing = function (todo) {
        $scope.editedTodo = null;
        if (!todo.title) {
            $scope.removeTodo(todo);
        }
    };

    $scope.removeTodo = function (todo) {
        $scope.todos.splice($scope.todos.indexOf(todo), 1);
    };

    $scope.clearCompletedTodos = function () {
        $scope.todos = $scope.todos.filter(function (val) {
            return !val.completed;
        });
    };

    $scope.markAll = function (completed) {
        $scope.todos.forEach(function (todo) {
            todo.completed = completed;
        });
    };
}

 

The rest is boilerplate Angular.js for the databinding. You can try out the demo here:

http://www.peterbromberg.net/firebase/index.htm

Be sure to login via Persona, as Facebook and Twitter authentication are not enabled on my demo. You can download a complete Visual Studio 2012 solution here:

FirebaseToDo.zip (263.07 kb)

Add comment

  Country flag


Loading