I tried logging in using my credentials, and I expected the WebSocket connection to recognize my session and allow me to stay connected. However, even after successful authentication, the server still says I am not logged in and disconnects me with the error “Connection rejected – Missing token!”. I also checked that my access token is being generated, but it seems like the server isn’t recognizing it properly in the WebSocket connection.
It looks like my WebSocket connection is being rejected due to a missing token, even though I successfully log in. After logging in, the server still says I’m not authenticated and disconnects me. The error message states: “Connection rejected – Missing token!” even though my login details and access token are valid. The issue might be related to token validation, session handling, or the way the token is being passed in the WebSocket connection.
I tried logging in using my credentials, and I expected the WebSocket connection to recognize my session and allow me to stay connected. However, even after successful authentication, the server still says I am not logged in and disconnects me with the error “Connection rejected – Missing token!”. I also checked that my access token is being generated, but it seems like the server isn’t recognizing it properly in the WebSocket connection.
error log
Custom Command (Use arrow keys)
❯ Change Mode
Change Password
Change Prefix
Kick Player
Ban IPAdress
Unban IPAdress
Restart Server ❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!
❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!
Otrzymany query: [Object: null prototype] { code: ‘8w2GBb2puGgcoJ07ex4dwuV3GmN9zs’ }
Token data: {
token_type: ‘Bearer’,
access_token: ‘UazoCEWwk7JZBebza6PDshV3mMnIn2’,
expires_in: 604800,
refresh_token: ‘y6kpQZi2QBoqL8BZQhDITN9lxLTYcT’,
scope: ‘identify’
}
User data: {
id: ‘1186727516774334516’,
username: ‘xx_ksgaming_xx’,
avatar: ‘6d761d8ef76fdd9e799634f49d3034cd’,
discriminator: ‘0’,
public_flags: 128,
flags: 128,
banner: null,
accent_color: null,
global_name: ‘!KoKsus’,
avatar_decoration_data: null,
banner_color: null,
clan: null,
primary_guild: null,
mfa_enabled: false,
locale: ‘en-GB’,
premium_type: 0
}
❌ Odrzucono połączenie WebSocket – użytkownik niezalogowany!
here is code
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();
}