Django密码过期

huangapple go评论65阅读模式
英文:

Django Password Expiry

问题

如果 HR 添加一个具有名字、姓氏、电子邮件、用户名和密码的用户。
设置密码后,密码只能在 5 分钟内访问,在此时间段结束后,密码将无法用于登录目的。

有人知道如何在 Django 中解决这个问题吗?

这是我的代码

models.py

class RegisterUser(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    mobile = models.CharField(max_length=100)
    password_expiry = models.DateTimeField(null=True, blank=True)

settings.py

PASSWORD_RESET_TIMEOUT_MINUTES = 5

views.py

from Password_Expiry.settings import PASSWORD_RESET_TIMEOUT_MINUTES

def register(request):
    if request.method == 'POST':
        fname = request.POST['fname']
        lname = request.POST['lname']
        mobile = request.POST['mobile']
        email = request.POST['email']
        uname = request.POST['uname']
        pwd = request.POST['pwd']
        user = User.objects.create(first_name=fname, last_name=lname, email=email, username=uname)
        user.set_password(pwd)
        user.save()
        reg_user = RegisterUser(user=user, mobile=mobile)
        reg_user.password_expiry = datetime.datetime.now() + timedelta(minutes=PASSWORD_RESET_TIMEOUT_MINUTES)
        reg_user.save()
        return redirect('/')
        return render(request, 'register.html')

def login(request):
    if request.method == 'POST':
        uname = request.POST['uname']
        pwd = request.POST['pwd']
        
        user = authenticate(username=uname, password=pwd)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return redirect('home')
            else:
                messages.error(request, 'this account is disabled. please contact admin.')
                return redirect('login')
        else:
            messages.error(request, 'invalid username or password')
            return redirect('login')
    else:
        return render(request, 'login.html',{'message':messages})
英文:

If HR add a user with first_name, last_name, email, username, and password.
after setting the password the password must only access for 5 minutes, after the time period the password is not usable for login purpose.

Does anyone know how to solve this problem in django

here is my code

models.py

class RegisterUser(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    mobile = models.CharField(max_length=100)
    password_expiry = models.DateTimeField(null=True, blank=True)

settings.py

PASSWORD_RESET_TIMEOUT_MINUTES = 5

views.py

from Password_Expiry.settings import PASSWORD_RESET_TIMEOUT_MINUTES

def register(request):
    if request.method == 'POST':
        fname = request.POST['fname']
        lname = request.POST['lname']
        mobile = request.POST['mobile']
        email = request.POST['email']
        uname = request.POST['uname']
        pwd = request.POST['pwd']
        user = User.objects.create(first_name=fname, last_name=lname, email=email, username=uname)
        user.set_password(pwd)
        user.save()
        reg_user = RegisterUser(user=user, mobile=mobile)
        reg_user.password_expiry = datetime.datetime.now() + timedelta(minutes=PASSWORD_RESET_TIMEOUT_MINUTES)
        reg_user.save()
        return redirect('/')
        return render(request, 'register.html')

def login(request):
    if request.method == 'POST':
        uname = request.POST['uname']
        pwd = request.POST['pwd']
        
        user = authenticate(username=uname, password=pwd)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return redirect('home')
            else:
                messages.error(request, 'this account is disabled. please contact admin.')
                return redirect('login')
        else:
            messages.error(request, 'invalid username or password')
            return redirect('login')
    else:
        return render(request, 'login.html',{'message':messages})

答案1

得分: 0

在你的登录视图函数中,可以验证当前时间是否小于模型中的 password_expiry 属性。如果小于 5 分钟,则登录用户,否则可以使用 PasswordResetView 和 Django 的邮件后端发送密码重置电子邮件给用户。有关更多详情,请参阅文档:
https://docs.djangoproject.com/en/4.2/topics/auth/default/

用户重置密码后,记得更新/延长模型中的 password_expiry 属性,以确保他们可以登录。

RegisterUser 模型只用于存储用户的手机号码和密码过期时间吗?如果是这样,为什么不直接扩展 User 模型以包含所需的字段?另外,在你的 register 函数中有两个返回语句,意味着第二个从未被调用。

我还建议在 forms.py 中创建适当的登录/注册表单,并在你的视图函数中使用它们。然后,你可以调用 .is_valid() 方法来验证来自表单的数据。

由于注册表单与你的 User 模型密切相关,你可以使用 Django 的 ModelForm,然后使用 .save() 来创建并保存数据库对象,而不是在视图函数中手动创建对象。
https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/

// forms.py
class SignUpForm(ModelForm):
   class Meta:
      model = User
      
// views.py
def register(request):
   if request.method == 'POST':
      form = SignUpForm(request.POST)
      ...
    
      if form.is_valid():
         # data valid
         ...
         form.save() # User is saved to database
英文:

In your login view function, you could validate that the current time is less than the password_expiry property in your model. If it has been less than 5 minutes, log the user in, otherwise you could make use of PasswordResetView and Django’s mailing backend to send password reset email to the user. See the docs for more details:
https://docs.djangoproject.com/en/4.2/topics/auth/default/

Once user resets the password, you need to remember to update/extend password_expiry property in the model, so they are not prevented from logging in.

Is RegisterUser model only used to store the user’s mobile number and password expiry time? If so, why not just extend the User model with the desired fields? Also, you have two return statements in your register function, meaning the second one is never called.

I would also suggest creating appropriate Login/Register forms in forms.py, and using them in your view functions. You would then be able to call the .is_valid() method to validate data from the form.

Since the registration form maps closely to your User model, you could use django’s ModelForm, and then use .save() to create and save the database object, as opposed to creating the object manually in your view function.
https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/

// forms.py
class SignUpForm(ModelForm):
   class Meta:
      model = User
	…


// views.py
def register(request):
   if request.method == ‘POST’:
      form = SignUpForm(request.POST)
      ...
    
      if form.is_valid():
         # data valid
         ...
         form.save() # User is saved to database

huangapple
  • 本文由 发表于 2023年4月13日 16:06:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定