authenticated through Facebook. To do this, I've written a simple
custom authentication backend:
# custom Facebook authentication backend
from django.contrib.auth.models import User
from site_main.models import *
from fb import facebook
class FBAuthBackend:
def authenticate(self, token):
try:
graph = facebook.GraphAPI(token)
profile = graph.get_object("me") # will throw an exception
if token is invalid
uid = profile['id']
# check for existing user
user = self.get_user(uid)
# otherwise create a new user
if user == None:
user = User(username=uid)
#user.set_unusable_password()
user.set_password(User.objects.make_random_password())
user.save()
uprofile = UserProfile(user=user)
uprofile.save()
user.first_name = profile['first_name']
user.last_name = profile['last_name']
user.save()
return user
except:
return None
def get_user(self, user_id):
try:
return User.objects.get(username=user_id)
except:
return None
This backend works fine - it checks the access token it receives and
creates a new user or returns an existing one, as expected.
I have a couple of login-related views:
from models import *
from django.contrib.auth import *
from django.shortcuts import *
from django.http import *
def site_login(request):
if 'token' in request.GET:
u = authenticate(token=request.GET['token'])
if u:
login(request, u)
return redirect('/')
def logintest(request):
return HttpResponse(str(request.user.is_authenticated()))
The authenticate() call works fine - u is assigned a valid user object
where u.is_authenticated() is True. However, once I navigate to any
other page - for example, the URL that calls logintest, the user is no
longer authenticated, i.e. u._is_authenticated() = False. It's almost
as if the login() call never saved the user into the session.
Please help - I am about ready to tear out my hair over this, and this
is stalling the rest of my development!
Thanks!
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment