Bird
Raised Fist0
Flaskframework~20 mins

Password reset email pattern in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Password Reset Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Flask route do when a password reset is requested?

Consider this Flask route for password reset requests. What is the main behavior when a user submits their email?

Flask
from flask import Flask, request, render_template_string
app = Flask(__name__)

@app.route('/reset-password', methods=['GET', 'POST'])
def reset_password():
    if request.method == 'POST':
        email = request.form.get('email')
        if email and '@' in email:
            # Simulate sending reset email
            return 'Reset email sent to ' + email
        else:
            return 'Invalid email', 400
    return render_template_string('<form method="post"><input name="email" type="email"/><button>Send</button></form>')
AIt sends a reset email if the email contains '@', otherwise returns a 400 error.
BIt always sends a reset email regardless of the email format.
CIt only accepts GET requests and ignores POST.
DIt returns a 404 error if the method is GET.
Attempts:
2 left
💡 Hint

Look at the condition that checks the email format and the HTTP method.

📝 Syntax
intermediate
2:00remaining
Which option correctly generates a secure token for password reset?

Which code snippet correctly generates a secure token for a password reset link in Flask?

Flask
import secrets

def generate_token():
    # Fill in the correct token generation
    pass
Areturn secrets.choice(['a','b','c','d'])
Breturn secrets.randbelow(1000000)
Creturn secrets.token_hex(4)
Dreturn secrets.token_urlsafe(32)
Attempts:
2 left
💡 Hint

Look for a method that returns a URL-safe string with enough randomness.

🔧 Debug
advanced
2:30remaining
Why does this password reset email sending code fail to send emails?

Review this Flask snippet for sending password reset emails. Why does it fail to send emails?

Flask
from flask_mail import Mail, Message

app.config.update(
    MAIL_SERVER='smtp.example.com',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME='user@example.com',
    MAIL_PASSWORD='password'
)
mail = Mail(app)

def send_reset_email(user_email, token):
    msg = Message('Reset Your Password', sender='noreply@example.com', recipients=[user_email])
    msg.body = f'Click to reset: http://example.com/reset/{token}'
    mail.send(msg)
AThe mail.send() method is missing app context, causing failure.
BMAIL_USE_TLS should be False for port 587.
CThe sender email must match MAIL_USERNAME exactly.
DThe Mail object is created before app is fully initialized, causing failure.
Attempts:
2 left
💡 Hint

Flask-Mail requires app context when sending emails outside request handlers.

❓ state_output
advanced
1:30remaining
What is the output of this Flask password reset token verification code?

Given this token verification function, what is the output when token='abc123' and stored_tokens={'abc123': 'user1'}?

Flask
stored_tokens = {'abc123': 'user1'}

def verify_token(token):
    user = stored_tokens.get(token)
    if user:
        return f'Token valid for {user}'
    else:
        return 'Invalid token'

result = verify_token('abc123')
ANone
B"Invalid token"
C"Token valid for user1"
DKeyError
Attempts:
2 left
💡 Hint

Check what stored_tokens.get(token) returns when token exists.

🧠 Conceptual
expert
2:00remaining
Which option best describes the security risk of using predictable tokens in password reset emails?

Why is it dangerous to use predictable tokens (like incremental numbers) in password reset links?

APredictable tokens improve performance but reduce email deliverability.
BAttackers can guess tokens and reset passwords of other users easily.
CThey cause the reset link to expire too quickly, annoying users.
DUsing predictable tokens requires more server memory to store.
Attempts:
2 left
💡 Hint

Think about what happens if someone can guess the token in a reset link.

Practice

(1/5)
1. What is the main purpose of using a token in a Flask password reset email pattern?
easy
A. To securely verify the user's identity before allowing password reset
B. To store the user's new password temporarily
C. To send the user's password in plain text via email
D. To log the user out of all sessions automatically

