Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing user email address

I would like to allow a user to change his email address. A user would change his email address, then a confirmation email with a link would be sent to that address, after the user clicked the link it would change his email address in the database.

I know there django-generic-confirmation deals with confirmations like this, but I would like to try and do it on my own.

To change an email, my code would be:

User.objects.get(username=username).update(email=request.POST['email'])

And to send an email to that address, I would have:

if 'Change Email' in request.POST.values():
    from django.core.mail import send_mail
    send_mail(
          'Confirm email change',
          'Click this **link** to confirm your change of email',
          '[email protected]',
          [request.POST['email']]
     )

How would I delay the change of email in the db until only after the user has confirmed his email? And how would i create a link that activates the email for this process? Thank you.

like image 481
David542 Avatar asked Jun 07 '11 00:06

David542


1 Answers

This is pretty simple. What you want to do is write an app with at least a model that looks like this;

class EmailChangeAuth(models.Model):
    auth_key = models.CharField(max_length=42)
    user = models.ForeignKey(User)
    new_email = models.CharField(max_length=256)

Fill in the auth_key with a UUID4 and you can treat it like you would a slug field in your urlconf.

Then write a view that takes the auth_key, searches for that in the database, and changes the user's email to new_email. Delete the record when you're done.

For bonus points, add in an expiration on it, and occasionally clean out any records older than a day.

You might also want to think about a security question type system instead. As the main reason a lot of people might want to change their email is that the old one no longer exists. For example leaving a company, a mail host disappearing (thats way less common now) etc, etc, etc.

like image 140
Hutch Avatar answered Sep 30 '22 07:09

Hutch