Search code examples
djangoemailkeyactivation

Django how to generate an automatic activation key for email activation link


I would like to know how can I generate an automatic activation key to be concatinated to my email activation link That's the sent link : http://localhost:8001/sign_up/60/subsribe/14/confirmEmail But for more security I want to send something like : http://localhost:8001/sign_up/60/subsribe/14/confirmEmail/{{ activation_key }}

mail = EmailMultiAlternatives("Confirmation d\'email pour finaliser votre inscripttion","pour finaliser votre inscription, veuillez consulter le lien ci-dessus ",from_email, to=[email])

mail.attach_alternative('http://localhost:8001/sign_up/' + str(id_account) + '/subscribe/' + str(id_sub) + '/confirmEmail',"text/html")

mail.send()

Solution

  • You can use the Signer class to achieve this. i.e.

    from django.core.signing import Signer
    signer = Signer()
    signed_value = signer.sign(profile.user.email)#gives '[email protected]:signed_things', extract signed_things'
    key = ''.join(signed_value.split(':')[1:])
    #send out key as part of url
    

    You can then store the key with the user profile for instance. When the link is requested, you can do something like the following:

    profile = get_object_or_404(UserProfile, key=key)
    signer = Signer()
    if signer.unsign('{0}:{1}'.format(profile.user.email, key)) == profile.user.email:
        profile.verified = True