0
我創建了一個cookie中間件,用於檢查名爲AUTHENTICATION的cookie,該cookie在子域上的外部系統上設置。該代碼似乎工作,但有時我從網站上有錯誤的電子郵件:自定義django後端登錄有時會失敗
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 = "[email protected]"
#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
我該怎麼辦,以防止發生錯誤?
太好了!謝謝! –