REST Service for POPCORN - ILIAS
alex
2025-05-15 2ce2d771a607d23ce67e6b07f86cb8cc76558771
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const fastify = require('fastify')({
   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('/users', async function (req, res) {
      const {offset, limit} = req.query
      const users = await db.getUsers(offset, limit)
      return res.send(users)
   })
   .get("/users/count", async function (req, res) {
      const count = await db.getUserCount()
      return res.send(count)
   })
   .get("/user/login/:login", async function (req, res) {
      const {login} = req.params
      const user = await db.getUserByLogin(login)
      if (user.length) {
         return res.send(user[0])
      }
      else {
         return res.code(404).send({status: "error", msg: "not found"})
      }
   })
   .get("/user/userid/:userid", async function (req, res) {
      const {userid} = req.params
      const user = await db.getUserByUserId(userid)
      if (user.length) {
         return res.send(user[0])
      }
      else {
         return res.code(404).send({status: "error", msg: "not found"})
      }
   })
 
 
/////////////////////////////////////////////////////////////////////////
 
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))
}