Simple User Login In Python Flask (No Database)

Welcome to a tutorial on how to create a simple user login system in Python Flask, without a database. Yes, for you guys who just want a “rather quick and easy” login system without having to deal with a database (nor the default flask login), here is how it can be done – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Python Login Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create your own project folder, e.g. D:\login, unzip the code inside this folder.
  • Open the terminal (or command line), navigate to your project folder cd D:\login.
  • As usual, create a virtual environment if you don’t want to mess up your other projects.
    • virtualenv venv
    • Windows – venv\scripts\activate
    • Mac/Linux – venv/bin/activate
  • Get all the packages – pip install Flask pyjwt bcrypt
  • Launch! python 4-server.py and access http://localhost/login.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PYTHON FLASK LOGIN SYSTEM

All right, let us now into the user login system. Not going to explain line-by-line, but here’s a quick walkthrough.

 

STEP 1) DUMMY HOME PAGE

templates/1-home.html
<h1>Hello World!</h1>
<p>This page can be accessed by anyone.</p>

First, we start with the home page itself. This can be accessed at http://localhost by everyone.

 

STEP 2) DUMMY ADMIN PAGE

templates/2-admin.html
<h1>It Works!</h1>
<p>This page can only be accessed by admin.</p>

Next, we have a “protected admin page” at http://localhost/admin. This can only be accessed by users who are signed in.

 

STEP 3) LOGIN PAGE

THE HTML

templates/3-login.html
<form id="login" onsubmit="return login()">
  <h1>LOGIN</h1>
  <input type="email" placeholder="Email" name="email" required value="jon@doe.com"/>
  <input type="password" placeholder="Password" name="password" required value="12345"/>
  <input type="submit" value="Sign In"/>
</form>

The login page will be deployed at http://localhost/login. This should not be much of a mystery, just the regular login form with email and password fields.

 

 

THE JAVASCRIPT

static/3-login.js
function login () {
  // (A) GET EMAIL + PASSWORD
  var data = new FormData(document.getElementById("login"));
 
  // (B) AJAX REQUEST
  fetch("/lin", { method:"POST", body:data })
  .then((res) => { return res.text(); })
  .then((txt) => {
  if (txt=="OK") { location.href = "../admin"; }
    else { alert(txt); }
  })
  .catch((err) => {
    alert("Server error - " + err.message);
    console.error(err);
  });
  return false;
}

We will be making a fetch POST call to the server for user authentication, thus this bit of Javascript code.

 

STEP 4) PYTHON FLASK SERVER

INITIALIZE

4-server.py
# (A) INIT
# (A1) LOAD REQUIRED PACKAGES
from flask import Flask, render_template, make_response, request, redirect, url_for
from werkzeug.datastructures import ImmutableMultiDict
import bcrypt, jwt, time, random
 
# (A2) FLASK INIT
app = Flask(__name__)
# app.debug = True
 
# (B) SETTINGS
HOST_NAME = "localhost"
HOST_PORT = 80
JWT_KEY = "YOUR-SECRET-KEY"
JWT_ISS = "YOUR-NAME"
JWT_ALGO = "HS512"

The first few parts of the server-side script should be self-explanatory. We are just loading the required packages and doing some settings. Yes, a gentle reminder to change those settings to your own.

  • HOST_NAME and HOST_PORT where you want to deploy this project.
  • JWT_KEY Generate your own random secret key for the JSON Web Token, and NEVER expose it.
  • JWT_ISS The issuer, usually your company or domain name.

 

 

THE USERS

4-server.py
# (C) USERS - AT LEAST HASH THE PASSWORD!
# password = "12345"
# print(bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()))
USERS = {
  "jon@doe.com" : b'$2b$12$3kcEc8qxnrHGCBHM8Bh0V.gWEFpsxpsxbkCfmk4BDcjBkGsVLut8i'
}

Yes, we don’t have a database. So, the only way is to keep the users is a dictionary… At least have the decency to hash/encrypt the passwords.

 

