我刚开始在Django工作,它太棒了!
我希望我的网络应用程序可以被有限数量的人使用他们的推特帐户访问。为了实现这一点,我使用了插件Authomatic。
这是一个入门示例,展示了如何在Django中使用Authomatic。从这个,我使用以下代码狙击坑:
def login(request, provider_name):
# We we need the response object for the adapter.
response = HttpResponse()
# Start the login procedure.
result = authomatic.login(DjangoAdapter(request, response), provider_name)
if result:
response.write('<a href="..">Home</a>')
elif result.user:
if not (result.user.name and result.user.id):
result.user.update()
var username = result.user.name
var id = result.user.id
return response
我的问题如下:在检查用户名是否是允许的推特用户之一后,我如何登录,以便用户浏览所有受保护的页面?我习惯于使用这样的东西:
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
但问题是twitter用户没有为他们分配User对象。我唯一能想到的就是在代码中硬编码一个默认的"允许"用户,但这似乎很不可靠。。。
编辑:我试图实现阿什温的答案,但这给了我这个:
#我们需要适配器的响应对象。response=HttpResponse()
# Start the login procedure.
result = authomatic.login(DjangoAdapter(request, response), provider_name)
if result:
response.write('<a href="..">Home</a>')
if result.error:
# Login procedure finished with an error.
response.write('<h2>Damn that error: {0}</h2>'.format(result.error.message))
elif result.user:
# We need to update the user to get more info.
if not (result.user.name and result.user.id):
result.user.update()
# Welcome the user.
response.write(u'<h1>Hi {0}</h1>'.format(result.user.name))
response.write(u'<h2>Your id is: {0}</h2>'.format(result.user.id))
response.write(u'<h2>Your email is: {0}</h2>'.format(result.user.email))
# if result.user.id == 110740012624414845989:
uname = result.user.id
pwd = '** RANDOM PASSOWRD I SHOULD HAVE? **'
user = authenticate(username=uname, password=pwd)
login(request, user)
首先,我无法想象在我的代码中有一个这样的密码编写器是一个好的做法。第二,我得到错误的提供者名称"用户名"没有指定!
有人知道我做错了什么吗?
您可以为所有允许的用户创建单独的User对象,那么这项工作将非常容易。只需检查数据库中的用户名是否可用,验证并登录请求即可。