Facebook Integration

(0 comments)

This article builds on the excellent tutorial at art and logic without the bootstrap css, but adding lots of screen shots. To have a function application that allows authentication through Facebook, the following tasks occur in order:

  • Create a Facebook application to obtain an application key/secret pair used to access the Facebook Graph API
  • Use the Facebook Graph API (through python social auth in this case) to get third party authentication and authorization credentials from Facebook users.
  • Post to application's personal and business Facebook pages to test
  • Create a FB test user, caching access_key information to then post to their personal and business FB pages to test
  • Apply to Facebook to allow the application to post to real Facebook user accounts

This is a precurser for a tutorial to show Facebook's authorisation process to allow an application to post to user accounts, and we will go through the first two points above.

Create a Facebook App

Log in with your Facebook account to the Facebook Developers area

https://developers.facebook.com

I can't honestly remember if you have to apply for a developer's account, but if you do have to, the process is quite simple. From the My Apps menu select Add a new app. Give your app a name, category and subcategory and save. I called my application Coolaide in this example.

My Facebook App - Coolaide

You will be presented with the app dashboard page. Select Settings from the left hand menu, and from here you need to select +Add Platform so that you can enter the URL your application will be served from.

The FB App Dashboard

Choose the Website platform

Choose *Website* platform

Once That is done, you will be returned to the settings page where you should enter the URL the application is to be served from. As we are working on our local machine for development, set this to http://localhost:8000. NOTE: the http:// is vital.

Development from localhost:8000

Once that is done, take a note of the App ID and App Secret (you may need to enter your FB password to show the secret). We now need to set up the django application. If you are not using virtual environments and have more than one development application on the go, then you need to start doing so. There are plenty of good tutorials. Create your virtual environment

jason:>mkvirtualenv thirdauth

or if you will work out virtual environments later, skip this step. Install the following.

(thirdauth)jason:>pip install Django==1.6.1
(thirdauth)jason:>pip install python-social-auth==0.1.26

Now create your django thirdauth application

django-admin.py startproject thirdauth

We need to update the thirdauth.settings file and add the App ID and App Secret from the newly created app;

# Cool Aide
SOCIAL_AUTH_FACEBOOK_KEY = '326284504245358'
SOCIAL_AUTH_FACEBOOK_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX'

Of course the App Secret should remain just that. The next steps I lifted pretty well out of the tutorial at art and logic

  • Add ‘thirdauth’ to INSTALLED_APPS
  • Create the template for the home page
  • Add a view for the home page
  • Add a URL pointing to the home page view

Add our application and python-social-auth to thirdauth.settings.

INSTALLED_APPS = (
  'django.contrib.admin',
  'django.contrib.auth',
  ...
  'social.apps.django_app.default',
  'thirdauth',
)

Controller

The urls.py needs to include the python social auth namespace to invoke the Facebook API, and django auth for logout.

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'thirdauth2.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    url('', include('social.apps.django_app.urls', namespace='social')),
    url('', include('django.contrib.auth.urls', namespace='auth')),
)

AND IMPORTANTLY, you need to let our application know where to return to after authentication by the third party (Facebook in this case) has occurred. In thirdauth.settings

LOGIN_REDIRECT_URL = '/'

Templates Setup

We now need to add some templates. Create a templates directory in the main project directory, and a directory under that named thirdauth (after the main application). We need to create a base template and a login template, so the directory tree will look like

(thirdauth)jason:>tree thirdauth
thirdauth
├── manage.py
├── templates
│   └── thirdauth
│       ├── base.html
│       └── home.html
└── thirdauth
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

3 directories, 7 files

Of course, you have to let Django know where your templates are, so in thirdauth.settings you need (assuming the app is under /www)

TEMPLATE_DIRS = (
    '/www/thirdauth/templates/',
)

also update thirdauth.settings to include the context processors and authentication backends

TEMPLATE_CONTEXT_PROCESSORS = (
   'django.contrib.auth.context_processors.auth',
   'django.core.context_processors.debug',
   'django.core.context_processors.i18n',
   'django.core.context_processors.media',
   'django.core.context_processors.static',
   'django.core.context_processors.tz',
   'django.contrib.messages.context_processors.messages',
   'social.apps.django_app.context_processors.backends',
   'social.apps.django_app.context_processors.login_redirect',
)

AUTHENTICATION_BACKENDS = (
   'social.backends.facebook.FacebookOAuth2',
   'django.contrib.auth.backends.ModelBackend',
)

Template Code

All we want to do initially is to say hello to a facebook user once logged on, and as I said before, I am not using the Bootstrap CSS used in the original tutorial. So a simple base.html is as follows

<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
   {% block main %}{% endblock %}
 </body>
</html>

It is ridiculously easy to add Google+ and Twitter authentication, and that is gone through in the art and logic tutorial, but here we will keep things simple and stick to Facebook. The home.html is thus

{% extends "thirdauth/base.html" %}

{% block main %}
 <div>
 <h1>Third-party authentication demo</h1>

 <p>
   <ul>
   {% if user and not user.is_anonymous %}
     <li>
       <a>Hello {{ user.get_full_name|default:user.username }}!</a>
     </li>
     <li>
       <a href="{% url "auth:logout" %}?next={{ request.path }}">Logout</a>
     </li>
   {% else %}
     <li>
       <a href="{% url "social:begin" "facebook" %}?next={{ request.path }}">Login with Facebook</a>
     </li>

   {% endif %}
   </ul>
 </p>
 </div>
{% endblock %}

View

The views.py file

from django.shortcuts import render_to_response
from django.template.context import RequestContext

def home(request):
   context = RequestContext(request,
                           {'user': request.user})
   return render_to_response('thirdauth/home.html',
                             context_instance=context)

Create the database and run

(thirdauth)jason:>./manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table social_auth_usersocialauth
Creating table social_auth_nonce
Creating table social_auth_association
Creating table social_auth_code

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use 'jason'): admin
Email address: admin@example.com
Password: 
Password (again): 
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
(thirdauth)jason:>./manage.py runserver
Validating models...

0 errors found
March 19, 2015 - 07:51:43
Django version 1.6.1, using settings 'thirdauth.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

And Bob is your Aunty's live in lover. You should be able to see the login page at

http://localhost:8000

and when you click the login link you will be redirected to Facebook, where you will be given the opportunity to authorize your app to allow third party authentication.

FB user authorizes application coolaide

Once you authorize, you will be redirected back to the application home page that now knows your name and your email address, and salutes you. So, this is the end of part one in a series of articles on social authentication. In Part 2, I will show how to request information from the Facebook user such as birthday and work history, how to safely use authentication tokens to post to your own pages, and to request authority to post to other Facebook users' time lines. This last is the crux of the tutorial, as most applications want to use Facebook as a publishing and promotion tool, and if you can reward users appropriately for posting your articles and blogs, more people will hit your site which boosts your Search Engine Optimization (SEO).

Current rating: 5

Comments

There are currently no comments

New Comment

required

required (not published)

optional