Consider this Flask route for password reset requests. What is the main behavior when a user submits their email?
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>')
Look at the condition that checks the email format and the HTTP method.
The route checks if the request method is POST and if the email contains '@'. If both are true, it simulates sending a reset email. Otherwise, it returns a 400 error for invalid email. For GET requests, it shows a simple form.
Which code snippet correctly generates a secure token for a password reset link in Flask?
import secrets def generate_token(): # Fill in the correct token generation pass
Look for a method that returns a URL-safe string with enough randomness.
secrets.token_urlsafe(32) generates a secure random URL-safe string of 32 bytes, ideal for tokens. randbelow returns an integer, token_hex(4) is shorter and less secure, choice picks a single character.
Review this Flask snippet for sending password reset emails. Why does it fail to send emails?
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)
Flask-Mail requires app context when sending emails outside request handlers.
mail.send() needs to run inside Flask's application context. Without it, sending fails silently or raises errors. Wrapping send_reset_email calls with app.app_context() fixes this.
Given this token verification function, what is the output when token='abc123' and stored_tokens={'abc123': 'user1'}?
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')Check what stored_tokens.get(token) returns when token exists.
stored_tokens.get('abc123') returns 'user1', so the function returns 'Token valid for user1'.
Why is it dangerous to use predictable tokens (like incremental numbers) in password reset links?
Think about what happens if someone can guess the token in a reset link.
Predictable tokens allow attackers to guess valid reset links and hijack accounts by resetting passwords without permission.