REST Service for POPCORN - ILIAS
alex
2025-05-16 c5bc857132ea7310dd5897f3aa77f3469016a6e2
app.js
@@ -2,20 +2,33 @@
   logger: true
})
const db = require("./lib/db")
const settings = require("./settings")
/////////////////////////////////////////////////////////////////////////
// AUTH
fastify.addHook("onRequest", async (req, res) => {
   const token = req.query.token
   if (token !== settings.authtoken) {
      console.error("# AUTH ERROR #", token)
      await promiseDelay(500) // delay response to avoid denial of service attacks
      res.code(403)
      return res.send({status: "error", error: "access denied"})
   }
   else {}
})
fastify
   .get('/api/users', async function (req, res) {
   .get('/users', async function (req, res) {
      const {offset, limit} = req.query
      const users = await db.getUsers(offset, limit)
      return res.send(users)
   })
   .get("/api/users/count", async function (req, res) {
   .get("/users/count", async function (req, res) {
      const count = await db.getUserCount()
      return res.send(count)
   })
   .get("/api/user/login/:login", async function (req, res) {
   .get("/user/login/:login", async function (req, res) {
      const {login} = req.params
      const user = await db.getUserByLogin(login)
      if (user.length) {
@@ -25,7 +38,7 @@
         return res.code(404).send({status: "error", msg: "not found"})
      }
   })
   .get("/api/user/userid/:userid", async function (req, res) {
   .get("/user/userid/:userid", async function (req, res) {
      const {userid} = req.params
      const user = await db.getUserByUserId(userid)
      if (user.length) {
@@ -39,10 +52,16 @@
/////////////////////////////////////////////////////////////////////////
fastify.listen({port: 4101}, function (err, address) {
fastify.listen({port: settings.port}, function (err, address) {
   if (err) {
      fastify.log.error(err)
      process.exit(1)
   }
   // Server is now listening on ${address}
})
/////////////////////////////////////////////////////////////////////////
async function promiseDelay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}