Created
July 14, 2020 08:36
-
-
Save tomcounsell/78d0a587b6107369792f1e05471e50cc to your computer and use it in GitHub Desktop.
Django User model one time pin code OTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
from django.db import models | |
from django.contrib.auth.models import AbstractUser | |
class User(AbstractUser): | |
created_at = models.DateTimeField(auto_now_add=True) | |
def get_otp(self, num_digits=4): | |
""" | |
generate random pin code | |
this will return the same value until the next time the user logs in | |
therefore, it can be called in view logic to both create and validate the code before login | |
""" | |
hash_object = hashlib.md5(bytes(f"{self.username}{self.created_at}{self.last_login}", encoding='utf-8')) | |
return str(int(hash_object.hexdigest(), 16))[-num_digits:] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment