Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 8, 2023 01:21
Show Gist options
  • Save code-boxx/a17692088b41171ed580a2fa79c30a90 to your computer and use it in GitHub Desktop.
Save code-boxx/a17692088b41171ed580a2fa79c30a90 to your computer and use it in GitHub Desktop.
Simple Python Admin Panel

SIMPLE PYTHON FLASK ADMIN PANEL

https://code-boxx.com/simple-admin-panel-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a static and templates folder.
    • Move css js files into the static folder.
    • Move html files into the templates folder
    • Download the image below as static/pic.png
    • Create a virtual environment - virtualenv venv.
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install required modules - pip install flask pyjwt bcrypt
    • Run python 4-server.py to start the server.
  2. Access http://localhost in your browser.

IMAGE

pic

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* (A) GLOBAL */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
display: flex;
min-height: 100vh;
padding: 0; margin: 0;
}
/* (B) SIDEBAR */
/* (B1) SIDEBAR ITSELF */
#pgside {
width: 230px;
transition: width 0.2s;
background: #283039;
}
/* (B2) USER OR BRANDING */
#pgside #pguser {
display: flex;
align-items: center;
padding: 10px;
background: #043368;
cursor: pointer;
}
#pgside #pguserimg {
border-radius: 50%;
width: 50px;
margin-right: 10px;
}
#pgside #pgusername {
color: #ff6a6a;
font-weight: 700;
text-transform: uppercase;
word-break: break-all;
}
#pgside #pguseracct { font-size: 13px; }
/* (B3) SIDEBAR ITEMS */
#pgside, #pgside a { color: #fff; }
#pgside a {
display: block;
padding: 20px;
width: 100%;
text-decoration: none;
cursor: pointer;
}
#pgside a.current { background: #7c1919; }
#pgside a:hover { background: #9b2323; }
/* (B4) SIDEBAR ICONS & TEXT */
#pgside .ico, #pgside .txt { font-style: normal; }
#pgside .ico {
font-size: 1.1em;
margin-right: 10px;
}
/* (B5) SMALL SCREEN TRANSFORMATION */
@media screen and (max-width:768px) {
#pgside { width: 70px; }
#pgside #pguser { justify-content: center; }
#pgside a {
text-align: center;
padding: 20px 0;
}
#pgside .ico {
font-size: 1.5em;
margin-right: 0;
}
#pgside .txt { display: none; }
#pgside #pguserimg { margin-right: 0; }
}
/* (C) MAIN CONTENTS */
#pgmain {
flex-grow: 1;
padding: 20px;
background: #f2f2f2;
}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.5">
<link rel="stylesheet" href="static/1-admin.css">
<script src="static/1-admin.js"></script>
{% block header %} {% endblock %}
</head>
<body>
<!-- (A) SIDEBAR -->
<div id="pgside">
<!-- (A1) BRANDING OR USER -->
<div id="pguser" onclick="if(confirm('Sign Off?')){logout();}">
<input type="hidden" name="logout" value="1">
<img src="static/pic.png" id="pguserimg">
<div class="txt">
<div id="pgusername">{{ user }}</div>
<div id="pguseracct">account | logoff</div>
</div>
</div>
<!-- (A2) MENU ITEMS -->
<a href="#" class="current">
<i class="ico">&#9733;</i>
<i class="txt">Section A</i>
</a>
<a href="#">
<i class="ico">&#9728;</i>
<i class="txt">Section B</i>
</a>
<a href="#">
<i class="ico">&#9737;</i>
<i class="txt">Section C</i>
</a>
</div>
<!-- (B) MAIN -->
<main id="pgmain">{% block content %} {% endblock %}</main>
</body>
</html>
function logout () {
fetch("/out", { method:"post" })
.then(res => res.text())
.then(txt => {
if (txt=="OK") { location.href = "../login"; }
else { alert(txt); }
})
.catch(err => {
console.error(err);
alert("Error - " + err.message);
});
return false;
}
{% extends "1-admin.html" %}
{% block content %}
<h1>It Works!</h1>
<p>You are in the protected admin page.</p>
{% endblock %}
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
background: #f2f2f2;
}
/* (B) LOGIN FORM */
form {
width: 400px;
padding: 20px;
margin: 0 auto;
border: 1px solid #ccc;
background: #fff;
}
form h1 {
font-size: 28px;
margin: 0 0 20px 0;
}
form label, form input {
display: block;
width: 100%;
}
form label {
color: #7e7e7e;
padding: 10px 0;
}
form input { padding: 10px; }
form input[type=submit] {
margin-top: 20px;
border: 0;
font-weight: 700;
color: #fff;
background: #c51111;
cursor: pointer;
}
/* (C) ERROR */
.error {
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ff7979;
background: #ffdada;
}
<!DOCTYPE html>
<html>
<head>
<title>Admin Login</title>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.5">
<link rel="stylesheet" href="static/3-login.css">
<script src="static/3-login.js"></script>
</head>
<body>
<form method="post" id="login" onsubmit="return login()">
<h1>ADMIN LOGIN</h1>
<label>Email</label>
<input type="email" name="email" required value="joy@doe.com">
<label>Password</label>
<input type="password" name="password" required value="12345">
<input type="submit" value="Login">
</form>
</body>
</html>
function login () {
// (A) GET EMAIL + PASSWORD
var data = new FormData(document.getElementById("login"));
// (B) AJAX REQUEST
fetch("/in", { method:"POST", body:data })
.then(res => res.text())
.then(txt => {
if (txt=="OK") { location.href = "../"; }
else { alert(txt); }
})
.catch(err => {
console.error(err);
alert("Error - " + err.message);
});
return false;
}
# (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
# (A3) SETTINGS
HOST_NAME = "localhost"
HOST_PORT = 80
JWT_KEY = "YOUR-SECRET-KEY"
JWT_ISS = "YOUR-NAME"
JWT_ALGO = "HS512"
# (B) USERS - AT LEAST HASH THE PASSWORD!
# password = "12345"
# print(bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()))
USERS = {
"joy@doe.com" : b'$2b$12$3kcEc8qxnrHGCBHM8Bh0V.gWEFpsxpsxbkCfmk4BDcjBkGsVLut8i'
}
# (C) JSON WEB TOKEN
# (C1) 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)
# (C2) VERIFY JWT
def jwtVerify(cookies):
try:
user = jwt.decode(cookies.get("JWT"), JWT_KEY, algorithms=[JWT_ALGO])
return user["data"]
except:
return False
# (D) ROUTES
# (D1) ADMIN PAGE
@app.route("/")
def index():
user = jwtVerify(request.cookies)
if user == False:
return redirect(url_for("login"))
else:
return render_template("2-home.html", title="Home Page", user=user["email"])
# (D2) LOGIN PAGE
@app.route("/login")
def login():
if jwtVerify(request.cookies):
return redirect(url_for("index"))
else:
return render_template("3-login.html")
# (D3) LOGIN ENDPOINT
@app.route("/in", methods=["POST"])
def lin():
data = dict(request.form)
valid = data["email"] in USERS
if valid:
valid = bcrypt.checkpw(data["password"].encode("utf-8"), USERS[data["email"]])
msg = "OK" if valid else "Invalid email/password"
res = make_response(msg, 200)
if valid:
res.set_cookie("JWT", jwtSign(data["email"]))
return res
# (D4) LOGOUT ENDPOINT
@app.route("/out", methods=["POST"])
def lout():
res = make_response("OK", 200)
res.delete_cookie("JWT")
return res
# (E) START!
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md static
md templates
move 1-admin.css static
move 1-admin.js static
move 3-login.css static
move 3-login.js static
move 1-admin.html templates
move 2-home.html templates
move 3-login.html templates
curl https://user-images.githubusercontent.com/11156244/281229681-7bd13b16-c07d-4909-a9d6-ef23e2ce1207.png --ssl-no-revoke --output static/pic.png
virtualenv venv
call venv\Scripts\activate
pip install flask pyjwt bcrypt
python 4-server.py
mkdir -m 777 static
mkdir -m 777 templates
mv ./1-admin.css ./static
mv ./1-admin.js ./static
mv ./3-login.css ./static
mv ./3-login.js ./static
mv ./1-admin.html ./templates
mv ./2-home.html ./templates
mv ./3-login.html ./templates
curl https://user-images.githubusercontent.com/11156244/281229681-7bd13b16-c07d-4909-a9d6-ef23e2ce1207.png --ssl-no-revoke --output static/pic.png
virtualenv venv
source "venv/bin/activate"
pip install flask pyjwt bcrypt
python 4-server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment