NodeJS Websocket Discord Bot AutorisierungJavaScript

Javascript-Forum
Anonymous
 NodeJS Websocket Discord Bot Autorisierung

Post by Anonymous »

Ich habe versucht, meine Anmeldeinformationen zu verwenden, und erwartete, dass die Websocket -Verbindung meine Sitzung erkennen und mir erlauben kann, in Verbindung zu bleiben. Selbst nach einer erfolgreichen Authentifizierung sagt der Server immer noch, dass ich mich nicht angemeldet habe und mich mit dem Fehler "abgelehnt - fehlendes Token!" trenne. Ich habe auch überprüft, ob mein Zugriffstoken generiert wird, aber es scheint, dass der Server ihn in der WebSocket -Verbindung nicht richtig erkennt. Ein fehlender Token, obwohl ich mich erfolgreich anmelde. Nach dem Anmelden sagt der Server immer noch, dass ich nicht authentifiziert bin und mich trenne. In der Fehlermeldung heißt es: "Verbindung abgelehnt - fehlendes Token!" Obwohl meine Anmeldedetails und meine Zugriffs -Token gültig sind. Das Problem kann mit Token -Validierung, Sitzungsbearbeitung oder der Art und Weise, wie das Token in der WebSocket -Verbindung übergeben wird Um meine Sitzung zu erkennen und mir zu ermöglichen, in Verbindung zu bleiben. Selbst nach einer erfolgreichen Authentifizierung sagt der Server immer noch, dass ich mich nicht angemeldet habe und mich mit dem Fehler "abgelehnt - fehlendes Token!" trenne. Ich habe auch überprüft, ob mein Zugriffstoken generiert wird, aber es scheint, dass der Server ihn in der WebSocket -Verbindung nicht ordnungsgemäß erkennt. Tasten)
❯ Änderungsmodus
Kennwort ändern
Präfix ändern
Kick -Player
Ban ipadress
ungeban ipadress
Server neu starten ❌ odrzucono połączenie Websocket - Użytkownik Niezalogowany! Ken_type: ' Bearer ',
access_token:' uazocewwk7jzbza6pdshv3mmnin2 ',
expires_in: 604800,
refresh_token:' y6kpqzi2qBoql8bzqhditn9lxlxlxltycT ',
accope'
ask. Daten: {
id: '118672751674334516',
Benutzername: 'xx_ksgaming_xx',
avatar: '6d761d8ef76fdd9e799634f49d30 />:
Discriminators' 0>,
: ,
Flags: 128,
Banner: Null,
Accent_Color: Null,
global_name: '! null,
clan: null,
primär_guild: null,
mfa_enabled: false,
Locale: 'en-gb',
premium_type: 0
}
❌ odrzucono połączenie webocket - użytkownik niezalogowany! < /p>
Hier ist Code < /p>

Code: Select all

require("dotenv").config()
const WebSocket = require("ws")
const msgpack = require("msgpack-lite")
const http = require("http")
const url = require("url")
const inquirer = require("inquirer")
const fetch = require("node-fetch")
const package = require("./package.json")
const { exec } = require('child_process');
var fs = require('fs');
var path = require('path');
const express = require("express")
const session = require("express-session");
const marked = require('marked');
const sessions = {}; // Przechowywanie sesji w zależności od adresu IP
const { URLSearchParams } = require('url')
const app = express()
const SESSIONS = {}; // Przechowywanie sesji użytkowników

const CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET;
const REDIRECT_URI = process.env.DISCORD_REDIRECT_URI;

function getDiscordAuthURL() {
return `https://discord.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=identify`;
}

const httpServer = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
res.setHeader("Access-Control-Allow-Headers", "*");

const parsed = url.parse(req.url, true);

if (req.url.startsWith("/auth/login")) {
res.writeHead(302, { Location: getDiscordAuthURL() });
return res.end();
}

if (req.url.startsWith("/auth/callback")) {
handleAuthCallback(req, res);
return;
}

let filePath = parsed.pathname === "/" ? "./static/index.html" : path.join("static", path.normalize(parsed.pathname));

fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(404, { "Content-Type": "text/plain" });
return res.end("Not Found");
}
res.writeHead(200, { "Content-Type": getContentType(filePath) });
res.end(content);
});
});

async function handleAuthCallback(req, res) {
const query = url.parse(req.url, true).query;
console.log("Otrzymany query:", query);  // Logowanie przekierowania z Discorda
if (!query.code) {
res.writeHead(400, { "Content-Type": "text/plain" });
return res.end("Brak kodu autoryzacji.");
}
try {
const tokenResponse = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "authorization_code",
code: query.code,
redirect_uri: REDIRECT_URI
})
});
const tokenData = await tokenResponse.json();
console.log("Token data:", tokenData);  // Logowanie odpowiedzi z Discorda
if (!tokenData.access_token) throw new Error("Nie udało się pobrać tokena!");

const userResponse = await fetch("https://discord.com/api/users/@me", {
headers: { Authorization: `Bearer ${tokenData.access_token}` }
});
const userData = await userResponse.json();
console.log("User data:", userData);  // Logowanie danych użytkownika

const sessionId = Math.random().toString(36).substr(2, 9);
SESSIONS[sessionId] = userData.id;

res.writeHead(302, {
"Set-Cookie": `session=${sessionId}; Path=/;  HttpOnly`,
"Location": "/"
});
res.end();
} catch (err) {
console.error("Błąd autoryzacji:", err);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Błąd autoryzacji.");
}
}

