Advertisement
osmarks

Untitled

Jan 18th, 2020
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs").promises
  2. const path = require("path")
  3. const crypto = require("crypto")
  4. const express = require("express")
  5. const multer = require("multer")
  6. const session = require("cookie-session")
  7. const expressPromiseRouter = require("express-promise-router")
  8.  
  9. const PASSWORD = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8" // 'password'
  10. const APP_ROOT = path.join(__dirname, "..")
  11. const UPLOAD_DIR = path.join(APP_ROOT, "uploads")
  12.  
  13. const upload = multer({
  14.     storage: multer.memoryStorage(),
  15.     limits: {
  16.         fileSize: 2**24 // 16MiB
  17.     }
  18. })
  19.  
  20. const server = express()
  21.  
  22. server.use(session({
  23.     secret: "SESSION SECRET",
  24.     cookie: {
  25.         maxAge: 1000 * 60 * 60 * 24 * 7 // one week in milliseconds
  26.     },
  27.     resave: false,
  28.     saveUninitialized: false
  29. }))
  30. server.use(express.static(UPLOAD_DIR))
  31. server.use("/dist", express.static(path.join(APP_ROOT, "dist"), {
  32. }))
  33. server.use(express.urlencoded({
  34.     extended: false
  35. }))
  36.  
  37. const app = expressPromiseRouter()
  38.  
  39. app.get("/", async (req, res) => {
  40.     res.render("index", { title: "Index" })
  41. })
  42.  
  43. // login form
  44. app.get("/login", (req, res) => res.render("login", { title: "Login" }))
  45. app.post("/login", (req, res) => { // validate the login
  46.     if (!req.body.password) return res.status(400).send("Missing password")
  47.     if (crypto.createHash("sha256").update(req.body.password).digest("hex") !== PASSWORD) return res.status(403).send("Invalid password")
  48.     req.session.authed = true
  49.     req.session.save()
  50.     res.redirect("/upload")
  51. })
  52.  
  53. app.use("/upload", (req, res, next) => { // redirect to login if not authenticated
  54.   if (!req.session || !req.session.authed) return res.redirect("/login")
  55.   next()
  56. })
  57. app.get("/upload", (req, res) => res.render("upload", { title: "Upload" }))
  58. app.post("/upload", upload.single("file"), async (req, res) => { // handle file uploads
  59.     if (!req.file) return res.status(400).send("Missing file")
  60.     const newFilename = `${new Date().getTime()}${path.extname(req.file.originalname)}`
  61.     await fs.writeFile(path.join(UPLOAD_DIR, newFilename), req.file.buffer)
  62.     res.redirect(`/${newFilename}`)
  63. })
  64.  
  65. server.use(app)
  66.  
  67. server.set("view engine", "pug")
  68. server.listen(3000, () => console.log("running"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement