import { Router } from 'express' import chalk from 'chalk' import { toLocalISO } from '../utils/util.js' export class StatusRouter extends Router { constructor() { super() this.get('/', (req, res) => { res.json({ status: 'ok' }) }) } } export class PingRouter extends Router { constructor() { super() this.post('/', (req, res) => { if (req.body?.message === 'ping') { res.json('pong') } else { res.status(400) res.json('Invalid request') } }) } } export const loggingMiddleware = (req, res, next) => { next() const coloredStatusCode = [ chalk.gray, chalk.green, chalk.blueBright, chalk.red, chalk.redBright, ][Math.floor(res.statusCode / 100) - 1](res.statusCode) console.log(`${toLocalISO(new Date())} | ${req.method} ${req.originalUrl} ${coloredStatusCode}`) } export const authMiddleware = getUserForSession => async (req, res, next) => { if (req.cookies.sid) { req.user = await getUserForSession(req.cookies.sid) console.log('Request from user: ' + req.user) } next() } export const authenticatedMiddleware = (req, res, next) => { req.user && next() }