Waiting for the caching state from discord client

This commit is contained in:
Dennis Heinrich 2024-04-28 21:15:19 +02:00
parent d08bf65ef5
commit ef9d2054d7
2 changed files with 112 additions and 101 deletions

View file

@ -46,28 +46,37 @@ client.once(Events.ClientReady, readyClient => {
}); });
}); });
client.on('ready', () => {
console.log('Discord is connected and cached');
event.emit('discord:ready');
});
event.on('verification:success', (authenticationObject, internetProtocolAddress) => { event.on('verification:success', (authenticationObject, internetProtocolAddress) => {
console.log(authenticationObject.guildId) client.guilds.fetch().then(async () => {
console.log(authenticationObject.userId) const guild = await client.guilds.fetch(authenticationObject.guildId);
let guild = client.guilds.cache.get(authenticationObject.guildId); const member = await guild.members.fetch(authenticationObject.userId);
console.log(guild) const role = guild.roles.cache.get(verifiedRoleId);
let member = guild.members.cache.get(authenticationObject.userId);
console.log(member) if (role && member) {
if(member) { member.roles.add(role)
member.roles.add(verifiedRoleId); .then(() => {
} console.log(`Role ${role.name} has been added to ${member.user.tag}`)
let embedBuilder = new EmbedBuilder();
let embedBuilder = new EmbedBuilder(); embedBuilder.setTitle('Verifizierung abgeschlossen');
embedBuilder.setTitle('Verifizierung abgeschlossen'); embedBuilder.setFields([
embedBuilder.setFields([ { name: 'Benutzername', value: `<@${member.id}>`, inline: false },
{ name: 'Benutzername', value: `<@${member.id}>`, inline: false }, { name: 'Zeitpunkt', value: `${new Date().toISOString()}`, inline: false },
{ name: 'Zeitpunkt', value: `${new Date().toISOString()}`, inline: false }, { name: 'IP-Adresse', value: internetProtocolAddress, inline: false },
{ name: 'IP-Adresse', value: internetProtocolAddress, inline: false }, { name: 'IP-Informationen', value: `[Informationen anzeigen](https://ipinfo.io/${internetProtocolAddress})`, inline: false },
{ name: 'IP-Informationen', value: `[Informationen anzeigen](https://ipinfo.io/${internetProtocolAddress})`, inline: false }, { name: 'User-ID', value: `${member.id}`, inline: false },
{ name: 'User-ID', value: `${member.id}`, inline: false }, ]);
]); client.channels.cache.get(channelLogsId).send({embeds: [embedBuilder]});
})
client.channels.cache.get(channelLogsId).send({embeds: [embedBuilder]}); .catch(console.error);
} else {
console.log('Role or member not found');
}
});
}); });
client.login(discordToken); client.login(discordToken);

View file

