iMerica / dj-rest-auth

Authentication for Django Rest Framework
https://dj-rest-auth.readthedocs.io/en/latest/index.html
MIT License
1.67k stars 311 forks source link

problem - uid - key - password_reset_key_message.txt #427

Closed kurotom closed 2 years ago

kurotom commented 2 years ago

Hi, I'm creating a project (an api), but I'm stuck on the next part. When sending the password reset mail, specifically 'password_reset_key_message.txt', I can't capture the user's 'key' and 'uid', I want to change the address.

I downgraded to version 2.1.4, but I still have this problem.

django==4.0.7 dj-rest-auth==2.1.4

Please help.

StephenSorriaux commented 2 years ago

Just had the same problem, ended up using a custom serializer and form. Below code is when using allauth but you get the idea.

myapp/settings.py:

...
REST_AUTH_SERIALIZERS = {
    'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.CustomPasswordResetSerializer'
}
...

myapp/serializers.py:

from dj_rest_auth.serializers import PasswordResetSerializer
from myapp.forms import CustomResetForm

class CustomPasswordResetSerializer(PasswordResetSerializer):
    """
    Serializer for requesting a password reset e-mail.
    """
    @property
    def password_reset_form_class(self):
        return CustomResetForm

myapp/forms.py:

from dj_rest_auth.forms import AllAuthPasswordResetForm
from django.contrib.sites.shortcuts import get_current_site
from allauth.account.forms import default_token_generator
from allauth.account.adapter import get_adapter
from allauth.account.utils import user_pk_to_url_str

class CustomResetForm(AllAuthPasswordResetForm):

    def save(self, request, **kwargs):
        current_site = get_current_site(request)
        email = self.cleaned_data['email']
        token_generator = kwargs.get('token_generator', default_token_generator)

        for user in self.users:

            temp_key = token_generator.make_token(user)
            uid = user_pk_to_url_str(user)

            context = {
                'current_site': current_site,
                'user': user,
                'key': temp_key,
                'uid': uid,
            }
            get_adapter(request).send_mail(
                'account/email/password_reset_key', email, context
            )
        return self.cleaned_data['email']

I simplified the save() method here since I wanted to but see below link for for current "complete" implementation https://github.com/iMerica/dj-rest-auth/blob/bf168d9830ca2e6fde56f83f46fe48ab0adc8877/dj_rest_auth/forms.py#L17

You end up with key (which is the token in the reset/confirm view) and uid being accessible to your template.

Hope it helps.

kurotom commented 2 years ago

It helped me, thank you very much, now I can capture the token and the uid in the txt file.

Thank you very much!.