aboutsummaryrefslogtreecommitdiffstats
path: root/routes/auth.js
diff options
context:
space:
mode:
authorpack <pack@packgekko.xyz>2026-08-12 17:06:50 +0000
committerpack <pack@packgekko.xyz>2026-08-12 17:06:50 +0000
commit5611527e313c4add16c432e5cf9d55a987558c02 (patch)
tree59ad054325096b6305277b94982bbe7f7f585f59 /routes/auth.js
parentd3adc16a08d95d6e331de55d7d3bf05a66a874a8 (diff)
downloadcrud-5611527e313c4add16c432e5cf9d55a987558c02.tar.gz
final commit
Diffstat (limited to 'routes/auth.js')
-rw-r--r--routes/auth.js76
1 files changed, 76 insertions, 0 deletions
diff --git a/routes/auth.js b/routes/auth.js
index e69de29..d6949d4 100644
--- a/routes/auth.js
+++ b/routes/auth.js
@@ -0,0 +1,76 @@
+const express = require('express');
+const bcrypt = require('bcryptjs');
+const db = require('../db');
+const requireAuth = require('../middleware/auth');
+
+const router = express.Router();
+
+/* register */
+router.post('/register', async (req, res) =>
+{
+ const { username, password } = req.body;
+ if (!username || !password)
+ {
+ return res.status(400).json({ error: 'Username and password required' });
+ }
+ try
+ {
+ const existing = db.prepare('SELECT id FROM users WHERE username = ?').get(username);
+ if (existing)
+ {
+ return res.status(409).json({ error: 'Username already taken' });
+ }
+ const hashed = bcrypt.hashSync(password, 10);
+ const result = db.prepare('INSERT INTO users (username, password) VALUES (?, ?)').run(username, hashed);
+ req.session.userId = result.lastInsertRowid;
+ res.status(201).json({ id: result.lastInsertRowid, username });
+ } catch (err)
+ {
+ res.status(500).json({ error: 'Registration failed' });
+ }
+});
+
+/* login. */
+router.post('/login', async (req, res) =>
+{
+ const { username, password } = req.body;
+ if (!username || !password)
+ {
+ return res.status(400).json({ error: 'Username and password required' });
+ }
+ try
+ {
+ const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
+ if (!user || !bcrypt.compareSync(password, user.password))
+ {
+ return res.status(401).json({ error: 'Invalid username or password' });
+ }
+ req.session.userId = user.id;
+ res.json({ id: user.id, username: user.username });
+ } catch (err)
+ {
+ res.status(500).json({ error: 'Login failed' });
+ }
+});
+
+/* logout */
+router.post('/logout', (req, res) =>
+{
+ req.session.destroy(() =>
+ {
+ res.clearCookie('connect.sid');
+ res.json({ message: 'Logged out' });
+ });
+});
+
+/* check session */
+router.get('/check', (req, res) =>
+{
+ if (req.session.userId)
+ {
+ return res.json({ loggedIn: true });
+ }
+ res.status(401).json({ loggedIn: false });
+});
+
+module.exports = router;