Today we are going to dive into creating a simple application with Facebook authentication using ember-simple-auth and Torii.

Ember Simple Auth is a lightweight library for implementing authentication with Ember.js applications. It handles all the session data and makes it really easy to authenticate against external providers or your own server. For the purposes of this tutorial we'll stick with authenticating against Facebook.

Torii is a set of abstractions that is built with a number of providers and a session manager. We'll be using the facebook-oauth2 provider that comes with Torii.

Getting Started

We'll assume that you already have Ember CLI installed.

ember new AuthExampleApp
cd AuthExampleApp
npm install torii --save-dev
ember install:addon ember-cli-simple-auth
ember install:addon ember-cli-simple-auth-torii

The last command will install the ember-cli-simple-auth addon. You'll need both addons and the torii npm for everything to work, at least as of ember-cli 0.2.0-beta.1.

Next we'll need to edit the config/environment.js file and add our authorizer. Since we are using Torii we have several built in providers we can use. We'll go ahead and configure the one for Facebook.

// config/environment.js
...
ENV['torii'] = {
    providers: {
      'facebook-oauth2': {
        apiKey: '410282359085824',
        redirectUri: 'http://localhost:4200'
      }
    }
  };


  return ENV;

The 'apiKey' you'll need to retrieve when you create your application in Facebook (the api key shown above is for a sample app I setup). Check out the Facebook login site for more information.

Just to make sure we don't have any issues with CSP we'll add another few lines to the environment.js file

// config/environment.js
...
   APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    contentSecurityPolicy: {
          'default-src': "'none'",
          'script-src': "'self' 'unsafe-inline' 'unsafe-eval'",
          'font-src': "'self'",
          'connect-src': "'self'",
          'img-src': "'self'",
          'report-uri':"'localhost'",
          'style-src': "'self' 'unsafe-inline'",
          'frame-src': "'none'"
        }

Now we won't have to worry about any warnings in the console.

Routes and Templates

Let's generate some routes and templates.

ember g route logout
ember g route login
ember g template index
ember g controller login

Ember Simple Auth comes with several application mixins. Let's set one up with the application route. By adding the ApplicationRouteMixin to the application route we can now access the session property from anywhere in our program.

// app/routes/application.js

import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin);

});

Next we'll add an action to the login route.

// app/routes/login.js

import Ember from 'ember';

export default Ember.Route.extend({
    actions: {
        facebookLogin: function() {
            this.get('session').authenticate('simple-auth-authenticator:torii', 'facebook-oauth2').then(function () {
                alert("logged in");
            });;
            return;
        }
    }
});

The 'alert' is just an example of what we can do after the authenticate promise returns. At this point we could transition to another route if necessary.

We'll need to setup the login controller next.

// app/controller/login.js

import Ember from 'ember';
import LoginControllerMixin from 'simple-auth/mixins/login-controller-mixin';

export default Ember.Controller.extend(LoginControllerMixin, {
      authenticator: 'authenticator:torii'
});

This LoginControllerMixin is needed for the authentication mechanism to login.

On to the templates! We want the index template to show a link to login or logout.

// app/templates/index.hbs

{{#if session.isAuthenticated}}
    Welcome logged in user!
    If you like to logout click {{#link-to 'logout'}}here{{/link-to}}
{{else}}
    Click here to {{#link-to 'login'}}login!{{/link-to}}
{{/if}}

The 'if' handlebars helper uses session to determine if the user is authenticated or not. If they are it gives a link to logout. If they aren't it gives a link to login.

We need the template for login now.

// app/templates/login.hbs

<h3>Login Route</h3>
<button {{action 'facebookLogin'}}>Login with Facebook</button>

And logout!

// app/templates/logout.hbs

    <h3>Logout</h3>
    <button {{action 'invalidateSession'}}>Logout</button>

That should be it.

Protected Route

Just for fun let's create a protected route. You'll only be able to access this route if you're logged in. If not you'll be redirected back to the application route.

ember g route protected

We'll be using the AuthenticatedRouteMixin to protect this route.

We'll need to add the mixin to the controller.

// routes/protected.js
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin);

Now we can put anything in the template and it should be protected

// app/templates/protected.hbs
<h1>Protected Route</h1>
You should only see this if you're logged in!

Fire up 'ember serve' and try to go to the /protected route. You'll notice how it redirects you back. Try again after logging in. It should allow you in now.

Future

I'll be adding my code to github soon. I'll be honest ember simple auth and torii can get complicated. This is a good start to understand how it works.

What do you think of Ember Simple Auth and Torii? Leave a comment below.

Image Credit

Ember Authentication Tutorial with Ember Simple Auth