手动登录用户没有密码 [英] Manually logging in a user without password

查看:155
本文介绍了手动登录用户没有密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望您能帮助我了解使用密码实现手动(服务器端启动)登录而不使用的最佳方法。让我解释工作流程:

I hope you can help me figure the best way to implement a manual (server-side initiated) login without using the password. Let me explain the workflow:


  • 用户注册

  • 谢谢!已发送带有激活链接的电子邮件blablabla

  • (帐户现在存在,但未被启用)

  • 用户打开电子邮件,点击链接

  • (帐号已启用)

  • 谢谢!您现在可以使用该网站

  • User registers
  • Thank you! An email with an activation link has been sent blablabla
  • (Account now exists but is marked not enabled)
  • User opens email, clicks link
  • (Account is enabled)
  • Thank you! You can now use the site

我想要做的是在他点击电子邮件链接后登录用户,以便他可以立即开始使用该网站。

What I'm trying to do is log in the user after he has clicked the email link so he can start using the website right away.

我不能使用他的密码,因为它在数据库中加密,是编写自定义身份验证后端的唯一选项? >

I can't use his password since it's encrypted in the DB, is the only option writing a custom authentication backend?

推荐答案

您不需要密码登录用户。 auth.login function just需要一个用户对象,当您启用该帐户时,您可能已经从数据库中获取。所以你可以直接通过登录

You don't need a password to log a user in. The auth.login function just takes a User object, which you are presumably already getting from the database when you enable the account. So you can pass that straight to login.

当然,你需要 请注意,用户无法伪装指向现有已启用帐户的链接,然后会自动将其登录为该用户。

Of course, you'll need to be very careful that there's no way a user can spoof a link to an existing already-enabled account, which would then automatically log them in as that user.

from django.contrib.auth import login

def activate_account(request, hash):
    account = get_account_from_hash(hash)
    if not account.is_active:
        account.activate()
        account.save()
        user = account.user
        login(request, user)

...等。

嗯,没有注意到使用认证的要求因为它添加了额外的属性。看看代码,它所做的只是一个相当于认证后端的模块路径的后端属性。所以你可以假冒它 - 在上面的登录呼叫之前,请执行以下操作:

Hmm, didn't notice that requirement to use authenticate because of the extra property it adds. Looking at the code, all it does is a backend attribute equivalent to the module path of the authenticating backend. So you could just fake it - before the login call above, do this:

user.backend = 'django.contrib.auth.backends.ModelBackend'

这篇关于手动登录用户没有密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