JSON WEB TOKEN

4-server.py
# (D) JSON WEB TOKEN
# (D1) GENERATE JWT
def jwtSign(email):
  # https://stackoverflow.com/questions/2511222/efficiently-generate-a-16-character-alphanumeric-string
  rnd = "".join(random.choice("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^_-") for i in range(24))
  now = int(time.time())
  return jwt.encode({
    "iat" : now, # ISSUED AT - TIME WHEN TOKEN IS GENERATED
    "nbf" : now, # NOT BEFORE - WHEN THIS TOKEN IS CONSIDERED VALID
    "exp" : now + 3600, # EXPIRY - 1 HR (3600 SECS) FROM NOW IN THIS EXAMPLE
    "jti" : rnd, # RANDOM JSON TOKEN ID
    "iss" : JWT_ISS, # ISSUER
    # WHATEVER ELSE YOU WANT TO PUT
    "data" : { "email" : email }
  }, JWT_KEY, algorithm=JWT_ALGO)
 
# (D2) VERIFY JWT
def jwtVerify(cookies):
  try:
    token = cookies.get("JWT")
    decoded = jwt.decode(token, JWT_KEY, algorithms=[JWT_ALGO])
    # DO WHATEVER YOU WANT WITH THE DECODED TOKEN
    # print(decoded)
    return True
  except:
    return False

To keep the long story short for those who are not familiar with JSON Web Token (JWT):

  • (D1) On valid user login, jwtSign() will generate an encrypted JWT cookie.
  • (D2) On the protected pages, we use jwtVerify() to decode the JWT cookie. Allow access only if it is a valid token.

 

 

ROUTES – HTML PAGES

4-server.py
# (E) ROUTES
# (E1) HOME PAGE
@app.route("/")
def index():
  return render_template("1-home.html")
 
# (E2) ADMIN PAGE
@app.route("/admin")
def admin():
  if jwtVerify(request.cookies):
    return render_template("2-admin.html")
  else:
    return redirect(url_for("login"))
 
# (E3) LOGIN PAGE
@app.route("/login")
def login():
  if jwtVerify(request.cookies):
    return redirect(url_for("admin"))
  else:
    return render_template("3-login.html")

As previously mentioned, we will deploy:

  • (E1) The home page, 1-home.html to /.
  • (E2) The admin page, 2-admin.html to /admin. Only verified users with a valid JWT token can access this page, unverified users will be redirected to the login page.
  • (E3) The login page, 3-login.html to /login. Verified users will be redirected to the admin page.

 

LOGIN & LOGOUT

4-server.py
# (E4) LOGIN ENDPOINT
@app.route("/lin", methods=["POST"])
def lin():
  data = dict(request.form)
  valid = data["email"] in USERS
  if valid:
    valid = bcrypt.checkpw(data["password"].encode("utf-8"), USERS["jon@doe.com"])
  msg = "OK" if valid else "Invalid email/password"
  res = make_response(msg, 200)
  if valid:
    res.set_cookie("JWT", jwtSign(data["email"]))
  return res

# (E5) LOGOUT ENDPOINT
@app.route("/lout", methods=["POST"])
def lout():
  res = make_response("OK", 200)
  res.delete_cookie("JWT")
  return res

Remember the login Javascript from earlier? This is the endpoint that will process the login. Very simply, verify the email/password against USERS and generate a JWT cookie token.

To logout, we simply unset the JWT cookie. I know, the “expert code ninjas” are going to say “this is stupid, just unset it on the client-side”. Sure thing. But I will recommend setting the httpOnly flag on the cookie too. So this endpoint is still useful.

 

 

GO!

4-server.py
# (F) START!
if __name__ == "__main__":
  app.run(HOST_NAME, HOST_PORT)

No explanation is required.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

WHAT’S NEXT?

This is pretty much a working example out of the box. Just add your own routes and create your own HTML templates – Do a quick if jwtVerify(request.cookies) check on all the protected pages. The end.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.