/* 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: } */ 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