Django如何通过电子邮件进行双因素身份验证?

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

Django, how to do two-factor authorization via email?

问题

我已重新定义了用户模型,并通过电子邮件进行了授权/注册。现在我想在用户输入用户名、密码和确认码发送到他的电子邮件时进行授权。我对工作方案很感兴趣。我这样看待它:vyushka使用随机生成代码,send_email将其发送出去,然后将这个代码写入数据库。在我看来,这是一个不好的决定(例如,将代码与用户一起存储在数据库中,因为仍然需要实现过期日期等等)。那么,有没有办法可以完成这个任务(生成代码,以及如何存储它以进行验证)?我知道有各种各样的具有双因素身份验证(2FA)的库,但这不是我的选择。

英文:

I have a website and I have already redefined the user model, made authorization/registration via email. Now I want to do authorization when a user enters a username, password and a confirmation code is sent to his email. I am interested in the scheme of work. I see it this way: vyushka generates code using random, send_email sends it and this very code is written to the database. In my opinion, this is a bad decision (For example, to store the code in the database with the user, because you still have to implement the expiration date, etc.).
So, are there any options for how this can be done. (generate code, where and how to store it for verification). I know about all sorts of libraries with 2FA, this is not my option.

答案1

得分: 1

你可以创建一个名为TwoFactorEmailModel的类,其中包括codeexpirationcreated_atuser字段。当用户输入电子邮件、密码和发送给他的验证码时,您需要按created_at字段对该用户的所有TwoFactorEmailModel对象进行排序,并获取第一个对象。如果它尚未过期并且用户输入的验证码与对象的验证码相等,则可以对用户进行身份验证。

Edit:

Вы можете создать метод модели (как описано выше), который будет генерировать код (я уверен, что для этого есть готовая библиотека) и вызываться при инициализации модели, то есть в методе init, а затем создать еще один метод, который будет отправлять электронное письмо пользователю. Например, методы могут выглядеть так:

class TwoFactorEmailModel(models.Model):
    code = models.CharField(max_length=32)
    created_at = models.DateTimeField(auto_now_add=True)
    expiration = models.DateTimeField(default=now() + timedelta(hours=2))
    user = models.ForeignKey(to='users.User', on_delete=models.CASCADE)
 
    def save(self):
        self.code = generate_code()
        return super().save()

    def generate_code(self):
        return 'your logic here'
    
    def send_two_factor_email(self, subject, body):
        'your logic...'
        send_mail(subject, body, [self.user.email])

    def can_be_sent(self, code):
        return self.expiration < now() and self.code == code

    def is_expired(self):
        return self.expiration < now()
英文:

You can create a TwoFactorEmailModel class with code, expiration, created_at and user fields, when the user enters email, password and the code sent to him, you have to sort all the TwoFactorEmailModel objects of this user by created_at field and get the first object, if it has not expired and the user entered code is equal to the object code, then you can authenticate the user.

Edit:

Вы можете создать метод модели(описаной выше), который будет генерироваь код(вообще я уверен что для этого есть готовая библиотека) и вызыватся при инициализации модели то есть в методе init, а затем создать ещё один метод, который будет отправлять электронное письмо пользователю. Например методы могут выглядеть так:

class TwoFactorEmailModel(models.Model):
    code = models.CharField(max_length=32)
    created_at = models.DateTimeField(auto_now_add=True)
    expiration = models.DateTimeField(default=now() + timedelta(hours=2)) 
    user = models.ForeignKey(to=&#39;users.User&#39;, on_delete=models.CASCADE)
 
    def save(self):
        self.code = generate_code()
        return super().save()

    def generate_code(self):
        return &#39;your logic here&#39;
    
    def send_two_factor_email(self, subject, body):
        &#39;your logic...&#39;
        send_mail(subject, body, [self.user.email])

    def can_be_sent(self, code):
        return self.expiration &lt; now() and self.code == code

    def is_expired(self):
        return self.expiration &lt; now()

答案2

得分: 1

这里我创建了一个小项目,用于双因素身份验证(电子邮件 + 一次性密码)...

Github存储库链接在这里

浏览器输出

Django如何通过电子邮件进行双因素身份验证?

英文:

Here I created a small project on it, (email + otp) for two-factor authentication...

Github repo link here

Browser output

Django如何通过电子邮件进行双因素身份验证?

huangapple
  • 本文由 发表于 2023年6月9日 03:55:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435297.html
匿名

发表评论

匿名网友

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

确定