Solution

  1. 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.
  2. Step 2: Identify the purpose of the token

    The token ensures only the rightful user can reset the password by verifying their identity.
  3. Final Answer:

    To securely verify the user's identity before allowing password reset -> Option A
  4. Quick Check:

    Token = Secure identity verification [OK]
Hint: Tokens verify identity safely before password changes [OK]
Common Mistakes:
  • Thinking tokens store passwords
  • Assuming tokens send passwords in email
  • Believing tokens log users out
2. Which of the following is the correct way to create a timed token using Flask's itsdangerous library?
easy
A. token = URLSafeTimedSerializer.dumps(secret_key, email)
B. token = URLSafeTimedSerializer(secret_key).loads(email)
C. serializer = URLSafeTimedSerializer(); token = serializer.dumps(secret_key, email)
D. serializer = URLSafeTimedSerializer(secret_key); token = serializer.dumps(email)

Solution

  1. Step 1: Recall the correct usage of URLSafeTimedSerializer

    It requires initializing with a secret key, then calling dumps() with the data to encode.
  2. 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.
  3. Final Answer:

    serializer = URLSafeTimedSerializer(secret_key); token = serializer.dumps(email) -> Option D
  4. Quick Check:

    Serializer + dumps(data) = token [OK]
Hint: Initialize serializer with key, then dumps(data) for token [OK]
Common Mistakes:
  • Calling dumps as a static method
  • Passing secret key to dumps instead of constructor
  • Using loads instead of dumps to create token
3. Given this Flask code snippet, what will be printed if the token is valid and not expired?
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')
medium
A. None
B. user@example.com
C. secret
D. Invalid or expired token

Solution

  1. 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.
  2. Step 2: Analyze the try-except block

    If the token is valid and not expired, loads returns the original email, which is printed.
  3. Final Answer:

    user@example.com -> Option B
  4. Quick Check:

    Valid token returns original email [OK]
Hint: Valid loads returns original data, else error [OK]
Common Mistakes:
  • Assuming loads returns the secret key
  • Confusing dumps and loads output
  • Ignoring max_age expiration
4. Identify the error in this Flask password reset token verification code:
from itsdangerous import URLSafeTimedSerializer
serializer = URLSafeTimedSerializer('secret')
token = serializer.dumps('user@example.com')

email = serializer.loads(token, max_age=3600)
print(email)
medium
A. Missing try-except block to handle expired or invalid tokens
B. Incorrect secret key used in serializer
C. Using dumps instead of loads to decode token
D. max_age parameter is not supported in loads

Solution

  1. Step 1: Review the code for error handling

    The code calls loads without try-except, so expired or invalid tokens cause exceptions.
  2. Step 2: Identify the missing safety measure

    Proper pattern uses try-except to catch exceptions and handle errors gracefully.
  3. Final Answer:

    Missing try-except block to handle expired or invalid tokens -> Option A
  4. Quick Check:

    Always catch exceptions when verifying tokens [OK]
Hint: Always wrap loads in try-except to catch errors [OK]
Common Mistakes:
  • Not handling exceptions on token verification
  • Confusing dumps and loads usage
  • Assuming max_age is unsupported
5. You want to implement a password reset feature in Flask that sends a reset link with a token valid for 30 minutes. Which approach correctly combines token creation, expiration, and email sending?
hard
A. Store user password in token, send email with token, verify token by comparing passwords
B. Generate token with random string, send email with token, verify token by checking string length
C. 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)
D. Create token with dumps(user_email), send email without token, verify token with loads(token, max_age=3600)

Solution

  1. 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.
  2. 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.
  3. 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 C
  4. Quick Check:

    Serializer + dumps + max_age + email link = secure reset [OK]
Hint: Use serializer dumps and loads with max_age for timed tokens [OK]
Common Mistakes:
  • Not setting max_age for token expiration
  • Sending token without including it in email link
  • Storing passwords in tokens
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard