aboutsummaryrefslogtreecommitdiff
path: root/src/auth.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/auth.js')
-rw-r--r--src/auth.js35
1 files changed, 34 insertions, 1 deletions
diff --git a/src/auth.js b/src/auth.js
index f907e6c..78e3dea 100644
--- a/src/auth.js
+++ b/src/auth.js
@@ -1,4 +1,5 @@
1const jwt = require("jsonwebtoken"); 1const jwt = require("jsonwebtoken");
2const { db } = require("./db");
2const { JWT_KEY } = require("./"); 3const { JWT_KEY } = require("./");
3 4
4function authenticateToken(req, res, next) { 5function authenticateToken(req, res, next) {
@@ -24,4 +25,36 @@ function authenticateToken(req, res, next) {
24 } 25 }
25} 26}
26 27
27module.exports = { authenticateToken }; 28function authenticateAdmin(req, res, next) {
29 if (!req.cookies || !req.cookies.auth_token) {
30 return res.redirect("/login");
31 }
32
33 const token = req.cookies.auth_token;
34
35 // If no token, deny access
36 if (!token) {
37 return res.redirect(
38 `/login?redirect=${encodeURIComponent(req.originalUrl)}`,
39 );
40 }
41
42 try {
43 const user = jwt.verify(token, JWT_KEY);
44 req.user = user;
45 const isAdmin = db
46 .query("SELECT isAdmin FROM users WHERE id = $id and isAdmin = 1")
47 .get({
48 id: req.user.id,
49 });
50 if (isAdmin) {
51 next();
52 } else {
53 res.status(400).send("only admins can invite");
54 }
55 } catch (error) {
56 res.send(`failed to authenticate as admin: ${error}`);
57 }
58}
59
60module.exports = { authenticateToken, authenticateAdmin };