function getContentType(filePath) {
const ext = path.extname(filePath);
const types = {
".js": "text/javascript",
".css": "text/css",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".mp3": "audio/mpeg",
".txt": "text/plain",
".wav": "audio/wav"
};
return types[ext] || "text/html";
}

httpServer.on("upgrade", (request, socket, head) => {
const pathname = url.parse(request.url).pathname?.replace(/\/$/, "")

// Sprawdzenie, czy ścieżka to /server
if (pathname === "/server") {
const userId = getSession(request);  // Pobierz dane sesji

// Jeśli sesja nie istnieje, połączenie jest odrzucane
if (!userId) {
console.log("❌ Odrzucono połączenie WebSocket - użytkownik niezalogowany!");
return socket.destroy();  // Zniszcz socket, jeśli nie ma sesji
}

console.log(`✅ Połączony użytkownik Discord ID: ${userId}`);

// Obsługuje upgrade WebSocket
server.handleUpgrade(request, socket, head, (ws) => {
server.emit("connection", ws, request);
});
} else {
// Jeśli ścieżka nie jest poprawna, połączenie jest odrzucane
socket.destroy();
}
});

// Funkcja do pobierania sesji z ciasteczka
function getSession(request) {
const cookieHeader = request.headers.cookie;
if (!cookieHeader) return null;

// Parse cookies
const cookies = Object.fromEntries(cookieHeader.split("; ").map(c => c.split("=")));
return SESSIONS[cookies.session] || null;  // Zwraca sesję, jeśli istnieje
}

httpServer.listen(PORT, () => {
setupServer()
commandStart()
})

const banIps = './data/BannedIps.json';

async function commandStart() {
console.clear();
console.log(`Listening at http://localhost:${PORT}\n`);
const command = await inquirer.prompt({
name: "command",
type: "list",
message: "Custom Command",
choices: ["Change Mode", "Change Password", "Change Prefix", "Kick Player", "Ban IPAdress", "Unban IPAdress", "Restart Server"]
});

if (command.command === "Change Mode") {
const mode = await inquirer.prompt({
name: "mode",
type: "list",
message: "Select mode",
choices: ["NORMAL", "SANDBOX", "ARENA", "HOCKEY"]
});
const modeType = [["HOCKEY"], ["SANDBOX", "NORMAL"], ["ARENA"]];
function areInSameGroup(arg1, arg2, arg3) {
for (const group of modeType) {
if (group.includes(arg1) && group.includes(arg2) &&  group.includes(arg3)) {
return true;
}
}
return false;
}

if (areInSameGroup(MODE, mode.mode)) {
MODE = mode.mode;
} else {
const restart = await inquirer.prompt({
name: "restart",
type: "confirm",
message: "Are you sure you want to restart server?"
});
if (restart.restart) {
MODE = mode.mode;
setupServer();
}
}
} else if (command.command === "Change Password") {
const password = await inquirer.prompt({
name: "password",
type: "input",
message: "Input password:"
});
PASSWORD = password.password;
} else if (command.command === "Change Prefix") {
const prefix = await inquirer.prompt({
name: "prefix",
type: "list",
message: "Select prefix",
choices: ["!", "?", "/", "\\", "`", "'", '"', ":", "|", ";", "", ",", ".", "~"]
});
PREFIX = prefix.prefix;
} else if (command.command === "Kick Player") {
const sid = await inquirer.prompt({
name: "sid",
type: "input",
message: "Input player sid:"
});
const sidNumber = Number(sid.sid);
if (!isNaN(sidNumber)) {
for (let i = 0; i < players.length; i++) {
let tmpPlayer = players[i];
if (tmpPlayer.sid === sidNumber) {
connection[tmpPlayer.id].close();
break;
}
}
}
} else if (command.command === "Restart Server") {
const restart = await inquirer.prompt({
name: "restart",
type: "confirm",
message: "Are you sure you want to restart server?"
});
if (restart.restart) {
setupServer();
}
} else if (command.command === "Ban IP") {
const ipInput = await inquirer.prompt({
name: "ip",
type: "input",
message: "Enter IP address to ban:"
});
const bannedIp = ipInput.ip;

if (!bannedIp) {
console.log("Invalid IP address.");
} else {
let bannedIps = [];
if (fs.existsSync(banIps)) {
const fileData = fs.readFileSync(banIps, 'utf8');
try {
bannedIps = JSON.parse(fileData);
} catch (error) {
console.log("Error parsing BannedIps.json, resetting file.");
}
}

if (!bannedIps.includes(bannedIp)) {
bannedIps.push(bannedIp);
fs.writeFileSync(banIps, JSON.stringify(bannedIps, null, 2));
console.log(`IP ${bannedIp} has been banned.`);
} else {
console.log("This IP is already banned.");
}

}
} else if (command.command === "Unban IPAdress") {
const ipInput = await inquirer.prompt({
name: "ip",
type: "input",
message: "Enter IP address to unban:"
});
const unbanIp = ipInput.ip;

if (!unbanIp) {
console.log("Invalid IP address.");
} else {
let bannedIps = [];
if (fs.existsSync(banIps)) {
bannedIps = JSON.parse(fs.readFileSync(banIps, 'utf8'));
}

if (bannedIps.includes(unbanIp)) {
bannedIps = bannedIps.filter(ip =>  ip !== unbanIp);
fs.writeFileSync(banIps, JSON.stringify(bannedIps, null, 2));
console.log(`IP ${unbanIp} has been unbanned.`);
} else {
console.log("This IP is not in the banned list.");
}
}
}
commandStart();
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post