@ -6,89 +6,91 @@ const event = require('../events/index').eventBus;
const blacklist = require('../network/blacklist'); const blacklist = require('../network/blacklist');
const database = require('../database/index'); const database = require('../database/index');
// This will load the blacklist and start the webserver when it's done event.on('discord:ready', () => {
blacklist.loadBlacklist().then(blacklist => { // This will load the blacklist and start the webserver when it's done
console.log('Network-Blacklist has been loaded') blacklist.loadBlacklist().then(blacklist => {
expressApp.use('/', express.static(__dirname + '/public')); console.log('Network-Blacklist has been loaded')
expressApp.use(IpFilter(blacklist)); expressApp.use('/', express.static(__dirname + '/public'));
expressApp.use(express.json()) expressApp.use(IpFilter(blacklist));
expressApp.use(express.json())
expressApp.use((err, req, res, _next) => { expressApp.use((err, req, res, _next) => {
if(req.query) { if(req.query) {
if(req.query.data && err instanceof IpDeniedError) { if(req.query.data && err instanceof IpDeniedError) {
req.body = JSON.parse(Buffer.from(req.query.data, 'base64').toString('utf-8')); req.body = JSON.parse(Buffer.from(req.query.data, 'base64').toString('utf-8'));
database.addAttempt(req.body.userId, req.body.guildId, req.headers['x-forwarded-for'] || req.socket.remoteAddress, "NETWORK_BLOCKED").then(() => { database.addAttempt(req.body.userId, req.body.guildId, req.headers['x-forwarded-for'] || req.socket.remoteAddress, "NETWORK_BLOCKED").then(() => {
res.status(401) res.status(401)
res.json({ networkBlacklisted: err.message }) res.json({ networkBlacklisted: err.message })
}) })
return; return;
}
} }
} res.status(err.status || 500)
res.status(err.status || 500) })
})
// This endpoint will return the turnstile sitekey // This endpoint will return the turnstile sitekey
expressApp.get('/turnstile/id', (req, res) => { expressApp.get('/turnstile/id', (req, res) => {
res.json({ id: turnstileSitekey }); res.json({ id: turnstileSitekey });
});
// This endpoint will verify the token from turnstile and adds the user to the database
expressApp.post('/verify', (req, res) => {
let turnstileToken = req.body.token;
let authenticationObject = req.body.data;
let internetProtocolAddress = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
let formData = new FormData();
formData.append('secret', turnstileSecret);
formData.append('response', turnstileToken);
database.ipUsedInLastDay(internetProtocolAddress).then(ipUsed => {
console.log('Verification request received, (IP, Discord-ID, Guild-ID)');
console.info(internetProtocolAddress, authenticationObject.userId, authenticationObject.guildId);
if(ipUsed) {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "IP_USED").then(() => {
console.log('IP-Address has been used in the last 24 hours');
res.json({ success: false, message: 'Die von dir genutzte IP-Adresse wurde erst kürzlich registriert. Probiere es später erneut.' });
});
} else {
database.isUserVerified(authenticationObject.userId, authenticationObject.guildId).then(userExists => {
if(!userExists) {
fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
body: formData,
method: 'POST',
}).then(response => response.json()).then(data => {
if (data.success) {
// Add the user to the database and emit the verification success event
database.addUser(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress).then(() => {
event.emit('verification:success', authenticationObject, internetProtocolAddress);
res.json({ success: true, message: 'Die Authentifizierung war erfolgreich' });
});
} else {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "CAPTCHA_FAIL").then(() => {
console.log('Verification failed');
res.json({ success: false, message: 'Das Captcha wurde nicht korrekt gelöst.' });
})
}
}).catch(error => {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "ERROR").then(() => {
console.error(error);
res.json({ success: false, message: 'Bitte probiere es später erneut.' });
})
});
} else {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "USER_VERIFIED_ALREADY").then(() => {
console.log('User already verified, potential risk');
res.json({ success: false, message: 'Das Konto wurde bereits in der Vergangenheit verifiziert. Wende dich an einen Admin um dich manuell freischalten zu lassen.' });
})
}
});
}
}); });
});
expressApp.listen(port, () => { // This endpoint will verify the token from turnstile and adds the user to the database
console.log(`Webserver is available on http://localhost:${port}`) expressApp.post('/verify', (req, res) => {
}) let turnstileToken = req.body.token;
let authenticationObject = req.body.data;
let internetProtocolAddress = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
let formData = new FormData();
formData.append('secret', turnstileSecret);
formData.append('response', turnstileToken);
database.ipUsedInLastDay(internetProtocolAddress).then(ipUsed => {
console.log('Verification request received, (IP, Discord-ID, Guild-ID)');
console.info(internetProtocolAddress, authenticationObject.userId, authenticationObject.guildId);
if(ipUsed) {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "IP_USED").then(() => {
console.log('IP-Address has been used in the last 24 hours');
res.json({ success: false, message: 'Die von dir genutzte IP-Adresse wurde erst kürzlich registriert. Probiere es später erneut.' });
});
} else {
database.isUserVerified(authenticationObject.userId, authenticationObject.guildId).then(userExists => {
if(!userExists) {
fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
body: formData,
method: 'POST',
}).then(response => response.json()).then(data => {
if (data.success) {
// Add the user to the database and emit the verification success event
database.addUser(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress).then(() => {
event.emit('verification:success', authenticationObject, internetProtocolAddress);
res.json({ success: true, message: 'Die Authentifizierung war erfolgreich' });
});
} else {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "CAPTCHA_FAIL").then(() => {
console.log('Verification failed');
res.json({ success: false, message: 'Das Captcha wurde nicht korrekt gelöst.' });
})
}
}).catch(error => {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "ERROR").then(() => {
console.error(error);
res.json({ success: false, message: 'Bitte probiere es später erneut.' });
})
});
} else {
database.addAttempt(authenticationObject.userId, authenticationObject.guildId, internetProtocolAddress, "USER_VERIFIED_ALREADY").then(() => {
console.log('User already verified, potential risk');
res.json({ success: false, message: 'Das Konto wurde bereits in der Vergangenheit verifiziert. Wende dich an einen Admin um dich manuell freischalten zu lassen.' });
})
}
});
}
});
});
expressApp.listen(port, () => {
console.log(`Webserver is available on http://localhost:${port}`)
})
});
}); });