Website/index.js

65 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-06-16 20:59:21 +02:00
import express from "express";
2024-06-24 23:54:38 +02:00
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import {getUser, loginUser} from "./login.js";
2024-06-16 20:59:21 +02:00
const server = express();
2024-06-18 08:09:55 +02:00
server.set('view engine', 'ejs')
server.use(express.static("static"))
2024-06-24 23:54:38 +02:00
server.use(cookieParser())
server.use(bodyParser.urlencoded({ extended: true }))
2024-06-18 08:09:55 +02:00
server.use(handle)
2024-06-16 20:59:21 +02:00
2024-06-25 01:24:57 +02:00
const sbstart = '<div style="position: fixed; top: 0; left: 0; padding: 5px; width: calc(100vw - 10px); display: block; background-color: #402060; text-align: center;">'
const sbbasic = '<a class=btn href="/"> Home </a><a class=btn href="/dashboard"> Dashboard </a>'
const sblogout = '<a class=btn href="/logout"> Log&nbsp;out </a>'
2024-06-24 23:54:38 +02:00
const sbend = "</div>"
2024-06-25 01:24:57 +02:00
const indexSidebar = sbstart + sbbasic + sbend
2024-06-18 08:09:55 +02:00
2024-06-24 23:54:38 +02:00
async function handle_other(req, res) {
if(req.method === "POST" && req.path === "/login" && req.body.username && req.body.password) {
let user = await loginUser(req.body.username, req.body.password)
if(user) {
res.cookie("token", user.token).redirect("/dashboard")
}
else {
res.status(403).render("login", {sidebar: indexSidebar, error: "Wrong username or password!"})
}
return
}
res.sendStatus(400)
}
async function handle(req, res) {
2024-06-18 08:09:55 +02:00
if(req.method !== "GET")
return handle_other(req, res);
2024-06-16 20:59:21 +02:00
console.log(`received request of ${req.path}`)
2024-06-18 08:09:55 +02:00
if(req.path == "/") {
2024-06-24 23:54:38 +02:00
res.render("index", {sidebar: indexSidebar})
return
}
if(req.path == "/dashboard") {
let user = await getUser(req.cookies.token)
if(user) {
2024-06-25 01:24:57 +02:00
res.render("dashboard", {sidebar: sbstart + sbbasic + sblogout + sbend, user})
2024-06-24 23:54:38 +02:00
}
else {
res.status(401).redirect("/login")
}
return;
}
if(req.path === "/login") {
res.render("login", {sidebar: indexSidebar, error: null})
return
}
if(req.path === "/logout") {
res.clearCookie("token").redirect("/")
2024-06-18 08:09:55 +02:00
return
}
res.status(404).render("404")
2024-06-16 20:59:21 +02:00
}
server.listen(40080)