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 8716819
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T06:10:39+00:00 2026-06-13T06:10:39+00:00

I have created a cookie middleware that checks for a cookie named AUTHENTICATION, this

  • 0

I have created a cookie middleware that checks for a cookie named AUTHENTICATION, this cookie is set on a external system on a subdomain. The code seems to be working, but sometimes I get an error email from the site:

File "/home/users/webuser/virtualenvs/production/lib/python2.7/site-packages/django-trunk/django/core/handlers/base.py", line 93, in get_response
response = middleware_method(request)

File "/home/users/webuser/virtualenvs/production/projectname/projectname/CookieMiddleware.py", line 21, in process_request
login(request, user)

File "/home/users/webuser/virtualenvs/production/lib/python2.7/site-packages/django-trunk/django/contrib/auth/__init__.py", line 70, in login
request.session[SESSION_KEY] = user.id

AttributeError: 'NoneType' object has no attribute 'id'

Here is my CookieMiddleware.py

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User

#Authentication Middleware using a external cookie named AUTHENTICATION
class CookieMiddleware(object):

    def process_request(self, request):
        if "AUTHENTICATION" not in request.COOKIES:
            #Cookie not found - do nothing
            return
        #Token found - first check if the user is allready is logged in
        if request.user.is_authenticated():
            return

        #Not logged in, then send to RemoteUserBackend.py    
        token = request.COOKIES["AUTHENTICATION"]

        user = authenticate(token=token)
        request.user = user
        login(request, user)

Here is my RemoteUserBackend.py

from django.conf import settings
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User, Group
from base64 import b64decode
from hashlib import sha1
from urllib import unquote
from suds.client import Client
from bs4 import BeautifulSoup

class Backend( object ):
        def authenticate(self, username=None, password=None, token=None):

            #Unescape token
            unescaped_token = unquote(token)

            #Decode token
            decoded_token = unescaped_token.decode('base64')

            #Split the token into tree variable
            secret, hashstring, userID = decoded_token.split('-', 2)

            #Secret needs to bee in lower to match shared secret
            secret_lower = secret.lower()

            #Make string of SHARED_SECRET, hashstring, userID
            check_string = "%s%s%s" % (settings.SHARED_SECRET, hashstring, userID)

            #sha1 the string
            sha1_check_string = sha1(check_string)

            #Check if the SHARED_SECRET is matching cookie secret
            cookie_valid = sha1_check_string.hexdigest() == secret_lower


            #Url to WSDL file
            url = 'http://f.domain.com/webservice/Person.cfc?wsdl'

            #Make SUDS.Client from WSDL url
            client = Client(url)

            #Make dict with parameters for WSDL query
            d = dict(CustomerId='xxx', Password='xxx', PersonId=userID)

            #Get result from WSDL query
            result = client.service.GetPerson(**d).encode("UTF-8")

            #Soup the result
            soup = BeautifulSoup(result)

            #Make groupname variable
            self.groupname = soup.personrecord.membersubcatshortname.string

            #Check if the groupname is empty
            if len(self.groupname) == 0:
                self.groupname = "allaccess"


            #Firstname
            self.first_name = soup.personrecord.firstname.string.encode("UTF-8")

            #Lastname
            self.last_name = soup.personrecord.lastname.string.encode("UTF-8")

            #Email
            self.email = soup.personrecord.email.string

            if len(self.email) == 0:
                self.email = "none@email.com"

            #Find what group the user has
            if 'low' in self.groupname:
                g = Group.objects.get(name='lowaccess') 
            elif 'all' in self.groupname:
                g = Group.objects.get(name='allaccess') 



            if cookie_valid:
                try:
                    user = User.objects.get(username=userID)

                    #The user exist, then update the user

                    #Clear all old groups, they could have changed since last login
                    user.groups.clear()
                    #Add the group
                    g.user_set.add(user) 


                except User.DoesNotExist:
                    # Create a new user

                    user = User(username=userID, first_name=self.first_name, last_name=self.last_name, email=self.email)
                    user.is_staff = False
                    user.is_superuser = False


                    user.save() #Save the user
                    g.user_set.add(user) #Add the group
                return user
            return None

        def get_user(self, user_id):
            try:
                return User.objects.get(pk=user_id)
            except User.DoesNotExist:
                return None

What can I do, to prevent the error from happening?

  • 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-06-13T06:10:40+00:00Added an answer on June 13, 2026 at 6:10 am

    In your CookieMiddleware.py:

    user = authenticate(token=token)
    request.user = user
    login(request, user)
    

    user maybe None and has no attributes, you should check it first

    if request.user:
        login(request, request.user)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have my own asp.net cookie created like this: var authTicket = new FormsAuthenticationTicket(
Say I have a PHP script that creates a cookie that expires 10 days
I have an ASP.NET Login App that creates a cookie called 'ASP_LOGIN77' and gives
I have created some JQuery that will expand a div 'popup' on hover and
I have created an android application that calls (using kSOAP library) a SOAP based
Am using WAMP server for PHP development. I have created a cookie in my
I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie..
i have created a cookie with: $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] :
I have created a facebook app that will be displayed on my companies fan
I have created page that every new user is redirected to upon visit, it

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.