1
votes

I have Django website which users can register and login with their phone number. Recently I decide to add a recover password with phone number part to my site,I read Authentication Views in Django which users can reset their password by sending them an email but first of all it use email to reset password and second it use django built-in views, but I want a function in my view which generate a unique one time reset password link then I send this link to them with my sms api so they can reset their password using this link. So how can I generate reset password link in a secure way? the only idea that I've got is to implement a model which store a random string with OnetoOne relation and use it as a reset password link.

1

1 Answers

0
votes

Yeah your solution is good idea, I think Better implementation of your idea is:

Add following in your settings:

JWT_SECRET = SECRET_KEY  # use settings secret key for JWT secret
JWT_ALGORITHM = 'HS256'
JWT_EXP_DELTA_SECONDS = 86400  # token expiring time in seconds let's assign one day

and here are the functions to encode and decode the reset token:

from your_django_project import settings
from datetime import datetime, timedelta
import jwt

def encoded_reset_token(user_id):
    payload = {
        'user_id': user_id,
        'exp': datetime.utcnow() + timedelta(seconds=settings.JWT_EXP_DELTA_SECONDS)
    }
    encoded_data = jwt.encode(payload, settings.JWT_SECRET, settings.JWT_ALGORITHM)
    return  encoded_data.decode('utf-8')

def decode_reset_token(reset_token):
    try:
        decoded_data = jwt.decode(reset_token, settings.JWT_SECRET,
                                  algorithms=[settings.JWT_ALGORITHM])
    except (jwt.DecodeError, jwt.ExpiredSignatureError):
        return None  # means expired token

    return decoded_data['user_id']

so there is no need to use extra table to store your reset tokens