1

我已经围绕 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() 时有些东西不起作用。我究竟做错了什么?

4

2 回答 2

1

现在它只检查标准的 Django 后端,但你必须编写一个自定义的后端,它需要一个通过来自foursquare 的 OAuth 身份验证的用户,并通过 Django 用户身份验证模型对他们进行身份验证。

在 settings.py

AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
                           'YOUR_APP.backends.FoursquareBackend',)

后端.py

from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend


class FoursquareBackend(ModelBackend):
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            return user
        except User.DoesNotExist:
            print "Looks like this user does not exist"
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
于 2014-02-14T00:42:13.623 回答
0

我发现这不起作用的原因是因为我没有自定义后端设置。我写了一个 Gist 描述我是如何做到这一点的,并在这里设置它:https ://gist.github.com/triplec1988/5891167

于 2013-06-29T19:25:59.093 回答