我已经围绕 google 和 stackoverflow 查看了有关此主题的其他一些问题,但似乎找不到正确的解决方案。我正在尝试使用foursquare对应用程序的用户进行身份验证。当用户使用foursquare登录时,我想在数据库中创建一个用户并存储他们的一些信息。这一切都很好。同时,我想以经过身份验证的用户身份登录他们。这是我遇到麻烦的地方。我的观点是这样的:
def foursq_done(request):
# get the access_token
access_token = request.session.get('access_token')
print access_token
# request user details from foursquare
params = {'oauth_token': access_token}
data = urllib.urlencode(params)
url = 'https://api.foursquare.com/v2/users/self'
full_url = url + '?' + data
print full_url
response = urllib2.urlopen(full_url)
response = response.read()
user_data = json.loads(response)['response']['user']
name = user_data['firstName']
try:
user = User.objects.get(username=user_data['contact']['email'])
except User.DoesNotExist:
# Save information on user
user = User.objects.create_user(username=user_data['contact']['email'],
first_name=user_data['firstName'], last_name=user_data['lastName'],
email=user_data['contact']['email'], password=access_token)
profile = Profile()
profile.user = user
profile.oauth_token = access_token
profile.save()
user = authenticate(username=user_data['contact']['email'], password=access_token)
login(request, user)
# show the page with the user's name to show they've logged in
return TemplateResponse(request, 'foursq_auth/foursq_welcome.html', {'name': name}
这与我之前创建 Django 用户时使用的登录过程相同,如下图所示:
def user_signup(request):
if request.method == 'POST':
form = forms.UserSignupForm(data=request.POST)
if form.is_valid():
user = form.save()
g = Group.objects.get(name='test_group')
g.user_set.add(user)
# log user in
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, u'Welcome to Social FollowUp')
return redirect('user_create')
else:
form = forms.UserSignupForm()
return TemplateResponse(request, 'user_signup.html', {
'form': form,
})
我希望我的foursquare登录过程得到相同的结果——用户经过身份验证并登录/识别为Django用户。相反,我一直看到这个错误:
Internal Server Error: /tattoo/foursquare/done/
Traceback (most recent call last):
File "/Users/triplec1988/projects/tattoo/venv/lib/python2.7/site- packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/triplec1988/projects/tattoo/tatt2me/web_tatt2me/views.py", line 106, in foursq_done
login(request, user)
File "/Users/triplec1988/projects/tattoo/venv/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 92, in login
request.session[BACKEND_SESSION_KEY] = user.backend
File "/Users/triplec1988/projects/tattoo/venv/lib/python2.7/site-packages/django/utils/functional.py", line 203, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute 'backend'
我不希望foursquare 用户成为AnonymousUser,但很明显,当我运行authenticate() 时有些东西不起作用。我究竟做错了什么?