Ember-Facebook-login-Django-Rest-Framework_imagefull

in Ember JS

Ember, Facebook login & Django Rest Framework

Recently on a new project we are creating I wanted to create a Facebook login mechanism thatĀ integrated well with the current Django authentication system.

The goal was that users trying to access our ember application had to be authenticated. Since we use some of the Facebook API internally to fetch photos and more, we require that the user authenticates via a “Login with facebook” button. If the user try to access our app he will get redirected to the /login route if he is not already authenticated.

Backend

I will not go into too much detail here, as you can use any type of backend. Though I assume you are using Django and are already using Django Rest Framework. You will need some kind of authentication, and for this we will use OAuth2.

You should follow this guide to setup Django Rest Framework with OAuth2 and facebook login. The guide is really good and just works out of the box.

Installing ember-simple-auth

First of all, we’re assuming you already started playing with Ember-cli, and you want to create a login.

Let’s install simple-auth first, which is a great plugin for dealing with authentication in ember:

 

This will install simple-auth. Which we will depend on when creating the login with facebook button.

 

Loading facebook SDK

We need the facebook JS SDK to add a login with facebook button.

Create a new file in your app folder named initializers and add this:

app/initializers/facebook.js

 

  • This will load the facebook SDK and wait for the SDK to be loaded before the app runs.
  • You see that we include

 

TheĀ ConvertTokenAuthenticator

When a user logins with the facebook SDK, we get a facebook access token. The facebook access token is useless before we actually can connect this to an actual user in our own database. So we have the /auth/convert-token api for this.

Lets implement it:

app/authenticators/ConvertTokenAuthenticator.js

  • We reuse the simple-auth-oauth2 authenticator and only provide some mechanism to convert a social token to an actual real access_token.

 

Configuring environment variables

Lets make some configuration,

config/environment.js

 

The Routes

app/router.js

Users who are not logged in must be redirected to /login

app/routes/application.js

  • This will make sure that user is redirected to /login if he was not authenticated yet.

The Login Controller

app/controllers/login.js

The login template

app/templates/login.hbs

 

 

Share this post

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Write a Comment

Comment