Computer scienceBackendFlaskUser-specified interactions

Authentication and Authorization in Flask

Theory

Login Flow using Flask-Login

Report a typo

In this example, we will create our login flow using Flask-Login.

Let us say we have a function that gives us a Flask-Login-compatible User object called get_user_compatible_with_flask_login.

Complete the following login endpoint using this user. Once you have logged in successfully, you will receive a login success message.

Write a program in Python 3
from flask_login import login_user
from flask import make_response, jsonify, request

success_message_template = "User with id {} logged in successfully"
failure_message_template = "User with id {} could not log in"

@app.route('/login', methods=["POST"])
def do_login():
# DO NOT CHANGE THE BELOW CODE
uid = request.get_json().get("user_id")
new_user = get_user_compatible_with_flask_login(uid) # GET a user for user id
if new_user:
# Enter your code here

# DO NOT CHANGE THE BELOW CODE
return make_response(jsonify(msg=success_message_template.format(uid)), 200) # login success
else:
return make_response(jsonify(msg=failure_message_template.format(uid)), 401) # login failure
___

Create a free account to access the full topic