aboutsummaryrefslogtreecommitdiff
path: root/auth
diff options
context:
space:
mode:
authorLarsVomMars2020-10-01 17:51:06 +0200
committerLarsVomMars2020-10-01 17:51:06 +0200
commitce4f9770702ee261b238a3466b1e1cf27246dfc8 (patch)
treea3b361003a5f0bd0a5670b7a6a3959380aa507fa /auth
parent590723afb4178e070a372d6e6054fe4d8549a4b0 (diff)
Login, sessions, password reset
Diffstat (limited to 'auth')
-rw-r--r--auth/index.js34
1 files changed, 32 insertions, 2 deletions
diff --git a/auth/index.js b/auth/index.js
index 9bc3f58..bbe3589 100644
--- a/auth/index.js
+++ b/auth/index.js
@@ -1,14 +1,44 @@
const express = require("express");
+const bcrypt = require("bcrypt");
const db = require("../db");
+
const app = express.Router();
-// TODO: Name list parser (teachers + pupils)
-// TODO: Add users (OTP)
// TODO: Change passwords
// TODO: Login (+ Frontend, cookie, etc)
app.use("/", express.static(__dirname + "/public"));
+app.post("/api/login", async (req, res) => {
+ const { username, password } = req.body;
+ if (!(username && password)) return res.send("error");
+ const user = await db.query("SELECT id, password FROM users WHERE username = ?", [username]);
+ if (!user.password) return res.send("error");
+ const loggedIn = await bcrypt.compare(password, user.password);
+ if (loggedIn) {
+ req.session.loggedIn = true;
+ req.session.uid = user.id;
+ }
+ return res.send(LoggedIn);
+});
+
+app.put("/api/password", async (req, res) => {
+ const { pwd, newPwd } = req.body;
+ if (!(pwd && newPwd)) return res.send("error");
+ 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");
+ try {
+ const newHash = await bcrypt.hash(newPwd, 12);
+ await db.query("UPDATE users SET password = ? WHERE id = ?", [newHash, req.session.uid]);
+ res.send("ok");
+ } catch (e) {
+ console.error(e);
+ res.send("error");
+ }
+});
+
app.get("/api/list", (req, res) => {});
module.exports = app;