【问题标题】:DJango: authenticate function vs verifying username, password and is_activeDJango:验证功能与验证用户名、密码和 is_active
【发布时间】:2018-08-10 04:12:09
【问题描述】:

我正在做一个 Django 项目:

我有一个带有用户名和密码的登录表单

通常我观察到authentication函数用于验证用户并通过即

user = authenticate(username, password)

我试图了解身份验证功能,但发现并不那么容易。

我想通过以下方式检查身份验证,而不是使用身份验证功能:

1) 检查用户名是否存在

2) 检查密码是否匹配

3) 检查 is_active 是否为真。

我可以通过以下方式做到这一点:

username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')

# check if user exists
try:
    user = User.objects.get(username=username)
except User.DoesNotExist:
    user = None

#check if user is_active
if user.is_active:
    user_active = true
else
    user_active = false

#check the password

if user_active:
    password_match = user.check_password(password):
else:
    password_match = false

if password_match:
    msg = "Login Successful"
else:
    msg = "Login Failed"

以上内容是否与身份验证功能相同,或者还有其他需要检查的内容。

【问题讨论】:

  • 如果这导致困难,您必须切换到更简单的任务。身份验证和授权是非常复杂和敏感的任务。你需要练习解决更简单的问题。此外它没有实用价值,因为 Django 身份验证实现很好,如果您不满意,还有很棒的 django-allauth 包。
  • 您尝试了解 Django 身份验证是一件好事,但不要因为您不了解它而自责。无论如何都要使用它,因为它已经实现得非常好。如果您真的想了解它,请在 SO 上发布该问题。

标签: django authentication


【解决方案1】:

authenticate 方法贯穿所有的身份验证后端,并将其称为authenticate 方法。

默认 Django 的身份验证后端是 ModelBackend。如果您检查它的 authenticate 方法,您会发现它已经包含了您所描述的所有步骤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2013-12-26
    • 2016-01-24
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多