Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs").promises
- const path = require("path")
- const crypto = require("crypto")
- const express = require("express")
- const multer = require("multer")
- const session = require("cookie-session")
- const expressPromiseRouter = require("express-promise-router")
- const PASSWORD = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8" // 'password'
- const APP_ROOT = path.join(__dirname, "..")
- const UPLOAD_DIR = path.join(APP_ROOT, "uploads")
- const upload = multer({
- storage: multer.memoryStorage(),
- limits: {
- fileSize: 2**24 // 16MiB
- }
- })
- const server = express()
- server.use(session({
- secret: "SESSION SECRET",
- cookie: {
- maxAge: 1000 * 60 * 60 * 24 * 7 // one week in milliseconds
- },
- resave: false,
- saveUninitialized: false
- }))
- server.use(express.static(UPLOAD_DIR))
- server.use("/dist", express.static(path.join(APP_ROOT, "dist"), {
- }))
- server.use(express.urlencoded({
- extended: false
- }))
- const app = expressPromiseRouter()
- app.get("/", async (req, res) => {
- res.render("index", { title: "Index" })
- })
- // login form
- app.get("/login", (req, res) => res.render("login", { title: "Login" }))
- app.post("/login", (req, res) => { // validate the login
- if (!req.body.password) return res.status(400).send("Missing password")
- if (crypto.createHash("sha256").update(req.body.password).digest("hex") !== PASSWORD) return res.status(403).send("Invalid password")
- req.session.authed = true
- req.session.save()
- res.redirect("/upload")
- })
- app.use("/upload", (req, res, next) => { // redirect to login if not authenticated
- if (!req.session || !req.session.authed) return res.redirect("/login")
- next()
- })
- app.get("/upload", (req, res) => res.render("upload", { title: "Upload" }))
- app.post("/upload", upload.single("file"), async (req, res) => { // handle file uploads
- if (!req.file) return res.status(400).send("Missing file")
- const newFilename = `${new Date().getTime()}${path.extname(req.file.originalname)}`
- await fs.writeFile(path.join(UPLOAD_DIR, newFilename), req.file.buffer)
- res.redirect(`/${newFilename}`)
- })
- server.use(app)
- server.set("view engine", "pug")
- server.listen(3000, () => console.log("running"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement