summaryrefslogtreecommitdiffstats
path: root/backend/src/routes.js
blob: a762d3a90de5300b40c8de4ecbaf7666732de757 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const express = require('express');
const sha512 = require('js-sha512');
const shortid = require('shortid');

const salt = 'suola';

const db = require('./db');

const buildSessionCookie = ({ sessionId, isLogout, remember }) => {
  if (!isLogout) {
    if (remember) {
      return `sessionId=${sessionId}; Domain=localhost; HttpOnly; SameSite=strict;`;
    } else {
      return `sessionId=${sessionId}; Domain=localhost; HttpOnly; SameSite=strict; Max-Age=86400;`;
    }
  } else {
    return `sessionId=deleted; Domain=localhost; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=strict;`;
  }
};

const normalRouter = express.Router();
const authedRouter = express.Router();

authedRouter.use(async (req, res, next) => {
  const cookies = req.cookies;
  const { sessionId } = cookies;

  if (!sessionId) {
    res.status(403);
    return res.json({
      message: 'Log in first!',
    });
  }

  const token = await db('tokens').where('value', sessionId).first();

  if (!token) {
    res.status(400);
    res.set('Set-Cookie', buildSessionCookie({ isLogout: true }));
    return res.json({
      message: 'Invalid session token.',
      sessionId,
    });
  }

  const user = await db('users').where({ id: token.user_id }).first();

  req.sessionId = sessionId;
  req.user = user;

  next();
});

normalRouter.get('/', (req, res) => {
  res.json({
    message: 'Backend API',
  });
});

normalRouter.post('/register', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    res.status(400);
    return res.json({
      error: 'Username or password missing.',
    });
  }

  const existingUuser = await db('users').where({ username }).first();
  if (existingUuser) {
    res.status(400);
    return res.json({
      error: 'Username already taken.',
    });
  }

  const pwHash = sha512(salt + password);
  const sessionId = shortid.generate();
  const user = (await db('users').insert({ username, password: pwHash }).returning('*'))[0];
  await db('tokens').insert({ user_id: user.id, type: 'session', value: sessionId });

  res.set('Set-Cookie', buildSessionCookie({ sessionId, remember: false, isLogout: false }));
  return res.json({
    username,
  });
});

normalRouter.post('/login', async (req, res) => {
  const { username, password, remember } = req.body;
  if (!username || !password) {
    res.status(400);
    return res.json({
      error: 'Username or password missing.',
    });
  }

  const user = await db('users').where({ username }).first();

  if (user) {
    const sessionId = shortid.generate();
    await db('tokens').insert({ user_id: user.id, type: 'session', value: sessionId });

    res.set('Set-Cookie', buildSessionCookie({ sessionId, remember, isLogout: false }));

    return res.json({
      username,
    });
  }

  res.status(403);
  res.json({
    error: 'Wrong username or password',
  });
});

authedRouter.post('/logout', async (req, res) => {
  if (req.user && req.sessionId) {
    await db('tokens').where({ value: req.sessionId }).delete();
  }
  res.status(204);
  res.set('Set-Cookie', buildSessionCookie({ isLogout: true }));
  res.send();
});

authedRouter.get('/user', (req, res) => {
  const user = req.user;
  return res.json({
    message: `Hello user ${user.username}!`,
    username: user.username,
  });
});

module.exports = { authedRouter, normalRouter };