Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 9, 2023 04:44
Show Gist options
  • Save code-boxx/715234546d472bcfb1f01a6b34f739a0 to your computer and use it in GitHub Desktop.
Save code-boxx/715234546d472bcfb1f01a6b34f739a0 to your computer and use it in GitHub Desktop.
NodeJS Express Admin Panel

NODEJS EXPRESS ADMIN PANEL

https://code-boxx.com/admin-panel-nodejs/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create 2 folders - assets, views.
    • Move all css js into assets.
    • Move all ejs into views.
    • Save the image below as assets/pic.png.
    • Install required modules - npm i bcryptjs express ejs body-parser cookie-parser multer jsonwebtoken
    • Start the Express server - node 3-server.js.
  2. Access http://localhost in your browser.

IMAGES

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;
}
<%- include("1-top.ejs"); %>
<h1>IT WORKS!</h1>
<p>You are in the admin panel.</p>
<%- include("1-bottom.ejs"); %>
function logout () {
fetch("/out", { method:"POST" })
.then(res => res.text())
.then(txt => {
if (txt=="OK") { location.href = "/"; }
else { alert(txt); }
})
.catch(err => console.error(err));
}
</main>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>TEST</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="assets/1-admin.css">
<script src="assets/1-admin.js"></script>
</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="assets/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">
/* (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="assets/2-login.css">
<script src="assets/2-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));
return false;
}
// (A) INITIALIZE
// (A1) LOAD REQUIRED MODULES
// npm i bcryptjs express ejs body-parser cookie-parser multer jsonwebtoken
const bcrypt = require("bcryptjs"),
path = require("path"),
express = require("express"),
bodyParser = require("body-parser"),
cookieParser = require("cookie-parser"),
multer = require("multer"),
jwt = require("jsonwebtoken");
// (A2) INIT EXPRESS SERVER
const app = express();
app.set("view engine", "ejs");
app.use(multer().array());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// (B) USER ACCOUNTS - AT LEAST ENCRYPT YOUR PASSWORDS!
// bcrypt.hash("PASSWORD", 8, (err, hash) => { console.log(hash); });
const users = {
"joy@doe.com" : "$2a$08$g0ZKZhiA97.pyda3bsdQx.cES.TLQxxKmbvnFShkhpFeLJTc6DuA6"
};
// (C) JSON WEB TOKEN
// (C1) SETTINGS - CHANGE TO YOUR OWN!
const jwtKey = "YOUR-SECRET-KEY",
jwtIss = "YOUR-NAME",
jwtAud = "site.com",
jwtAlgo = "HS512";
// (C2) GENERATE JWT TOKEN
jwtSign = email => {
// (C2-1) RANDOM TOKEN ID
let char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&_-", rnd = "";
for (let i=0; i<16; i++) {
rnd += char.charAt(Math.floor(Math.random() * char.length));
}
// (C2-2) UNIX TIMESTAMP NOW
let now = Math.floor(Date.now() / 1000);
// (C2-3) SIGN TOKEN
return jwt.sign({
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 token id
iss : jwtIss, // issuer
aud : jwtAud, // audience
data : { email : email } // whatever else you want to put
}, jwtKey, { algorithm: jwtAlgo });
};
// (C3) VERIFY TOKEN
jwtVerify = (cookies) => {
if (cookies.JWT===undefined) { return false; }
try {
let decoded = jwt.verify(cookies.JWT, jwtKey);
// DO WHATEVER EXTRA CHECKS YOU WANT WITH DECODED TOKEN
// console.log(decoded);
return decoded["data"];
} catch (err) { return false; }
};
// (D) EXPRESS HTTP
// (D1) STATIC ASSETS
app.use("/assets", express.static(path.join(__dirname, "assets")))
// (D2) DUMMY ADMIN HOME PAGE - REGISTERED USERS ONLY
app.get("/", (req, res) => {
let user = jwtVerify(req.cookies);
if (user === false) {
res.redirect("../login");
} else {
res.render("1-admin.ejs", { user : user["email"] });
}
});
// (D3) LOGIN PAGE
app.get("/login", (req, res) => {
if (jwtVerify(req.cookies) === false) {
res.render("2-login.ejs");
} else {
res.redirect("../");
}
});
// (D4) LOGIN ENDPOINT
app.post("/in", async (req, res) => {
let pass = users[req.body.email] !== undefined;
if (pass) {
pass = await bcrypt.compare(req.body.password, users[req.body.email]);
}
if (pass) {
res.cookie("JWT", jwtSign(req.body.email));
res.status(200);
res.send("OK");
} else {
res.status(200);
res.send("Invalid user/password");
}
});
// (D5) LOGOUT ENDPOINT
app.post("/out", (req, res) => {
res.clearCookie("JWT");
res.status(200);
res.send("OK");
});
// (E) START EXPRESS SERVER
app.listen(80, () => console.log(`Server running at port 80`));
md assets
md views
move 1-admin.css assets
move 1-admin.js assets
move 2-login.css assets
move 2-login.js assets
move 1-admin.ejs views
move 1-bottom.ejs views
move 1-top.ejs views
move 2-login.ejs views
curl https://user-images.githubusercontent.com/11156244/281618268-e53412ae-4c1d-4b45-9225-e6a7930710ea.png --ssl-no-revoke --output assets/pic.png
call npm i bcryptjs express ejs body-parser cookie-parser multer jsonwebtoken
node 3-server.js
mkdir -m 777 assets
mkdir -m 777 views
mv ./1-admin.css ./assets
mv ./1-admin.js ./assets
mv ./2-login.css ./assets
mv ./2-login.js ./assets
mv ./1-admin.ejs ./views
mv ./1-bottom.ejs ./views
mv ./1-top.ejs ./views
mv ./2-login.ejs ./views
curl https://user-images.githubusercontent.com/11156244/281618268-e53412ae-4c1d-4b45-9225-e6a7930710ea.png --ssl-no-revoke --output ./assets/pic.png
source "npm i bcryptjs express ejs body-parser cookie-parser multer jsonwebtoken"
node 3-server.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment