summaryrefslogtreecommitdiffstats
path: root/server/api/authentication.js
blob: 2ac8f461ac5f0ea97458352d3083a2de67e2cf15 (plain) (blame)
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
/* global __appdir */
const path = require('path')
var express = require('express')
const { decorateApp } = require('@awaitjs/express')
var noAuthRouter = decorateApp(express.Router())
var authentication = require(path.join(__appdir, 'lib', 'authentication'))

// Authentification method for the API using the authorization header. (GET)
noAuthRouter.postAsync('/token', async (req, res) => {
  const body = req.body
  const result = await authentication.verifyUser(body.username, body.password)
  const code = result.code
  delete result.code
  return res.status(code).send(result)
})

/*
 * username
 * password
 *
 * @return: Return an object with the jwt. { token:<TOKEN> }
 */
noAuthRouter.postAsync('/cookies', async (req, res) => {
  const body = req.body
  const result = await authentication.verifyUser(body.username, body.password)
  const code = result.code
  delete result.code
  if (code !== 200) return res.status(code).send(result)
  else {
    // The token has the form header.payload.signature
    // We split the cookie in header.payload and signature in two seperate cookies.
    // The signature cookie is httpOnly so JavaScript never has access to the full cookie.
    // Read more at: https://medium.com/lightrail/getting-token-authentication-right-in-a-stateless-single-page-application-57d0c6474e3
    const split = result.token.split('.')
    const headerPayload = split[0] + '.' + split[1]
    const signature = split[2]
    res.cookie('jwt_hp', headerPayload, { secure: true, httpOnly: false, sameSite: 'strict' })
    res.cookie('jwt_s', signature, { secure: true, httpOnly: true, sameSite: 'strict' })
    return res.send()
  }
})

// Logout method for the frontend. Deleting the cookies by overwriting them.
noAuthRouter.post('/logout', (req, res) => {
  // End session properly.
  res.clearCookie('jwt_hp')
  res.clearCookie('jwt_s')
  // TODO: blacklisting jwt ?
  // authentication.logout()
  // TODO: Implement.. blacklisting for jwt's and destroy the cookies..
  // Maybe use express-jwt and use the rewoke function.
  return res.status(200).send()
})

module.exports.noAuthRouter = noAuthRouter