We use a password reset email pattern to help users safely change their forgotten passwords. It sends a special link to their email so only they can reset their password.
Password reset email pattern in Flask
from flask import Flask, request, url_for from itsdangerous import URLSafeTimedSerializer app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) def generate_reset_token(email): return serializer.dumps(email, salt='password-reset-salt') def verify_reset_token(token, expiration=3600): try: email = serializer.loads(token, salt='password-reset-salt', max_age=expiration) except Exception: return None return email
The URLSafeTimedSerializer creates a token that expires after some time.
Use the same salt value when generating and verifying tokens.
token = generate_reset_token('user@example.com') print(token)
email = verify_reset_token(token) if email: print(f'Token valid for {email}') else: print('Token invalid or expired')
This program creates a reset token for a user email, prints a reset link with the token, then simulates verifying the token when the user clicks the link.
from flask import Flask, request, url_for from itsdangerous import URLSafeTimedSerializer app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) def generate_reset_token(email): return serializer.dumps(email, salt='password-reset-salt') def verify_reset_token(token, expiration=3600): try: email = serializer.loads(token, salt='password-reset-salt', max_age=expiration) except Exception: return None return email # Simulate sending reset email user_email = 'user@example.com' token = generate_reset_token(user_email) print(f'Reset link: http://example.com/reset_password/{token}') # Simulate user clicking the link later received_token = token verified_email = verify_reset_token(received_token) if verified_email: print(f'Token valid for {verified_email}') else: print('Token invalid or expired')
Always keep your SECRET_KEY safe and secret.
Tokens should expire to prevent misuse.
Send the reset link via email securely and avoid showing tokens in URLs publicly.
The password reset email pattern helps users safely reset forgotten passwords.
It uses a token that expires to verify the user's identity.
Flask with itsdangerous makes creating and checking tokens easy.
Practice
Solution
Step 1: Understand the role of tokens in password reset
Tokens are unique codes sent to users to confirm their identity securely during password reset.Step 2: Identify the purpose of the token
The token ensures only the rightful user can reset the password by verifying their identity.Final Answer:
To securely verify the user's identity before allowing password reset -> Option AQuick Check:
Token = Secure identity verification [OK]
- Thinking tokens store passwords
- Assuming tokens send passwords in email
- Believing tokens log users out
Solution
Step 1: Recall the correct usage of URLSafeTimedSerializer
It requires initializing with a secret key, then calling dumps() with the data to encode.Step 2: Match the syntax to the correct option
serializer = URLSafeTimedSerializer(secret_key); token = serializer.dumps(email) correctly creates the serializer and calls dumps(email) to create the token.Final Answer:
serializer = URLSafeTimedSerializer(secret_key); token = serializer.dumps(email) -> Option DQuick Check:
Serializer + dumps(data) = token [OK]
- Calling dumps as a static method
- Passing secret key to dumps instead of constructor
- Using loads instead of dumps to create token
from itsdangerous import URLSafeTimedSerializer
serializer = URLSafeTimedSerializer('secret')
token = serializer.dumps('user@example.com')
try:
email = serializer.loads(token, max_age=3600)
print(email)
except Exception:
print('Invalid or expired token')Solution
Step 1: Understand what serializer.dumps and loads do
dumps creates a token from the email string; loads decodes it back if valid and within max_age.Step 2: Analyze the try-except block
If the token is valid and not expired, loads returns the original email, which is printed.Final Answer:
user@example.com -> Option BQuick Check:
Valid token returns original email [OK]
- Assuming loads returns the secret key
- Confusing dumps and loads output
- Ignoring max_age expiration
from itsdangerous import URLSafeTimedSerializer
serializer = URLSafeTimedSerializer('secret')
token = serializer.dumps('user@example.com')
email = serializer.loads(token, max_age=3600)
print(email)Solution
Step 1: Review the code for error handling
The code calls loads without try-except, so expired or invalid tokens cause exceptions.Step 2: Identify the missing safety measure
Proper pattern uses try-except to catch exceptions and handle errors gracefully.Final Answer:
Missing try-except block to handle expired or invalid tokens -> Option AQuick Check:
Always catch exceptions when verifying tokens [OK]
- Not handling exceptions on token verification
- Confusing dumps and loads usage
- Assuming max_age is unsupported
Solution
Step 1: Understand token creation and expiration
Use URLSafeTimedSerializer with secret key to create a token from user email; set max_age to 1800 seconds (30 minutes) when verifying.Step 2: Combine with email sending and verification
Send the token in the reset link via email; verify token on reset page using loads with max_age to ensure expiration.Final Answer:
Create a URLSafeTimedSerializer with secret key, generate token with dumps(user_email), send email with link containing token, verify token with loads(token, max_age=1800) -> Option CQuick Check:
Serializer + dumps + max_age + email link = secure reset [OK]
- Not setting max_age for token expiration
- Sending token without including it in email link
- Storing passwords in tokens
Ready to prove it?
Pass the test and this pattern moves unknown
