aboutsummaryrefslogtreecommitdiffstats
path: root/routes/auth.js
blob: d6949d42fed44bdbda4ebd5d9f526eadd0b6749b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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;