Skip to content

Instantly share code, notes, and snippets.

@triplec1988
Created June 29, 2013 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save triplec1988/5891167 to your computer and use it in GitHub Desktop.
Save triplec1988/5891167 to your computer and use it in GitHub Desktop.
This is a step by step guide for authenticating and saving users in Django using Foursquare and OAuth without having to use a large library like django-social. This can also be used as a guide for implementing other third party applications (i.e. Instagram, Twitter, etc) as your Django authentication and user creation source. STEP ONE: Register …
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class FoursquareBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(username=username)
return user
except User.DoesNotExist:
print "Looks like this user does not exist"
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
{% extends "base.html" %}
{% block title %}YOUR_APP -- Foursquare{% endblock %}
{% block body %}
<div id="login">
<p>Sign in with Foursquare to begin.</p>
<p><a href="{% url 'foursq_auth' %}">Login</a></p>
</div>
{% endblock %}
{% extends "base.html" %}
{% block title %}YOUR_APP -- Welcome{% endblock %}
{% block body %}
<p>Hi {{ user.first_name }}, you've successfully logged in! </p>
<a href="{% url 'foursq_unauth' %}">Logout</a>
{% endblock %}
##############################
##### FOURSQUARE #####
##############################
FSQ_CLIENT_ID = 'YOUR_CLIENT_ID'
FSQ_CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
FSQ_ACCESS_TOKEN_URL = 'https://foursquare.com/oauth2/access_token'
FSQ_AUTHORIZE_URL = 'https://foursquare.com/oauth2/authenticate'
FSQ_REDIRECT_URL = 'YOUR_REDIRECT_URL'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
'YOUR_APP.backends.FoursquareBackend',)
from django.conf.urls import patterns, url
from YOUR_APP import views
urlpatterns = patterns('',
# Main is where you'll have a button to login via Foursquare
url(r'^foursquare/$', views.foursq_main, name='foursq_main'),
# This is your callback URL
url(r'^foursquare/callback/$', views.foursq_callback, name='foursq_callback'),
# This is the user logout URL
url(r'^foursquare/logout/$', views.foursq_unauth, name='foursq_unauth'),
# This URL calls the Foursquare authentication process
url(r'^foursquare/auth/$', views.foursq_auth, name='foursq_auth'),
# This URL saves the user in auth_user, authenticates and logs them in
url(r'^foursquare/done/$', views.foursq_done, name='foursq_done'),
# This URL is the welcome page after a user has been logged in successfully
url(r'^foursquare/welcome/$', views.foursq_welcome, name='foursq_welcome'),
)
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import *
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
import urllib
import urllib2
import json
from models import *
from YOUR_PROJECT.settings import FSQ_CLIENT_ID, FSQ_CLIENT_SECRET, FSQ_ACCESS_TOKEN_URL, FSQ_AUTHORIZE_URL, FSQ_REDIRECT_URL
##############################
##### FOURSQUARE #####
##############################
def foursq_main(request):
return TemplateResponse(request, 'foursq_auth/foursq_login.html')
def foursq_auth(request):
# build the url to request
params = {'client_id': FSQ_CLIENT_ID,
'response_type': 'code',
'redirect_uri': FSQ_REDIRECT_URL}
data = urllib.urlencode(params)
# redirect the user to the url to confirm access for the app
return redirect('%s?%s' % (FSQ_AUTHORIZE_URL, data))
def foursq_callback(request):
# get the code returned from foursquare
code = request.GET.get('code')
# build the url to request the access_token
params = {'client_id': FSQ_CLIENT_ID,
'client_secret': FSQ_CLIENT_SECRET,
'grant_type': 'authorization_code',
'redirect_uri': FSQ_REDIRECT_URL,
'code': code}
data = urllib.urlencode(params)
req = urllib2.Request(FSQ_ACCESS_TOKEN_URL, data)
# request the access_token
response = urllib2.urlopen(req)
access_token = json.loads(response.read())
access_token = access_token['access_token']
# store the access_token for later use
request.session['access_token'] = access_token
# redirect the user to show we're done
return redirect(reverse('foursq_done'))
def foursq_done(request):
# get the access_token
access_token = request.session.get('access_token')
# request user details from foursquare
params = {'oauth_token': access_token}
data = urllib.urlencode(params)
url = 'https://api.foursquare.com/v2/users/self'
full_url = url + '?' + data
response = urllib2.urlopen(full_url)
response = response.read()
user_data = json.loads(response)['response']['user']
try:
user = User.objects.get(username=user_data['contact']['email'])
except User.DoesNotExist:
# Save information on user
user = User(username=user_data['contact']['email'],
first_name=user_data['firstName'], last_name=user_data['lastName'],
email=user_data['contact']['email'])
user.set_password(access_token)
user.save()
user = authenticate(username=user.username, password=user.password)
login(request, user)
# show the page with the user's name to show they've logged in
return redirect(reverse('foursq_welcome'))
@login_required
def foursq_welcome(request):
user = request.user
return TemplateResponse(request, 'foursq_auth/foursq_welcome.html', {'user': user})
def foursq_unauth(request):
# clear any tokens and logout
request.session.clear()
logout(request)
return redirect(reverse('foursq_main'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment