From c082552fae2542c8474af33c155dbccf7b2ad7ea Mon Sep 17 00:00:00 2001 From: Isaac Date: Sat, 7 May 2022 18:28:38 +0100 Subject: [PATCH] Update guilds route --- src/http.js | 26 ++++++++++++++++++++++++-- src/routes/api/admin/guilds/index.js | 14 +++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/http.js b/src/http.js index 5e7ccbd..5fbc234 100644 --- a/src/http.js +++ b/src/http.js @@ -1,6 +1,6 @@ const fastify = require('fastify')(); const oauth = require('@fastify/oauth2'); -const { randomBytes } = require('crypto'); +// const { randomBytes } = require('crypto'); const { short } = require('leeks.js'); const { join } = require('path'); const { readFiles } = require('node-dir'); @@ -31,7 +31,8 @@ module.exports = client => { cookieName: 'token', signed: false, }, - secret: randomBytes(16).toString('hex'), + // secret: randomBytes(16).toString('hex'), + secret: process.env.DB_ENCRYPTION_KEY, }); // auth @@ -44,6 +45,27 @@ module.exports = client => { } }); + fastify.decorate('isAdmin', async (req, res) => { + try { + const userId = req.user.payload.id; + const guildId = req.params.guild; + const guild = client.guilds.cache.get(guildId); + const guildMember = await guild.members.fetch(userId); + const isAdmin = guildMember.permissions.has('MANAGE_GUILD'); + + if (!isAdmin) { + return res.code(401).send({ + error: 'Unauthorised', + message: 'User is not authorised for this action', + statusCode: 401, + + }); + } + } catch (err) { + res.send(err); + } + }); + // logging fastify.addHook('onResponse', (req, res, done) => { done(); diff --git a/src/routes/api/admin/guilds/index.js b/src/routes/api/admin/guilds/index.js index c3e1d0a..54c5dc9 100644 --- a/src/routes/api/admin/guilds/index.js +++ b/src/routes/api/admin/guilds/index.js @@ -1,9 +1,17 @@ module.exports.get = fastify => ({ handler: async (req, res) => { const { client } = res.context.config; - const user = await client.users.fetch(req.user.payload.id); - console.log(req.user.payload.username, user?.tag); - res.send(client.guilds.cache); + const guilds = client.guilds.cache + .filter(async guild => { + const member = await guild.members.fetch(req.user.payload.id); + return member.permissions.has('MANAGE_GUILD'); + }) + .map(guild => ({ + id: guild.id, + logo: guild.iconURL(), + name: guild.name, + })); + res.send(guilds); }, onRequest: [fastify.authenticate], }); \ No newline at end of file