From 81df4ebf075aba8d2e2bb753eeef680f3c6baba3 Mon Sep 17 00:00:00 2001 From: Fernando Date: Fri, 26 Apr 2024 18:58:30 -0300 Subject: [PATCH] fix --- Discord/discordIndex.js | 10 ++ Discord/updateProductMassage.js | 9 -- config/web-config.js | 2 +- functions.js | 102 +++++++++++++++++++- index.js | 137 +++++++++++++++++++++++++-- public/css/perms.css | 90 ++++++++++++++++++ public/css/reusable/styleRoot.css | 6 +- public/js/perms.js | 148 ++++++++++++++++++++++++++++++ views/dashboard.ejs | 11 +++ views/perms.ejs | 36 +++++++- views/sales.ejs | 82 +++++++++-------- 11 files changed, 568 insertions(+), 65 deletions(-) delete mode 100644 Discord/updateProductMassage.js create mode 100644 public/css/perms.css create mode 100644 public/js/perms.js diff --git a/Discord/discordIndex.js b/Discord/discordIndex.js index 3095f14..45db882 100644 --- a/Discord/discordIndex.js +++ b/Discord/discordIndex.js @@ -96,6 +96,16 @@ module.exports = (Discord, client) => { try { var DiscordServer = await client.guilds.cache.get(interaction.guildId); var DiscordChannel = await DiscordServer.channels.cache.get(interaction.channelId) + let verifyPerms = await functions.verifyPermissions(interaction.user.id,interaction.guildId,Discord,client) + if (verifyPerms.error == true) { + return + } + if (verifyPerms.perms.owner == false && verifyPerms.perms.command == false) { + interaction.reply({content:'Você não tem permissão para executar comandos',ephemeral: true}) + return + } + + // interacao do botao de compra de um produto if (interaction.customId.includes('comprar')) { let server = await db.findOne({colecao:"servers",doc:interaction.guildId}) diff --git a/Discord/updateProductMassage.js b/Discord/updateProductMassage.js deleted file mode 100644 index 1604cd2..0000000 --- a/Discord/updateProductMassage.js +++ /dev/null @@ -1,9 +0,0 @@ -const db = require('../Firebase/models') -module.exports = async (Discord, client, data) => { - const DiscordServer = await client.guilds.cache.get(data.serverID); - const DiscordChannel = await DiscordServer.channels.cache.get(data.channelID); - var serverDB = await db.findOne({ colecao: 'servers', doc: await data.serverID }) - var productID = await data.productID - var produto = await serverDB.products.find(product => product.productID == productID) - let mensageDiscord = await DiscordChannel.messages.fetch(produto.mensageID) -} \ No newline at end of file diff --git a/config/web-config.js b/config/web-config.js index cdb2780..a988ba3 100644 --- a/config/web-config.js +++ b/config/web-config.js @@ -8,7 +8,7 @@ module.exports = { }, port: process.env.PORT || 3000, // serviceAccount: JSON.parse(process.env.SERVICEACCOUNT), - serviceAccount: require('./fireabse.json'), + serviceAccount: require('./firebase.json'), secret:process.env.CLIENTSECRET, clientId:process.env.CLIENTID, redirect:process.env.REDIRECTURL, diff --git a/functions.js b/functions.js index 86a949e..9decc02 100644 --- a/functions.js +++ b/functions.js @@ -2,15 +2,115 @@ const axios = require('axios') const sharp = require('sharp'); const fs = require('fs'); const stripe = require('stripe')(require('./config/web-config').stripe); -const db = require('./Firebase/models') +const db = require('./Firebase/models'); module.exports = { + verifyPermissions: async (user, server, Discord, client) => { + try { + let serverDB = await db.findOne({ colecao: "servers", doc: server }) + if (!serverDB) { + return { error: true, err: "server not found" }; + } + const guild = await client.guilds.cache.get(server); + if (!guild) { + return { error: true, err: "server not found" }; + } + + const member = await guild.members.cache.get(user); + + if (!member) { + return { error: true, err: "member not found" }; + } + + if (guild.ownerId == member.user.id) { + return { + error: false, perms: { + owner: true, + botEdit: true, + paymentEdit: true, + commands: true, + commandsAllChannel: true, + } + } + } + if (serverDB.permissions) { + + + const memberRoles = await member.roles.cache; + + if (memberRoles.size > 1) { + const UserRolesPerms = await serverDB.permissions.filter(role => memberRoles.has(role.id)); + if (UserRolesPerms.length > 0) { + let totalPerms = {} + await UserRolesPerms.forEach((element) => { + let perms = element.perms + if (perms.botEdit == true) { + totalPerms.botEdit = true + } + if (perms.paymentEdit == true) { + totalPerms.paymentEdit = true + } + if (perms.commands == true) { + totalPerms.commands = true + } + if (perms.commandsAllChannel == true) { + totalPerms.commandsAllChannel = true + } + }) + if (!('botEdit' in totalPerms)) { + totalPerms.botEdit = false + } + if (!('paymentEdit' in totalPerms)) { + totalPerms.paymentEdit = false + } + if (!('commands' in totalPerms)) { + totalPerms.commands = false + } + if (!('commandsAllChannel' in totalPerms)) { + totalPerms.commandsAllChannel = false + } + totalPerms.owner = false + return { error: false, perms: totalPerms } + } else { + return { + error: false, perms: { + botEdit: true, + paymentEdit: false, + commands: true, + commandsAllChannel: false, + owner: false + } + } + } + } else { + console.log(`${member.user.username} não possui cargos.`); + return { error: true, err: "user not roles" }; + } + } else { + return { + error: false, perms: { + botEdit: true, + paymentEdit: false, + commands: true, + commandsAllChannel: false, + owner: false + } + } + } + } catch (error) { + console.log(error); + return { error: true, err: error } + } + }, subscriptionStatus: async (req, res, next) => { if (!req.params.id || !req.session.uid) { res.redirect('/') return } let server = await db.findOne({ colecao: "servers", doc: req.params.id }) + if ("vitalicio" in server && server.vitalicio == true) { + next() + } if (server) { try { const assinatura = await stripe.subscriptions.retrieve(server.subscription); diff --git a/index.js b/index.js index f05ec9b..1df6735 100644 --- a/index.js +++ b/index.js @@ -169,7 +169,6 @@ app.get('/auth/callback', async (req, res) => { ...headers } }).then((res) => { return res.data }).catch((err) => console.error(err)); - await db.create('users', userResponse.id, { id: userResponse.id, username: userResponse.username, @@ -259,6 +258,16 @@ app.get('/server/:id', functions.subscriptionStatus, async (req, res) => { return } + let verifyPerms = await functions.verifyPermissions(user.id, server.id, Discord, client) + if (verifyPerms.error == true) { + res.redirect('/dashboard') + return + } + if ('botConfig' in verifyPerms.perms && verifyPerms.perms.botEdit == false) { + res.redirect('/dashboard?botedit=false') + return + } + let analytics = await db.findOne({ colecao: "analytics", doc: req.params.id }) let comprasConcluidas = JSON.stringify(await functions.getDatesLast7Days(analytics["vendas completas"], functions.formatDate)) @@ -268,9 +277,6 @@ app.get('/server/:id', functions.subscriptionStatus, async (req, res) => { }) - - - app.get('/server/sales/:id', functions.subscriptionStatus, async (req, res) => { let serverID = req.params.id let user = await db.findOne({ colecao: 'users', doc: req.session.uid }) @@ -282,6 +288,16 @@ app.get('/server/sales/:id', functions.subscriptionStatus, async (req, res) => { res.redirect('/dashboard') return } + let verifyPerms = await functions.verifyPermissions(user.id, server.id, Discord, client) + if (verifyPerms.error == true) { + res.redirect('/dashboard') + return + } + + if ('botConfig' in verifyPerms.perms && verifyPerms.perms.botConfig == false) { + res.redirect(`/server/${serverID}`) + return + } let bankData = server.bankData ? server.bankData : null const guilds = client.guilds.cache; @@ -295,7 +311,7 @@ app.get('/server/sales/:id', functions.subscriptionStatus, async (req, res) => { const textChannels = channels.filter(channel => channel.type === 0); - res.render('sales', { host: `${webConfig.host}`, bankData: bankData, user: user, server: server, channels: textChannels, formatarMoeda: functions.formatarMoeda }) + res.render('sales', { perms: verifyPerms.perms, host: `${webConfig.host}`, bankData: bankData, user: user, server: server, channels: textChannels, formatarMoeda: functions.formatarMoeda }) }) @@ -343,6 +359,7 @@ app.get('/server/analytics/:id', functions.subscriptionStatus, async (req, res) app.get('/server/permissions/:id', functions.subscriptionStatus, async (req, res) => { + let serverID = req.params.id let user = await db.findOne({ colecao: 'users', doc: req.session.uid }) let server = await db.findOne(({ colecao: 'servers', doc: serverID })) @@ -351,7 +368,27 @@ app.get('/server/permissions/:id', functions.subscriptionStatus, async (req, res return } - res.render('perms', { host: `${webConfig.host}`, user: user, server: server }) + let verifyPerms = await functions.verifyPermissions(user.id, server.id, Discord, client) + if (verifyPerms.error == true) { + res.redirect('/dashboard') + return + } + + if (verifyPerms.error == false && verifyPerms.perms.owner == false) { + res.redirect(`/server/${serverID}`) + return + } + + const guilds = client.guilds.cache; + const isBotInServer = guilds.has(serverID); + if (!isBotInServer) { + res.redirect(`/addbot/${serverID}`) + return + } + let guild = guilds.get(serverID) + let roles = guild.roles.cache + let rolesFilter = roles.filter(role => role.managed == false && role.mentionable == false) + res.render('perms', { host: `${webConfig.host}`, user: user, server: server, roles: JSON.stringify(rolesFilter) }) }) @@ -475,12 +512,96 @@ app.post('/config/change', async (req, res) => { } res.status(200).json({ success: true }) } catch (error) { - res.status(200).json({ success: false,data:'Erro ao salvar as configurações' }) + res.status(200).json({ success: false, data: 'Erro ao salvar as configurações' }) console.log(error); } }) +app.post('/perms/changeOne', async (req, res) => { + try { + let server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + let roleID = await req.body.roleID + if (!server || !roleID) { + return + } + if (!('permissions' in server)) { + await db.update('servers', req.body.serverID, { + permissions: [ + { + id:roleID, + perms: { + botEdit: true, + paymentEdit: false, + commands: true, + commandsAllChannel: false, + } + } + ] + }) + } + server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + + let permissions = server.permissions + let rolePermission = permissions.find(element=>element.id == roleID) + let index = permissions.findIndex(element=>element.id == roleID) + + rolePermission.perms[await req.body.item] = await req.body.value + + permissions[index] = rolePermission + + console.log(permissions); + await db.update('servers', req.body.serverID, { + permissions: permissions + }) + + } catch (error) { + + } +}) + +app.post('/perms/get', async (req, res) => { + try { + let server = await db.findOne({ colecao: "servers", doc: req.body.serverID }) + let roleID = await req.body.roleID + if (!server || !roleID) { + return + } + if (!('permissions' in server)) { + res.status(200).json({ success: true, data: { + botEdit: true, + paymentEdit: false, + commands: true, + commandsAllChannel: false, + owner: false + } }) + return + } + let rolePermission = server.permissions.find(element=>element.id == roleID) + let roleData + if (rolePermission) { + roleData = rolePermission.perms + }else{ + roleData = { + botEdit: true, + paymentEdit: false, + commands: true, + commandsAllChannel: false, + owner: false + } + } + res.status(200).json({ success: true, data: roleData}) + + } catch (error) { + console.log(error); + res.status(200).json({ success: false }) + } +}) + + + + + //TODO Mercado Pago const mercadoPago = require('./mercadoPago.js') @@ -496,7 +617,7 @@ app.use('/', stripeRoutes); //TODO PRODUTOS ROUTES const produtoRoutes = require('./stripe/productsRoutes.js'); -const { doc } = require("firebase/firestore"); +const { Filter } = require("firebase-admin/firestore"); app.use('/', produtoRoutes); diff --git a/public/css/perms.css b/public/css/perms.css new file mode 100644 index 0000000..ae3e832 --- /dev/null +++ b/public/css/perms.css @@ -0,0 +1,90 @@ +#main-containner { + width: calc(100% - 18em); + position: relative; + top: 2em; + left: 18em; + display: flex; + justify-content: center; + align-items: center; + padding: 1em; + min-height: calc(100vh - 5em); + +} + +#main-content { + width: 100%; + display: flex; + justify-content: space-between; + align-items: center; + min-height: calc(100vh - 12em); + gap: 2em; + padding: 1em; + padding-right: 3em; + padding-left: 3em; + margin-top: 5em; +} + +#roles-containner { + width: 30%; + padding: 1em; + display: flex; + flex-direction: column; + align-items: center; + background-color: var(--tertiary-color); + border-radius: var(--border-radius-mid); + min-height: calc(100vh - 13em); +} + +#roles-row{ + width: 100%; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 1em; + padding-top: 1em; + margin-bottom: 1em; + height: 100%; +} + +.text-role-col { + cursor: pointer; + text-align: center; + font-size: 1em; + font-weight: 500; + color: var(--color-text-primary); + font-family: 'poppins'; + text-shadow: 0px 0px 25px var(--text-gray-color-primary); + transition: 0.7s; + &:hover{ + opacity: 0.8; + text-decoration: underline; + transition: 0.7s; + } +} + + +#permissions-containner{ + width: 60%; + padding: 1em; + min-height: calc(100vh - 13em); +} + +#permission-col{ + display: flex; + flex-direction: column; + justify-content: start; + align-items: start; + margin-top: 2em; + gap: 1.5em; + .title-col{ + text-align: start; + } +} + +.perm-content{ + display: flex; + justify-content: space-between; + gap: 1em; + width: 100%; +} \ No newline at end of file diff --git a/public/css/reusable/styleRoot.css b/public/css/reusable/styleRoot.css index 650f552..11f615f 100644 --- a/public/css/reusable/styleRoot.css +++ b/public/css/reusable/styleRoot.css @@ -248,15 +248,15 @@ a { transition: .4s; } -#checkbox:checked+.slider { +#checkbox:checked+.slider,#perm-commands-checkbox:checked+.slider,#perm-commandsAllChannel-checkbox:checked+.slider,#perm-botEdit-checkbox:checked+.slider,#perm-paymentEdit-checkbox:checked+.slider { background-color: var(--main-color-purple); } -#checkbox:focus+.slider { +#checkbox:focus+.slider , #perm-commands-checkbox:focus+.slider,#perm-commandsAllChannel-checkbox:focus+.slider,#perm-botEdit-checkbox:focus+.slider,#perm-paymentEdit-checkbox:focus+.slider { box-shadow: 0 0 1px var(--main-color-purple); } -#checkbox:checked+.slider:before { +#checkbox:checked+.slider:before,#perm-commands-checkbox:checked+.slider:before,#perm-commandsAllChannel-checkbox:checked+.slider:before,#perm-botEdit-checkbox:checked+.slider:before,#perm-paymentEdit-checkbox:checked+.slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); diff --git a/public/js/perms.js b/public/js/perms.js new file mode 100644 index 0000000..a079b39 --- /dev/null +++ b/public/js/perms.js @@ -0,0 +1,148 @@ +let serverID = location.pathname.replace('/server/permissions/', "") + + +let rolesCol = document.querySelectorAll('.roles-col span') +async function convertHexColor(color) { + color = parseInt(color) + if (color == 0) { + return '#828e94' + } + return `#${await color.toString(16)}` +} +rolesCol.forEach(async elemento => { + const cor = elemento.getAttribute('data-color'); + let convertColor = await convertHexColor(cor) + console.log(convertColor); + elemento.style.color = convertColor; +}); + +document.getElementById('roles-row').addEventListener('click',async function (event) { + if (event.target.classList.contains('text-role-col')) { + document.querySelectorAll('.text-role-col').forEach(text=>{ + text.style.textDecoration = 'none' + }) + + let element = event.target + element.style.textDecoration = 'underline' + let id = element.getAttribute('data-roleID') + let permRow = document.getElementById('permissions-row') + permRow.setAttribute('data-rolesIdEdit', id) + let permsActual = await fetch('/perms/get', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + serverID: serverID, + roleID:id + }), + }).then((response)=>{return response.json()}) + if (!permsActual.data) { + return + } + + permRow.innerHTML = ` +
+
+
+
Permitir usar comandos
+
Caso esteja ativo, quem estiver com cargo poderá usar os comandos do bot.
+
+
+
+ + +
+
+
+
+
+
+
Permitir usar comandos em qualquer canal
+
Caso esteja ativo, quem estiver com cargo poderá usar os comandos do bot em qualquer canal.
+
+
+
+ + +
+
+
+
+
+
+
Permitir configurar o bot
+
Caso esteja ativo, quem estiver com cargo poderá acessar esse site e configurar o bot..
+
+
+
+ + +
+
+
+
+
+
+
Permitir configurar meios de pagamento
+
Caso esteja ativo, quem estiver com cargo poderá acessar esse site e configurar os metodos de pagamento.
+
+
+
+ + +
+
+
+
+ + ` + document.getElementById('perm-commands-checkbox').addEventListener('click', () => { + sendModifyPerm('perm-commands-checkbox') + }) + document.getElementById('perm-commandsAllChannel-checkbox').addEventListener('click', () => { + sendModifyPerm('perm-commandsAllChannel-checkbox') + }) + document.getElementById('perm-paymentEdit-checkbox').addEventListener('click', () => { + sendModifyPerm('perm-paymentEdit-checkbox') + }) + document.getElementById('perm-botEdit-checkbox').addEventListener('click', () => { + sendModifyPerm('perm-botEdit-checkbox') + }) + successNotify('Cargo trocado!') + } +}); + +function sendModifyPerm(item) { + let itemDOM = document.getElementById(item) + let itemName = item.replace('perm-', "").replace('-checkbox', "") + let role = document.getElementById('permissions-row').getAttribute('data-rolesIdEdit') + if (itemDOM && itemName && role) { + fetch('/perms/changeOne', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + serverID: serverID, + item: itemName, + value: itemDOM.checked, + roleID:role + }), + }) + successNotify('Permissões alteradas!') + } +} + diff --git a/views/dashboard.ejs b/views/dashboard.ejs index 536eff8..6ce8d93 100644 --- a/views/dashboard.ejs +++ b/views/dashboard.ejs @@ -52,8 +52,19 @@ + + <%- include('./reusable/script.ejs') %> + \ No newline at end of file diff --git a/views/perms.ejs b/views/perms.ejs index bc87aa8..d491ae5 100644 --- a/views/perms.ejs +++ b/views/perms.ejs @@ -3,7 +3,7 @@ <%- include('./reusable/head.ejs') %> - +
@@ -11,11 +11,41 @@
<%- include('./reusable/header.ejs',{index:5}) %>
- +
+
+
+
+

Cargos

+

Clique no cargo que deseja editar as permissões!

+
+
+
+ <% JSON.parse(roles).forEach(element => { %> +
+ <%= element.name %> +
+ <% }) %> +
+
+
+
+
+
+

Permissões

+

As opção marcadas são alteradas automaticamente no sistema!

+
+
+

+ Clique em algum cargo para comecar a editar +

+
+
+
+
<%- include('./reusable/script.ejs') %> - + \ No newline at end of file diff --git a/views/sales.ejs b/views/sales.ejs index a99c98f..e8da798 100644 --- a/views/sales.ejs +++ b/views/sales.ejs @@ -114,50 +114,52 @@
-

Pagamentos

-

- Adicione os seus dados bancarios abaixo. -

-
-
-
- - -
-
- - -
-
- - - -
-
- - -
-
-
- - + <% if (perms.owner == true || perms.paymentEdit && perms.paymentEdit == true) { %> +

Pagamentos

+

+ Adicione os seus dados bancarios abaixo. +

+
+
+
+ +
-
- - +
+ +
-
-
-
- - +
+ + + +
+
+ + +
+
+
+ + +
+
+ + +
+
+
+
+ + +
+
-
-
+ <% }%>

Produtos