Bird
Raised Fist0
Flaskframework~20 mins

Login form and verification in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Login Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a user submits the login form with correct credentials?

Consider a Flask login form that checks username and password against stored values. What is the typical behavior after a successful login?

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

users = {'alice': 'wonderland'}

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username in users and users[username] == password:
            return redirect(url_for('dashboard'))
        else:
            return 'Login Failed', 401
    return render_template_string('''<form method='post'>
        <input name='username'>
        <input name='password' type='password'>
        <input type='submit'>
    </form>''')

@app.route('/dashboard')
def dashboard():
    return 'Welcome!'

if __name__ == '__main__':
    app.run()
AThe user is redirected to the dashboard page with a welcome message.
BThe login form reloads with an error message about invalid credentials.
CThe server returns a 404 Not Found error.
DThe user sees the login form again without any message.
Attempts:
2 left
💡 Hint

Think about what redirect(url_for('dashboard')) does after a successful login.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Flask login route

Which option correctly fixes the syntax error in this Flask login route code?

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

users = {'alice': 'wonderland'}

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    if username in users and users[username] == password
        return 'Logged in'
    else:
        return 'Failed'

if __name__ == '__main__':
    app.run()
AChange 'request.form' to 'request.forms'.
BIndent the return statements one level less.
CAdd a colon ':' at the end of the if statement line.
DRemove the else block entirely.
Attempts:
2 left
💡 Hint

Python requires a colon at the end of control statements like if.

❓ state_output
advanced
2:00remaining
What is the output after submitting invalid credentials?

Given this Flask login snippet, what response does the server send when the password is wrong?

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

users = {'bob': 'builder'}

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    if username in users and users[username] == password:
        return 'Success'
    else:
        return 'Unauthorized', 401

if __name__ == '__main__':
    app.run()
AA redirect to the login page
B'Unauthorized' with HTTP status code 401
C'Success' with HTTP status code 200
DA server error 500
Attempts:
2 left
💡 Hint

Look at the else block's return statement and its status code.

🔧 Debug
advanced
2:00remaining
Why does this Flask login form always fail to authenticate?

Examine the code below. Why does the login always fail even with correct credentials?

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

users = {'eve': 'secret'}

@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    if username == users.get(username) and password == users.get(username):
        return 'Logged in'
    else:
        return 'Failed'

if __name__ == '__main__':
    app.run()
AThe route does not accept POST requests.
BThe form data keys are incorrect; should use 'user' and 'pass'.
CThe users dictionary is empty, so no match is possible.
DThe condition compares username to password instead of checking password correctness.
Attempts:
2 left
💡 Hint

Look carefully at the if condition comparing username and password.

🧠 Conceptual
expert
3:00remaining
What is the main security risk of this simple Flask login implementation?

Consider a Flask login system that stores passwords in plain text in a dictionary and checks them directly. What is the biggest security risk?

Flask
users = {'admin': '12345'}

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    if username in users and users[username] == password:
        return 'Welcome'
    else:
        return 'Denied', 401
APasswords are stored in plain text, risking exposure if the code or data leaks.
BThe login form uses POST instead of GET, which is insecure.
CThe code does not use HTTPS, causing syntax errors.
DThe username is not validated for length, causing runtime errors.
Attempts:
2 left
💡 Hint

Think about how passwords should be stored securely.

Practice

(1/5)
1. What is the main purpose of a login form in a Flask web application?
easy
A. To create database tables
B. To display images on the webpage
C. To collect username and password from users
D. To send emails automatically

Solution

  1. Step 1: Understand the role of a login form

    A login form is designed to collect user credentials like username and password.
  2. Step 2: Identify the correct purpose in Flask context

    In Flask, the login form collects these details to verify user identity before granting access.
  3. Final Answer:

    To collect username and password from users -> Option C
  4. Quick Check:

    Login form = collect credentials [OK]
Hint: Login forms always gather user credentials [OK]
Common Mistakes:
  • Confusing login form with other features like email or images
  • Thinking login form creates database tables
  • Assuming login form sends emails automatically
