flask website with authentication

A Flask website with username, password authentication


A simple website with an index page for logging in and a home page.

Two html templates under the /templates folder

1. index.html

It contains inputs for username and password, a submit button and a dynamic 'message' field that can be set by flask script.

<html>

   <form method="POST">

  <input type="text" id="user" name="user" value='your username'><br>

  <input type="text" id="password" name="password" value='your password'><br>

  <button type="submit">Login</button>

   </form>

   <p>{{message}}<p>

</html>


2. home.html

After logged in, it shows a welcome message and a button for logging out.

<html>

   <p>{{message}}<p><br>

   <form method="POST">

  <button type="submit">Logout</button>

   </form>

</html>


3. the main Flask app.py script

To be able to keep the user's log in status, a session is required.

To keep the session secure, a super secret key is also needed to be set upfront.

If the user has logged in, the session simply keeps the username in it.

If session doesn't have the username in it, it is considered not logged in and direct back to the login page.

The session is maintained on the server side, so the client side can not manipulate it.


The login page (default to /), renders the index.html with a good day message for GET request.

Then the user can type in username, password and submit as a POST request.

If username password are good, it updates the session "session['username'] = username" to indicate that the user has logged in, and redirect to the home page.

Otherwise, it redirect back to the login page with a message 'Invalid username or password')


On the home page, it simply shows a welcome message with the username.

On clicking the logout button, a post request is submitted. The session will be cleared "session.pop('username', None)" and it goes back to login page.

If one go directly to the home page, it checks if the user has logged in "'username' in session". If not simply go back to login page.


from flask import Flask, render_template, request, redirect, url_for, session


app = Flask(__name__)


# for encryting the session / cookie. Change this to a more secure key in production.

app.secret_key = 'super-secret-key'  


# Sample user credentials (you would typically store these in a database)

users = {

    'user1': 'password1',

    'user2': 'password2'

}


# Home page with login form

@app.route('/', methods=['GET', 'POST'])

def login():

    if request.method == 'POST':

        print(request.form)

        username = request.form['user']

        password = request.form['password']

        if username in users and users[username] == password:

            session['username'] = username

            return redirect(url_for('home'))

        else:

            return render_template('index.html', message='Invalid username or password')

    else:

        return render_template('index.html', message='good day')


# home page accessible after login

@app.route('/home', methods=['GET', 'POST'])

def home():

    if 'username' in session: #check if the user has logged in

        if request.method == 'POST':

            #logout request

            session.pop('username', None)

            return redirect(url_for('login'))

        else:

            return render_template('home.html', message='hi {}, welcome to home page'.format(session['username']))

else:

#not logged in yet, redirect back to login page

        return redirect(url_for('login')) 

    

if __name__ == '__main__':

    app.run(debug=True)