Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4272006
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T07:31:10+00:00 2026-05-21T07:31:10+00:00

I created a django application with a user login/registration page. I am trying to

  • 0

I created a django application with a user login/registration page. I am trying to implement a facebook login also possible along with my django login. For doing so i was following this link : enter link description here. As the documentaion says, i have created a file called FaebookConnectMiddleware.py and put in settings.py folder; and changed the db name to my db name. Now the facebook log in works fine, but after it logs in, its redirected to that same page (django registration page,dats where i put FB login button).How can i redirect it to another page in my application. Can somebody help me to solve this. I will paste FacebookConnectMiddleware.py code here.

 # FacebookConnectMiddleware.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.conf import settings

import md5
import urllib
import time
import simplejson
from datetime import datetime

# These values could be placed in Django's project settings
# More info here: http://nyquistrate.com/django/facebook-connect/
FACEBOOK_API_KEY = 'xxxxx'
FACEBOOK_SECRET_KEY = 'xxxx'

REST_SERVER = 'http://api.facebook.com/restserver.php'

# You can get your User ID here: http://developers.facebook.com/tools.php?api
MY_FACEBOOK_UID = 'xxx@gmail.com'

NOT_FRIEND_ERROR = 'You must be my Facebook friend to log in.'
PROBLEM_ERROR = 'There was a problem. Try again later.'
ACCOUNT_DISABLED_ERROR = 'Your account is not active.'
ACCOUNT_PROBLEM_ERROR = 'There is a problem with your account.'

class FacebookConnectMiddleware(object):

    def process_request(self, request):
        try:
             # Set the facebook message to empty. This message can be used to dispaly info from the middleware on a Web page.
            request.facebook_message = None

            # Don't bother trying FB Connect login if the user is already logged in
            if not request.user.is_authenticated():

                # FB Connect will set a cookie with a key == FB App API Key if the user has been authenticated
                if FACEBOOK_API_KEY in request.COOKIES:

                    signature_hash = self.get_facebook_signature(request.COOKIES, True)

                    # The hash of the values in the cookie to make sure they're not forged
                    if(signature_hash == request.COOKIES[FACEBOOK_API_KEY]):

                        # If session hasn't expired
                        if(datetime.fromtimestamp(float(request.COOKIES[FACEBOOK_API_KEY+'_expires'])) > datetime.now()):

                            # Make a request to FB REST(like) API to see if current user is my friend
                            are_friends_params = {
                                'method':'Friends.areFriends',
                                'api_key': FACEBOOK_API_KEY,
                                'session_key': request.COOKIES[FACEBOOK_API_KEY + '_session_key'],
                                'call_id': time.time(),
                                'v': '1.0',
                                'uids1': MY_FACEBOOK_UID,
                                'uids2': request.COOKIES[FACEBOOK_API_KEY + '_user'],
                                'format': 'json',
                            }

                            are_friends_hash = self.get_facebook_signature(are_friends_params)

                            are_friends_params['sig'] = are_friends_hash

                            are_friends_params = urllib.urlencode(are_friends_params)

                            are_friends_response  = simplejson.load(urllib.urlopen(REST_SERVER, are_friends_params))

                            # If we are friends
                            if(are_friends_response[0]['are_friends'] is True):

                                try:
                                    # Try to get Django account corresponding to friend
                                    # Authenticate then login (or display disabled error message)
                                    django_user = UniversityDetails.objects.get(username=request.COOKIES[FACEBOOK_API_KEY + '_user'])
                                    user = authenticate(username=request.COOKIES[FACEBOOK_API_KEY + '_user'], 
                                                        password=md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] + settings.FACEBOOK_SECRET_KEY).hexdigest())
                                    if user is not None:
                                        if user.is_active:
                                            login(request, user)
                                            self.facebook_user_is_authenticated = True
                                        else:
                                            request.facebook_message = ACCOUNT_DISABLED_ERROR
                                            self.delete_fb_cookies = True
                                    else:
                                       request.facebook_message = ACCOUNT_PROBLEM_ERROR
                                       self.delete_fb_cookies = True
                                except User.DoesNotExist:
                                    # There is no Django account for this Facebook user.
                                    # Create one, then log the user in.

                                    # Make request to FB API to get user's first and last name
                                    user_info_params = {
                                        'method': 'Users.getInfo',
                                        'api_key': FACEBOOK_API_KEY,
                                        'call_id': time.time(),
                                        'v': '1.0',
                                        'uids': request.COOKIES[FACEBOOK_API_KEY + '_user'],
                                        'fields': 'first_name,last_name',
                                        'format': 'json',
                                    }

                                    user_info_hash = self.get_facebook_signature(user_info_params)

                                    user_info_params['sig'] = user_info_hash

                                    user_info_params = urllib.urlencode(user_info_params)

                                    user_info_response  = simplejson.load(urllib.urlopen(REST_SERVER, user_info_params))


                                    # Create user
                                    user = UniversityDetails.objects.create_user(request.COOKIES[FACEBOOK_API_KEY + '_user'], '', 
                                                                    md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] + 
                                                                    settings.SECRET_KEY).hexdigest())
                                    user.first_name = user_info_response[0]['first_name']
                                    user.last_name = user_info_response[0]['last_name']
                                    user.save()

                                    # Authenticate and log in (or display disabled error message)
                                    user = authenticate(username=request.COOKIES[FACEBOOK_API_KEY + '_user'], 
                                                        password=md5.new(request.COOKIES[FACEBOOK_API_KEY + '_user'] + settings.FACEBOOK_SECRET_KEY).hexdigest())
                                    if user is not None:
                                        if user.is_active:
                                            login(request, user)
                                            self.facebook_user_is_authenticated = True
                                        else:
                                            request.facebook_message = ACCOUNT_DISABLED_ERROR
                                            self.delete_fb_cookies = True
                                    else:
                                       request.facebook_message = ACCOUNT_PROBLEM_ERROR
                                       self.delete_fb_cookies = True
                            # Not my FB friend
                            else:
                                request.facebook_message = NOT_FRIEND_ERROR
                                self.delete_fb_cookies = True

                        # Cookie session expired
                        else:
                            logout(request)
                            self.delete_fb_cookies = True

                   # Cookie values don't match hash
                    else:
                        logout(request)
                        self.delete_fb_cookies = True

            # Logged in
            else:
                # If FB Connect user
                if FACEBOOK_API_KEY in request.COOKIES:
                    # IP hash cookie set
                    if 'fb_ip' in request.COOKIES:

                        try:
                            real_ip = request.META['HTTP_X_FORWARDED_FOR']
                        except KeyError:
                            real_ip = request.META['REMOTE_ADDR']

                        # If IP hash cookie is NOT correct
                        if request.COOKIES['fb_ip'] != md5.new(real_ip + FACEBOOK_SECRET_KEY + settings.FACEBOOK_SECRET_KEY).hexdigest():
                             logout(request)
                             self.delete_fb_cookies = True
                    # FB Connect user without hash cookie set
                    else:
                        logout(request)
                        self.delete_fb_cookies = True

        # Something else happened. Make sure user doesn't have site access until problem is fixed.
        except:
            request.facebook_message = PROBLEM_ERROR
            logout(request)
            self.delete_fb_cookies = True

    def process_response(self, request, response):        

        # Delete FB Connect cookies
        # FB Connect JavaScript may add them back, but this will ensure they're deleted if they should be
        if self.delete_fb_cookies is True:
            response.delete_cookie(FACEBOOK_API_KEY + '_user')
            response.delete_cookie(FACEBOOK_API_KEY + '_session_key')
            response.delete_cookie(FACEBOOK_API_KEY + '_expires')
            response.delete_cookie(FACEBOOK_API_KEY + '_ss')
            response.delete_cookie(FACEBOOK_API_KEY)
            response.delete_cookie('fbsetting_' + FACEBOOK_API_KEY)

        self.delete_fb_cookies = False

        if self.facebook_user_is_authenticated is True:
            try:
                real_ip = request.META['HTTP_X_FORWARDED_FOR']
            except KeyError:
                real_ip = request.META['REMOTE_ADDR']
            response.set_cookie('fb_ip', md5.new(real_ip + FACEBOOK_SECRET_KEY + settings.FACEBOOK_SECRET_KEY).hexdigest())

        # process_response() must always return a HttpResponse
        return response

    # Generates signatures for FB requests/cookies
    def get_facebook_signature(self, values_dict, is_cookie_check=False):
        signature_keys = []
        for key in sorted(values_dict.keys()):
            if (is_cookie_check and key.startswith(FACEBOOK_API_KEY + '_')):
                signature_keys.append(key)
            elif (is_cookie_check is False):
                signature_keys.append(key)

        if (is_cookie_check):
            signature_string = ''.join(['%s=%s' % (x.replace(FACEBOOK_API_KEY + '_',''), values_dict[x]) for x in signature_keys])
        else:
            signature_string = ''.join(['%s=%s' % (x, values_dict[x]) for x in signature_keys])
        signature_string = signature_string + FACEBOOK_SECRET_KEY

        return md5.new(signature_string).hexdigest()

