You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.8 KiB
JavaScript

import express from 'express'
import crypto from 'crypto'
// import serveStatic from 'serve-static'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import { authMiddleware, loggingMiddleware, PingRouter, StatusRouter } from './server/helpers.js'
import { createDatabase, getUser, updateUser } from './db/database.js'
const app = express()
const sessions = {
store: {},
createSession(username) {
const sid = crypto.randomBytes(10).toString('hex')
this.store[sid] = username
return sid
},
getUserForSession(sid) {
return this.store[sid] ?? null
},
}
const db = createDatabase('./db.local.json', {
users: {
['BachoSeven']: {},
['aziis98']: {},
},
problems: {},
})
app.use(bodyParser.json())
app.use(cookieParser())
app.use(loggingMiddleware)
app.use(authMiddleware(sid => sessions.getUserForSession(sid)))
app.use('/api/status', new StatusRouter())
app.use('/api/ping', new PingRouter())
app.get('/api/current-user', (req, res) => {
res.json(sessions.getUserForSession(req.cookies.sid))
})
app.post('/api/login', (req, res) => {
const { username } = req.body
res.cookie('sid', sessions.createSession(username), { maxAge: 1000 * 60 * 60 * 24 * 7 })
res.json({ status: 'ok' })
})
app.post('/api/logout', (req, res) => {
res.cookie('sid', '', { expires: new Date() })
res.json({ status: 'ok' })
})
app.get('/api/user/:id', async (req, res) => {
const user = await getUser(db, req.params.id)
if (user) {
res.json(user)
} else {
res.sendStatus(404)
}
})
app.post('/api/user/:id', async (req, res) => {
await updateUser(db, req.params.id, req.body)
res.sendStatus(200)
})
app.all('*', (_req, res) => {
res.sendStatus(404)
})
app.listen(4000, () => {
console.log(`Started server on port 4000...`)
})