diff options
-rw-r--r-- | app.js | 3 | ||||
-rw-r--r-- | auth/index.js | 23 |
2 files changed, 17 insertions, 9 deletions
@@ -8,7 +8,8 @@ const quotes = require("./quotes"); const app = express(); -app.use(session({ secret: "keyboard cat", resave: false, saveUninitialized: true, cookie: { secure: true } })); +// TODO: Use secure: true in production +app.use(session({ secret: "keyboard cat", resave: false, saveUninitialized: true, cookie: { secure: false } })); app.use(express.urlencoded({ extended: true })); app.use(express.json()); diff --git a/auth/index.js b/auth/index.js index 0dac61c..3fb86d3 100644 --- a/auth/index.js +++ b/auth/index.js @@ -7,35 +7,42 @@ const app = express.Router(); // TODO: Change passwords // TODO: Login (+ Frontend, cookie, etc) -app.use("/", express.static(__dirname + "/public")); +app.use( + "/", + (req, res, next) => { + if (!req.session.loggedIn) next(); + else res.redirect("/"); + }, + express.static(__dirname + "/public") +); app.post("/api/login", async (req, res) => { const { username, password } = req.body; - if (!(username && password)) return res.send("error"); + if (!(username && password)) return res.redirect("/auth"); const user = (await db.query("SELECT id, password FROM users WHERE username = ?", [username]))[0]; - if (!user.password) return res.send("error"); + if (!user.password) return res.redirect("/auth"); const loggedIn = await bcrypt.compare(password, user.password); if (loggedIn) { req.session.loggedIn = true; req.session.uid = user.id; } - return res.send(loggedIn); + res.redirect("/auth"); }); app.put("/api/password", async (req, res) => { const { pwd, newPwd } = req.body; - if (!(pwd && newPwd)) return res.send("error"); + if (!(pwd && newPwd)) return res.redirect("/auth"); const user = await db.query("SELECT id, password FROM users WHERE username = ?", [username]); if (!user.password) return res.send("error"); if (!((await bcrypt.compare(pwd, user.password)) && user.id === req.session.uid && req.session.loggedIn)) - return res.send("error"); + return res.redirect("/auth"); try { const newHash = await bcrypt.hash(newPwd, 12); await db.query("UPDATE users SET password = ? WHERE id = ?", [newHash, req.session.uid]); - res.send("ok"); + res.redirect("/auth"); } catch (e) { console.error(e); - res.send("error"); + res.redirect("/auth"); } }); |