【问题标题】:Authenticating django with Authomatic - Best workflow使用自动的身份验证 django - 最佳工作流程
【发布时间】:2015-04-04 01:25:11
【问题描述】:

我刚开始在 Django 中工作,这太棒了!

我希望有限数量的人可以通过他们的 twitter 帐户访问我的 web 应用程序。为了实现这一点,我使用了插件 Authomatic。

This 是一个入门示例,展示了如何在 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

我的问题如下:在检查用户名是否是允许的 twitter 用户之一后,我如何登录以便用户可以浏览所有受保护的页面?我习惯使用这样的东西:

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)

但问题是 twitter 用户没有分配给他们的 User 对象。我唯一能想到的就是在我的代码中硬编码一个默认的“允许”用户,但这似乎很狡猾......

编辑:我试图实现 Ashwin 的答案,但这给了我这个:

# 我们需要适配器的响应对象。 响应 = 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)

首先,我无法想象在我的代码中使用这样的密码编写器是一种很好的做法。其次,我收到错误提供者名称“用户名”未指定!

有人知道我做错了什么吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以为所有允许的用户创建单独的用户对象,那么这项工作将非常容易。只需检查用户名在数据库中是否可用,验证并登录请求。

    【讨论】:

    • 感谢您的回答,但如果我没有密码,如何验证这些用户对象?
    • @user3361028:您可以使用无密码身份验证。这应该会有所帮助:stackoverflow.com/questions/2787650/…
    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 2016-07-09
    • 2011-08-17
    • 2016-09-16
    • 1970-01-01
    • 2021-07-20
    • 2018-06-21
    • 2016-01-27
    相关资源
    最近更新 更多