xssbook/index.js
2023-01-23 21:40:41 -05:00

135 lines
No EOL
2.6 KiB
JavaScript

const express = require('express')
const app = express()
const cache = require('./src/cache')
const con = require('./src/console')
const auth = require('./src/api/auth')
const pages = require('./src/api/pages')
const posts = require('./src/api/posts')
const users = require('./src/api/users')
app.set('trust proxy', true)
app.use(express.static('public'))
app.use(require('cookie-parser')())
app.use(express.json());
app.use((req, res, next) => {
var ip = req.headers['x-real-ip'] || req.socket.remoteAddress;
if (req.path !== '/console') {
let body = { ...req.body }
if (body.password !== undefined) {
body.password = '********'
}
con.log(
ip,
req.method,
req.path,
body
)
}
next()
})
app.use((req, res, next) => {
if (req.path.startsWith('/api/auth')) {
next()
return
}
const cookies = req.cookies
if (cookies === undefined || cookies.auth === undefined) {
if (req.method !== 'GET' && req.path.startsWith('/api')) {
res.status(401).send({msg: 'Unauthorized'})
return
}
next()
return
}
const user = cache.auth(req.cookies.auth)
if (user !== undefined) {
res.locals.user = user
} else if (req.method !== 'GET' && req.path.startsWith('/api')) {
res.status(401).send({msg: 'Unauthorized'})
return
}
next()
})
app.use('/api/auth', auth)
app.use('/api/posts', posts)
app.use('/api/users', users)
app.use('/', pages)
app.get('/console', (req, res) => {
res.send(con.render())
})
app.use((req, res, next) => {
res.status(404).sendFile('404.html', { root: './public' })
})
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
res.status(400).send({ msg: 'Invalid json body' })
return
}
console.error(err)
res.status(500).send({ msg: 'Internal server error' })
})
const cron = require('node-cron').schedule('*/5 * * * *', () => {
con.msg('Writing cache to database')
cache.dump()
})
const port = 8080
const server = app.listen(port, () => {
console.log(`App listening on port http://127.0.0.1:${port}`)
})
const close = () => {
console.log('Writing cache to database')
cache.dump()
console.log('Stopping cron jobs')
cron.stop()
server.close(() => {
console.log('HTTP server closed')
})
}
process.on('SIGINT', close)
process.on('SIGTERM', close)
process.on('SIGQUIT', close)