Code
from flask import (
Flask,
g,
redirect,
render_template,
request,
session,
url_for
)
class User:
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
users = []
users.append(User(id=1, username='Usman', password='password'))
users.append(User(id=2, username='Becca', password='secret'))
users.append(User(id=3, username='Carlos', password='somethingsimple'))
app = Flask(__name__)
app.secret_key = 'somesecretkeythatonlyishouldknow'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = [x for x in users if x.username == username][0]
if user and user.password == password:
return "You Do it"
return redirect(url_for('login'))
return render_template('login.html')
if _name_ == '__main__':
app.run()
In this tutorial, you will:
Use the Flask-Login library for session management
Use the built-in Flask utility for hashing passwords
Add protected pages to the app for logged in users only
Use Flask-SQLAlchemy to create a User model
Create sign-up and login forms for the users to create accounts and log in
Flash error messages back to users when something goes wrong
Use information from the user’s account to display on the profile page
You will build a sign-up and a login page that allow users to log in and access protected pages. You will use information from the User model and display it on the protected pages when the user logs in to simulate what a profile would look like.
To complete this tutorial, you will need the following:
Some familiarity with Python.
Python installed on a local environment.
Knowledge of Basic Linux Navigation and File Management.
Here is a diagram to provide a sense of what the file structure of the project will look like once you have completed the tutorial:
Step 1 — Installing Packages
There are three main packages you need for your project:
Flask
Flask-Login: to handle the user sessions after authentication
Flask-SQLAlchemy: to represent the user model and interface with the database
You will be using SQLite to avoid having to install any extra dependencies for the database.
In this tutorial, you used Flask-Login and Flask-SQLAlchemy to build a login system for an app. You covered how to authenticate a user by first creating a user model and storing the user information. Then you had to verify the user’s password was correct by hashing the password from the form and comparing it to the one stored in the database. Finally, you added authorization to the app by using the @login_required decorator on a profile page so only logged-in users can see that page.
What you created in this tutorial will be sufficient for smaller apps, but if you wish to have more functionality from the beginning, you may want to consider using either the Flask-User or Flask-Security libraries, which are both built on top of the Flask-Login library