Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a secure unsubscribe link for emails sent with Flask

I want to generate an unsubscribe link that a user can click when receiving an email to unsubscribe that address. I don't want to just include the email in the link because a user could edit the link to unsubscribe someone else. Most emails I see generate some sort of token and the site knows how to match the token to the user. How can I generate such a token with Flask?

for email in email_lst:
      body = 'unsubscribe link with token'
      msg.attach(MIMEText(body, 'html'))
      more code to send email
like image 924
leaving_traces Avatar asked Jan 06 '23 16:01

leaving_traces


1 Answers

Flask includes the library itsdangerous which is used to generate tokens by securely signing serialized data.

For each email, generate a token with the email to be unsubscribed, and create an unsubscribe route that accepts and decodes that token to determine who to unsubscribe.

from itsdangerous import URLSafeSerializer, BadData

@app.route('/unsubscribe/<token>')
def unsubscribe(token):
    s = URLSafeSerializer(app.secret_key, salt='unsubscribe')

    try:
        email = s.loads(token)
    except BadData:
        # show an error
        ...

    # unsubscribe
    ...

def send_email():
    s = URLSafeSerializer(app.secret_key, salt='unsubscribe')
    token = s.dumps(user.email)
    url = url_for('unsubscribe', token=token)

    # add the url to your message
    ...

Since the token is signed, a user can see the data but can't change it without invalidating the token.

like image 153
davidism Avatar answered Jan 16 '23 20:01

davidism