views These functions does the login/registration for the django application.

def registrationForm(request):
    if request.method == "POST":  
        firstName = request.POST.get("firstName")
        lastName = request.POST.get("lastName")
        email = request.POST.get("email")
        password = request.POST.get("password")
        sex = request.POST.get("sex")
        birthday = request.POST.get("birthday")
        UniversityDetails(firstName=firstName,lastName=lastName,email=email,password=password,sex=sex,birthday=birthday).save()

        send_mail('Email Verification', 'You have registered successfully', 'xx@gmail.com',
    ['xx@gmail.com'], fail_silently=False)

        return render_to_response('login.html')

    return render_to_response("registrationForm.html")

def login(request):
    if request.POST:       
        #sessionObj = request.session['active_token']
       # print sessionObj
        email=request.POST.get("username")
        password = request.POST.get("password")
        user = UniversityDetails.objects.filter(email=email,password=password)
        if(not user):
            return render_to_response("registrationForm.html",{'invalid': True })
        else:
            return render_to_response("login.html")
    return render_to_response("registrationForm.html")

registrationForm.html

<div id="fb-root"></div>
  <script src="http://connect.facebook.net/en_US/all.js"></script>
  <script>
   FB.init({ 
        appId:'114322105313139', cookie:true,
        status:true, xfbml:true 
     });
  </script>     
  <fb:login-button perms="email,user_checkins"  onlogin=”location.reload(false);">Login with Facebook</fb:login-button>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T07:31:11+00:00Added an answer on May 21, 2026 at 7:31 am

    I think you just need to declare the variable at the top of your class as false

    class FacebookConnectMiddleware(object):
    
        facebook_user_is_authenticated = False
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.