2. Which Flask code snippet correctly defines a route to display a login form using GET method?
easy
A. app.route('/login', methods=['GET'])\ndef login():\n return render_template('login.html')
B. app.route('/login', methods=['POST'])\ndef login():\n return render_template('login.html')
C. app.route('/login')\ndef login():\n return redirect('/home')
D. app.route('/login', methods=['DELETE'])\ndef login():\n return 'Delete method not allowed'

Solution

  1. Step 1: Identify the correct HTTP method for showing a form

    Login forms are usually shown with GET requests, so methods=['GET'] is correct.
  2. Step 2: Check the route and function return

    The route '/login' with methods=['GET'] returns the login.html template to display the form.
  3. Final Answer:

    app.route('/login', methods=['GET'])\ndef login():\n return render_template('login.html') -> Option A
  4. Quick Check:

    Show form = GET method [OK]
Hint: Use GET method to display forms in Flask routes [OK]
Common Mistakes:
  • Using POST method to show the form instead of GET
  • Not specifying methods list defaults to GET but unclear
  • Using DELETE method which is invalid for forms
3. Given this Flask login verification code snippet, what will be the output if username='admin' and password='1234' are submitted?
from flask import Flask, request, render_template_string
app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    user = request.form.get('username')
    pwd = request.form.get('password')
    if user == 'admin' and pwd == '1234':
        return 'Login successful'
    else:
        return 'Login failed'
medium
A. Login successful
B. Login failed
C. SyntaxError
D. No output

Solution

  1. Step 1: Check the submitted username and password

    The code compares user to 'admin' and pwd to '1234'. Both match the submitted values.
  2. Step 2: Determine the returned response

    Since both match, the function returns 'Login successful'.
  3. Final Answer:

    Login successful -> Option A
  4. Quick Check:

    Correct credentials = Login successful [OK]
Hint: Match input values exactly to get success message [OK]
Common Mistakes:
  • Confusing POST and GET methods for form data
  • Assuming wrong output when credentials match
  • Ignoring case sensitivity in username/password
4. Identify the error in this Flask login route code:
@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    if username = 'user' and password = 'pass':
        return 'Welcome!'
    else:
        return 'Invalid credentials'
medium
A. No return statement in the function
B. Missing 'methods' argument in @app.route decorator
C. Incorrect use of request.args instead of request.form
D. Using '=' instead of '==' in the if condition

Solution

  1. Step 1: Check the if condition syntax

    The code uses single '=' which is assignment, not comparison. It should be '==' to compare values.
  2. Step 2: Verify other parts of the code

    The methods argument is present, request.form is correctly used, and return statements exist.
  3. Final Answer:

    Using '=' instead of '==' in the if condition -> Option D
  4. Quick Check:

    Comparison needs '==' not '=' [OK]
Hint: Use '==' for comparisons, '=' is assignment [OK]
Common Mistakes:
  • Using '=' instead of '==' in conditions
  • Forgetting to specify POST method in route
  • Using request.args for POST form data
5. You want to create a Flask login system that locks out a user after 3 failed attempts. Which approach correctly combines login verification and attempt tracking?
hard
A. Use a global variable to count attempts and reset on successful login
B. Store attempt count in session and check before verifying credentials
C. Check attempts only after successful login to reset count
D. Ignore attempt count and always allow login attempts

Solution

  1. Step 1: Understand where to store attempt count

    Using session storage per user is best to track attempts individually without global conflicts.
  2. Step 2: Implement logic to check attempts before verifying credentials

    Check if attempts exceed 3 before allowing login verification to prevent further tries.
  3. Step 3: Reset attempt count on successful login

    Resetting attempts after success avoids locking out valid users.
  4. Final Answer:

    Store attempt count in session and check before verifying credentials -> Option B
  5. Quick Check:

    Session tracks attempts per user [OK]
Hint: Use session to track attempts and block after limit [OK]
Common Mistakes:
  • Using global variables causing shared count for all users
  • Resetting attempts only after success but not checking before login
  • Ignoring attempt limits and allowing unlimited tries
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