英文:
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的类,其中包括code、expiration、created_at和user字段。当用户输入电子邮件、密码和发送给他的验证码时,您需要按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='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()
答案2
得分: 1
这里我创建了一个小项目,用于双因素身份验证(电子邮件 + 一次性密码)...
Github存储库链接在这里
浏览器输出
英文:
Here I created a small project on it, (email + otp) for two-factor authentication...
Github repo link here
Browser output
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论