自定义django后端登录有时会失败

时间:2012-10-20 14:47:04

标签: python django django-authentication

我创建了一个cookie中间件来检查名为AUTHENTICATION的cookie,这个cookie是在子域上的外部系统上设置的。代码似乎有效,但有时我从网站收到错误电子邮件:

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'

这是我的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)

这是我的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

我该怎么做才能防止错误发生?

1 个答案:

答案 0 :(得分:0)

CookieMiddleware.py

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

user可能None并且没有属性,您应该先检查

if request.user:
    login(request, request.user)