Token Maneger #250
@ -21,9 +21,9 @@ describe("Small functions", () => {
|
||||
BdsCore.BdsSettings.UpdatePlatform("dragonfly");
|
||||
done();
|
||||
});
|
||||
it("Register And Delete API Token", function (done) {
|
||||
const Token = BdsCore.BdsManegerAPI.token_register();
|
||||
BdsCore.BdsManegerAPI.delete_token(Token);
|
||||
it("Register And Delete Token", function (done) {
|
||||
const Token = BdsCore.BdsToken.CreateToken();
|
||||
BdsCore.BdsToken.DeleteToken(Token.Token);
|
||||
done();
|
||||
});
|
||||
it("Get Server Config", function (done) {
|
||||
|
@ -9,12 +9,12 @@ const { PlatformVersionsV2 } = require("../src/BdsServersDownload");
|
||||
|
||||
// Get Current Tokens and Show in the console
|
||||
function ShowToken() {
|
||||
const TokenFilePath = BdsCore.BdsManegerAPI.TokensFilePath;
|
||||
const TokenFilePath = BdsCore.BdsToken.TokenFile;
|
||||
let Tokens = 1
|
||||
if (fs.existsSync(TokenFilePath)) {
|
||||
[...JSON.parse(fs.readFileSync(TokenFilePath, "utf8"))].slice(0, 5).forEach(token => {console.log(Tokens+":", "Bds API Token:", token.token); Tokens++});
|
||||
[...JSON.parse(fs.readFileSync(TokenFilePath, "utf8"))].slice(0, 5).forEach(token => {console.log(Tokens+":", "Bds API Token:", token.Token); Tokens++});
|
||||
} else {
|
||||
console.log(Tokens+":", "Bds API Token:", BdsCore.BdsManegerAPI.token_register());
|
||||
console.log(Tokens+":", "Bds API Token:", (BdsCore.BdsToken.CreateToken()).Token);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,11 +1,19 @@
|
||||
/**
|
||||
* Bds Maneger Telegram Bot v13.1.1
|
||||
*/
|
||||
const { version, BdsSettings, BdsToken, BdsSystemInfo, BdsManegerServer } = require("../../index");
|
||||
const { Telegraf } = require("telegraf");
|
||||
const os = require("os");
|
||||
const fs = require("fs");
|
||||
const { Telegraf, Markup } = require("telegraf");
|
||||
const bds = require("../../index");
|
||||
const { GetPlatform, GetPaths, GetTelegramToken, UpdateTelegramToken } = require("../../src/lib/BdsSettings");
|
||||
const { GetKernel, arch, system } = require("../../src/lib/BdsSystemInfo");
|
||||
const { Detect } = require("../../src/CheckKill");
|
||||
const { CheckTelegramUser } = require("../../src/UsersAndtokenChecks");
|
||||
const BdsInfo = require("../../BdsManegerInfo.json");
|
||||
const path = require("path");
|
||||
|
||||
// Set Telegram Bot
|
||||
if (process.env.BDS_DOCKER_IMAGE === "true") {
|
||||
if (process.env.TelegramToken) BdsSettings.UpdateTelegramToken(process.env.TelegramToken);
|
||||
}
|
||||
const TelegramToken = BdsSettings.GetTelegramToken();
|
||||
if (!TelegramToken) throw new Error("Add Telegram Token");
|
||||
const bot = new Telegraf(TelegramToken);
|
||||
|
||||
// Bot Start And Help messages
|
||||
const HelpAndStart = [
|
||||
@ -14,303 +22,111 @@ const HelpAndStart = [
|
||||
"We are changing some things but everything is working!!",
|
||||
"Options:",
|
||||
" /start or /help: This message!",
|
||||
" /basic",
|
||||
" start, stop, backup",
|
||||
" /live_log",
|
||||
" enabler, disabler",
|
||||
" /live_log",
|
||||
" /download",
|
||||
" Version",
|
||||
" ",
|
||||
];
|
||||
bot.start((ctx) => ctx.reply(HelpAndStart.join("\n")));
|
||||
bot.help((ctx) => ctx.reply(HelpAndStart.join("\n")));
|
||||
|
||||
// Set Telegram Bot
|
||||
const TelegramToken = GetTelegramToken();
|
||||
if (!TelegramToken) throw new Error("Add Telegram Token");
|
||||
const bot = new Telegraf(TelegramToken);
|
||||
// Info
|
||||
bot.command("info", async (ctx) => {
|
||||
const info = await BdsSystemInfo.SystemInfo();
|
||||
const reply = [
|
||||
`Bds Maneger Core Version: ${version}`,
|
||||
"Available Servers (Platfroms):",
|
||||
"",
|
||||
`Bedrock: ${info.valid_platform.bedrock ? "Avaible" : "Not Avaible"}`,
|
||||
`Java: ${info.valid_platform.java ? "Avaible" : "Not Avaible"}`,
|
||||
`Pocketmine-MP: ${info.valid_platform.pocketmine ? "Avaible" : "Not Avaible"}`,
|
||||
`Spigot: ${info.valid_platform.java ? "Avaible" : "Not Avaible"}`,
|
||||
`Dragonfly: ${info.valid_platform.dragonfly ? "Avaible" : "Not Avaible"}`,
|
||||
];
|
||||
return ctx.reply(reply.join("\n"));
|
||||
});
|
||||
|
||||
// Start and Help Command
|
||||
bot.start((ctx)=>ctx.reply(HelpAndStart.join("\n")));
|
||||
bot.help((ctx)=>ctx.reply(HelpAndStart.join("\n")));
|
||||
// Setup User Token
|
||||
bot.command("token", async (ctx) => {
|
||||
const AllTokens = BdsToken.GetAllTokens();
|
||||
const TextToken = ctx.message.text.replace(/\/token\s+/, "");
|
||||
if (AllTokens.length > 0) {
|
||||
if (!TextToken) return ctx.reply("Please, add your token");
|
||||
if (!BdsToken.CheckToken(TextToken)) return ctx.reply("Invalid Token");
|
||||
BdsToken.UpdateTelegramID(TextToken, ctx.message.from.id);
|
||||
return ctx.reply(`Token Associed to your account (You id: ${ctx.message.from.id})`);
|
||||
} else {
|
||||
ctx.reply("Please wait, we are setting up your fist token");
|
||||
const FistToken = BdsToken.CreateToken("admin", ctx.message.from.id);
|
||||
return ctx.reply(`Your fist token is: ${FistToken.Token}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Send Command to Servers
|
||||
bot.command("command", async (ctx) => {
|
||||
const user_id = ctx.message.from.id;
|
||||
if (ctx.message.from.is_bot) return ctx.reply("You can't send commands to servers");
|
||||
const command = ctx.message.text.replace(/^\/command\s+/i, "");
|
||||
if (!(BdsToken.CheckTelegramID(user_id))) return ctx.reply("You are not allowed to send commands to servers or is not setup you Token");
|
||||
const __Current_Sessions__ = BdsManegerServer.GetSessions();
|
||||
const SessionsArray = Object.keys(__Current_Sessions__)
|
||||
if (SessionsArray.length > 0) SessionsArray.forEach((key) => {
|
||||
__Current_Sessions__[key].SendCommand(command);
|
||||
}); else return ctx.reply("No Servers Running");
|
||||
});
|
||||
|
||||
// Enable or Disable Player on connect
|
||||
let ReplyList = [];
|
||||
const TmpReplyList = path.join(os.tmpdir(), "ReplyList.json");
|
||||
const WriteTmpReplyList = () => fs.writeFileSync(TmpReplyList, JSON.stringify(ReplyList));
|
||||
if (fs.existsSync(TmpReplyList)) ReplyList = JSON.parse(fs.readFileSync(TmpReplyList));
|
||||
BdsManegerServer.RegisterPlayerGlobalyCallbacks((Actions) => {
|
||||
const MountText = [];
|
||||
Actions.forEach((action) => {
|
||||
MountText.push(`${action.Player} ${action.Action}`);
|
||||
});
|
||||
ReplyList.forEach((reply) => {
|
||||
return bot.telegram.sendMessage(reply.id, MountText.join("\n"));
|
||||
});
|
||||
});
|
||||
|
||||
// User
|
||||
bot.command("player", ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const Server = global.ServerExec;
|
||||
const CtxOption = ctx.message.text.replace("/player", "").trim();
|
||||
const CtxContext = CtxOption.replace(/^kick|^deop|^ban|^op/, "").trim();
|
||||
if (CtxOption) {
|
||||
const Players = CtxContext.split(/, |,/gi).filter(a => a.trim());
|
||||
console.log(Players);
|
||||
if (/kick/.test(CtxOption)){
|
||||
if (Players.length >= 1) {
|
||||
Players.forEach(Player => {
|
||||
Server.kick(Player);
|
||||
ctx.reply(`${Player} was kicked`);
|
||||
});
|
||||
} else ctx.reply("and the Players?")
|
||||
}
|
||||
else if (/deop/.test(CtxOption)){
|
||||
if (Players.length >= 1) {
|
||||
Players.forEach(Player => {
|
||||
Server.deop(Player);
|
||||
ctx.reply(`${Player} was deopped`);
|
||||
});
|
||||
} else ctx.reply("and the Players?")
|
||||
}
|
||||
else if (/ban/.test(CtxOption)){
|
||||
if (Players.length >= 1) {
|
||||
Players.forEach(Player => {
|
||||
Server.ban(Player);
|
||||
ctx.reply(`${Player} was banned`);
|
||||
});
|
||||
} else ctx.reply("and the Players?")
|
||||
}
|
||||
else if (/op/.test(CtxOption)){
|
||||
if (Players.length >= 1) {
|
||||
Players.forEach(Player => {
|
||||
Server.op(Player);
|
||||
ctx.reply(`${Player} was opped`);
|
||||
});
|
||||
} else ctx.reply("and the Players?")
|
||||
}
|
||||
else if (/list/.test(CtxOption)){
|
||||
const Player_Json_path = GetPaths("player");
|
||||
let Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[GetPlatform()];
|
||||
const new_players = {};
|
||||
Players_Json.forEach(Player => {
|
||||
console.log(Player);
|
||||
if (new_players[Player.Player]) {
|
||||
new_players[Player.Player].push([`Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n"));
|
||||
} else {
|
||||
new_players[Player.Player] = [
|
||||
[`Player: ${Player.Player}`, `Action: ${Player.Action}`, `Date: ${Player.Date}`].join("\n")
|
||||
]
|
||||
}
|
||||
});
|
||||
console.log(new_players);
|
||||
Object.getOwnPropertyNames(new_players).forEach(Player_Array => {
|
||||
let Length = Math.abs(new_players[Player_Array].length - 5);
|
||||
let Player = new_players[Player_Array].slice(0, Length).join("\n")
|
||||
ctx.reply(Player);
|
||||
});
|
||||
}
|
||||
else ctx.reply("Invalid option")
|
||||
const ChatID = ctx.chat.id;
|
||||
if (ReplyList.find(User => User.id === ChatID)) {
|
||||
ReplyList = ReplyList.filter(User => User.id !== ChatID);
|
||||
ctx.reply("Player on connect disabled");
|
||||
} else {
|
||||
const ReplyOption = Markup.keyboard([
|
||||
"/player kick",
|
||||
"/player deop",
|
||||
"/player ban",
|
||||
"/player op",
|
||||
"/player list",
|
||||
]).oneTime().resize();
|
||||
ctx.reply("Player Options:", ReplyOption);
|
||||
ReplyList.push({ id: ChatID });
|
||||
ctx.reply("Player on connect enabled");
|
||||
}
|
||||
WriteTmpReplyList();
|
||||
});
|
||||
|
||||
// Basic server
|
||||
bot.command("basic", async ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const text = ctx.message.text.replace("/basic", "").trim();
|
||||
if (text) {
|
||||
// Start Server
|
||||
if (/start/.test(text)) {
|
||||
if (Detect()) ctx.reply("Stop Server");
|
||||
else {
|
||||
try {
|
||||
const Server = bds.start();
|
||||
Server.log(function (data){
|
||||
for (let stx of global.LiveLog) stx.reply(data);
|
||||
});
|
||||
global.ServerExec = Server;
|
||||
return ctx.reply("Server Started")
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
ctx.reply("We couldn't start the server")
|
||||
ctx.reply(err.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
// Stop Server
|
||||
else if (/stop/.test(text)) {
|
||||
if (Detect()) {
|
||||
try {
|
||||
bds.stop()
|
||||
ctx.reply("Stopping your server")
|
||||
} catch (err) {
|
||||
ctx.reply("We had an error for your server");
|
||||
ctx.reply(err.toString());
|
||||
}
|
||||
} else ctx.reply("Your server is stopped")
|
||||
}
|
||||
// Backup
|
||||
else if (/backup/.test(text)) {
|
||||
const Backup = bds.backup();
|
||||
ctx.replyWithDocument({
|
||||
source: Backup.Buffer,
|
||||
filename: Backup.file_name,
|
||||
})
|
||||
}
|
||||
// Invalid option
|
||||
else return ctx.reply("Invalid option, they are just: start, stop")
|
||||
} else {
|
||||
await ctx.deleteMessage();
|
||||
const Options = Markup.keyboard([
|
||||
"/basic start",
|
||||
"/basic stop",
|
||||
"/basic backup",
|
||||
]).oneTime().resize();
|
||||
ctx.reply("Basic Options", Options);
|
||||
}
|
||||
});
|
||||
|
||||
// Select Platform
|
||||
bot.command("platform", async ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const text = ctx.message.text.replace("/platform", "").trim();
|
||||
if (text) {
|
||||
try {
|
||||
bds.BdsSettigs.UpdatePlatform(text);
|
||||
return ctx.reply(`Platform update to ${text}`)
|
||||
} catch (err) {
|
||||
ctx.reply("We were unable to change the platform")
|
||||
return ctx.reply(err.toString())
|
||||
}
|
||||
} else {
|
||||
await ctx.deleteMessage();
|
||||
const Keyboard = Markup.keyboard([
|
||||
"/platform bedrock",
|
||||
"/platform java",
|
||||
"/platform pocketmine",
|
||||
"/platform jsprismarine"
|
||||
]).oneTime().resize();
|
||||
ctx.reply("Select Platform", Keyboard)
|
||||
}
|
||||
});
|
||||
|
||||
// Download Server
|
||||
bot.command("download", async ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const version = ctx.message.text.replace(/\/download|[a-zA-Z]/gi, "").trim();
|
||||
if (version) {
|
||||
await bds.download(version, true);
|
||||
ctx.reply(`Sucess install ${GetPlatform()} with version ${version}`);
|
||||
} else {
|
||||
await ctx.deleteMessage();
|
||||
const KeyboardVersion = Markup.keyboard(Object.getOwnPropertyNames((await (await fetch(BdsInfo.Fetchs.servers)).json())[GetPlatform()]).map(version => {
|
||||
return {
|
||||
text: `/download ${version}`
|
||||
}
|
||||
})).oneTime().resize();
|
||||
ctx.reply("Select Version to Install", KeyboardVersion);
|
||||
}
|
||||
});
|
||||
|
||||
// Command
|
||||
bot.command("command", async ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const text = ctx.message.text.replace("/command", "").trim();
|
||||
if (!(Detect())) return ctx.reply("Your server is stopped");
|
||||
if (text) {
|
||||
try {
|
||||
global.ServerExec.command(text);
|
||||
} catch (err) {
|
||||
ctx.reply("We couldn't execute the command");
|
||||
ctx.reply(`${err}`);
|
||||
}
|
||||
} else {
|
||||
await ctx.deleteMessage();
|
||||
return ctx.reply("/command <command>");
|
||||
}
|
||||
});
|
||||
|
||||
// Send Info
|
||||
bot.command("info", ctx => {
|
||||
const config = bds.get_config();
|
||||
const InfoRes = [
|
||||
`Bds Maneger core version: ${bds.package_json.version}`,
|
||||
`Kernel: ${GetKernel()}`,
|
||||
`Arch: ${arch}`,
|
||||
`System: ${system}`,
|
||||
`Platform: ${GetPlatform()}`,
|
||||
`World_name: ${config.world}`,
|
||||
`Running: ${bds.detect()}`,
|
||||
`Port_V4: ${config.portv4}`,
|
||||
`Port_V6: ${config.portv6}`,
|
||||
`Max_players: ${config.players}`,
|
||||
`Whitelist: ${config.whitelist}`,
|
||||
]
|
||||
ctx.reply(InfoRes.join("\n\n"));
|
||||
});
|
||||
|
||||
// Live Log User
|
||||
global.LiveLog = [];
|
||||
bot.command("live_log", async ctx => {
|
||||
// Check admin Username
|
||||
if (!(CheckTelegramUser(ctx.from.username))) return ctx.reply("you are not an administrator");
|
||||
|
||||
const option = ctx.message.text.replace("/live_log", "").trim();
|
||||
if (option) {
|
||||
if (/enable/.test(option)) {
|
||||
global.LiveLog.push(ctx);
|
||||
return ctx.reply("Sucess");
|
||||
} else if (/disable/.test(option)) {
|
||||
// ctx.from.id
|
||||
for (let ctx_Logs in global.LiveLog) {
|
||||
if (global.LiveLog[ctx_Logs].from.id === ctx.from.id) {
|
||||
delete global.LiveLog[ctx_Logs];
|
||||
global.LiveLog = global.LiveLog.filter(a=>a);
|
||||
return ctx.reply("Ok");
|
||||
}
|
||||
}
|
||||
return ctx.reply("You are not in the list");
|
||||
}
|
||||
}
|
||||
await ctx.deleteMessage();
|
||||
const ReplyOption = Markup.keyboard([
|
||||
"/live_log enable",
|
||||
"/live_log disable",
|
||||
]).oneTime().resize();
|
||||
ctx.reply("Enable/Disabled?", ReplyOption);
|
||||
});
|
||||
|
||||
// text
|
||||
bot.on("text", ctx => {
|
||||
console.log(ctx.message.text);
|
||||
if (!(/\/.*/gi.test(ctx.message.text))) global.ServerExec.command(`say ${ctx.message.text}`)
|
||||
});
|
||||
|
||||
// catch
|
||||
// Get Catch
|
||||
bot.catch(console.log);
|
||||
|
||||
module.exports.description = "Start Bot of Telegram";
|
||||
module.exports.Args = [
|
||||
{
|
||||
arg: "t",
|
||||
main: async () => bot.launch()
|
||||
main: async () => {
|
||||
console.log("Start Telegram Bot");
|
||||
return bot.launch()
|
||||
}
|
||||
},
|
||||
{
|
||||
arg: "telegram",
|
||||
main: async () => bot.launch()
|
||||
},
|
||||
{
|
||||
arg: "register_telegram_token",
|
||||
main: async (Token = "") => {
|
||||
if (!(Token && typeof Token === "string")) throw new Error("Token is not a string");
|
||||
return UpdateTelegramToken(Token);
|
||||
main: async () => {
|
||||
console.log("Start Telegram Bot");
|
||||
return bot.launch()
|
||||
}
|
||||
}
|
||||
];
|
||||
module.exports.help = [
|
||||
" -t, --telegram Start Telegram Bot"
|
||||
];
|
||||
module.exports.DockerImage = {
|
||||
postStart: async () => {
|
||||
if (BdsSettings.GetTelegramToken()) {
|
||||
console.log("Start Telegram Bot");
|
||||
return bot.launch();
|
||||
}
|
||||
}
|
||||
};
|
4
index.js
4
index.js
@ -14,6 +14,10 @@ if (process.env.ShowLoadTime) console.time("Bds Maneger Core: Settings");
|
||||
module.exports.BdsSettings = require("./src/lib/BdsSettings");
|
||||
if (process.env.ShowLoadTime) console.timeEnd("Bds Maneger Core: Settings");
|
||||
|
||||
if (process.env.ShowLoadTime) console.time("Bds Maneger Core: Token");
|
||||
module.exports.BdsToken = require("./src/lib/Token");
|
||||
if (process.env.ShowLoadTime) console.timeEnd("Bds Maneger Core: Token");
|
||||
|
||||
if (process.env.ShowLoadTime) console.time("Bds Maneger Core: System Info");
|
||||
module.exports.BdsSystemInfo = require("./src/lib/BdsSystemInfo");
|
||||
if (process.env.ShowLoadTime) console.timeEnd("Bds Maneger Core: System Info");
|
||||
|
@ -51,7 +51,7 @@ function CreateBackup() {
|
||||
}
|
||||
|
||||
// The Bds Maneger Core Backup
|
||||
for (let index of ["BdsConfig.yaml", "bds_tokens.json"]) if (fs.existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index));
|
||||
for (let index of ["BdsConfig.yaml", "BdsToken.json"]) if (fs.existsSync(join(bds_dir, index))) zip.addLocalFile(join(bds_dir, index));
|
||||
|
||||
for (let index of Object.getOwnPropertyNames(GetPaths("all")).filter(path => !/servers|backups/.test(path)).map(name => GetPaths(name))) {
|
||||
if (fs.existsSync(index)) {
|
||||
|
@ -12,6 +12,11 @@ const BasicCommands = require("./ManegerServer/BasicCommands");
|
||||
const ServerSessions = {};
|
||||
module.exports.GetSessions = () => ServerSessions;
|
||||
|
||||
const PlayersCallbacks = [];
|
||||
module.exports.RegisterPlayerGlobalyCallbacks = function RegisterPlayerGlobalyCallbacks(callback){
|
||||
PlayersCallbacks.push(callback);
|
||||
}
|
||||
|
||||
module.exports.StartServer = function start() {
|
||||
const commandExists = require("../src/lib/commandExist");
|
||||
const io = require("./api").SocketIO;
|
||||
@ -218,10 +223,13 @@ module.exports.StartServer = function start() {
|
||||
UUID: returnFuntion.uuid,
|
||||
data: data
|
||||
});
|
||||
PlayerJson.CreatePlayerJson(data, Actions => {
|
||||
PlayerJson.CreatePlayerJson(data, async Actions => {
|
||||
if (Actions.length === 0) return;
|
||||
PlayerJson.UpdateUserJSON(Actions);
|
||||
io.emit("PlayerAction", Actions);
|
||||
PlayersCallbacks.forEach(async callback => {
|
||||
if (typeof callback === "function") return callback(Actions);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -231,22 +239,6 @@ module.exports.StartServer = function start() {
|
||||
return returnFuntion;
|
||||
}
|
||||
|
||||
// Search player in JSON
|
||||
module.exports.Player_Search = function Player_Search(player = "dontSteve") {
|
||||
const Player_Json_path = BdsSettings.GetPaths("player"), Current_platorm = BdsSettings.GetPlatform();
|
||||
const Players_Json = JSON.parse(fs.readFileSync(Player_Json_path, "utf8"))[Current_platorm]
|
||||
for (let Player of Players_Json) {
|
||||
if (Player.Player === player.trim()) return Player;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
module.exports.GetFistSession = function GetFistSession(){
|
||||
const ArraySessions = Object.getOwnPropertyNames(ServerSessions)
|
||||
if (ArraySessions.length === 0) throw "Start Server";
|
||||
return ServerSessions[0]
|
||||
}
|
||||
|
||||
module.exports.CronBackups = BdsSettings.GetCronBackup().map(Crron => {
|
||||
const Cloud_Backup = {
|
||||
Azure: require("./clouds/Azure").Uploadbackups,
|
||||
|
@ -9,13 +9,12 @@ function CreatePlayerJson(data = "", callback = (d = [{Player: "", Action: "conn
|
||||
// "[INFO] Player disconnected: Sirherobrine, xuid: 2535413418839840",
|
||||
const BedrockMap = data.split(/\n|\r/gi).map(line => {
|
||||
if (line.includes("connected")) {
|
||||
let SplitLine = line.replace(/\[.+\]\s+Player/gi, "").trim().split(/\s+/gi);
|
||||
let Actions = "";
|
||||
if (/^disconnected/.test(SplitLine[0].trim())) Actions = "disconnect"; else Actions = "connect";
|
||||
if (/^disconnected/.test(line)) Actions = "disconnect"; else Actions = "connect";
|
||||
|
||||
// Object Map
|
||||
const ObjectReturn = {
|
||||
Player: line.replace(/^.*connected:/gi, "").replace(/, xuid:.*$/gi, "").trim(),
|
||||
Player: line.replace(/^.*connected:|,.*xuid:.*$/gi, "").trim(),
|
||||
Action: Actions,
|
||||
Platform: Current_platorm,
|
||||
xuid: line.replace(/^.*,.*xuid:/gi, "").trim(),
|
||||
|
@ -1,43 +0,0 @@
|
||||
const { bds_dir, GetServerBan, GetTelegramAdmins, GetPlatform, GetPaths } = require("../src/lib/BdsSettings");
|
||||
const { existsSync, readFileSync } = require("fs")
|
||||
const { join } = require("path")
|
||||
|
||||
function CheckTelegramUser(admin_name){
|
||||
for(let admin_check of GetTelegramAdmins()){
|
||||
if (admin_name === admin_check || admin_check === "all_users") return true;
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function CheckPlayer(player = "null"){
|
||||
const json = require(GetPaths("player"))[GetPlatform()];
|
||||
if (json[player]) return true; else return false
|
||||
}
|
||||
|
||||
function token_verify(token){
|
||||
const path_tokens = join(bds_dir, "bds_tokens.json");
|
||||
if (existsSync(path_tokens)) var tokens = JSON.parse(readFileSync(path_tokens, "utf8")); else return false
|
||||
for (let token_verify of tokens) {
|
||||
const element = token_verify.token
|
||||
if (element === token) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function CheckBan(player){
|
||||
var players = GetServerBan();
|
||||
for(let check_ in players){
|
||||
const admin_check = players[check_]
|
||||
if (player === admin_check.username) {
|
||||
if (admin_check[GetPlatform()]) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CheckTelegramUser,
|
||||
CheckPlayer,
|
||||
CheckBan,
|
||||
token_verify
|
||||
}
|
80
src/api.js
80
src/api.js
@ -1,13 +1,11 @@
|
||||
// Node Modules
|
||||
const os = require("os");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { randomUUID } = require("crypto");
|
||||
// Bds Maneger Core
|
||||
const BdsManegerCore = require("../index");
|
||||
const BdsSystemInfo = require("../src/lib/BdsSystemInfo");
|
||||
const BdsChecks = require("./UsersAndtokenChecks");
|
||||
const BdsSettings = require("../src/lib/BdsSettings");
|
||||
const TokenManeger = require("./lib/Token");
|
||||
|
||||
// Init Express
|
||||
const express = require("express");
|
||||
@ -38,7 +36,7 @@ io.use(function (socket, next) {
|
||||
const { headers, query } = socket.handshake;
|
||||
const Token = headers["AuthorizationToken"] || query["token"] || query["Token"];
|
||||
if (Token) {
|
||||
if (BdsChecks.token_verify(Token)) {
|
||||
if (TokenManeger.CheckToken(Token, "all")) {
|
||||
socket.token = Token;
|
||||
return next();
|
||||
}
|
||||
@ -57,46 +55,51 @@ app.all(["/v2", "/v2/*"], ({res}) => res.status(401).json({
|
||||
|
||||
// Check Token
|
||||
function CheckToken (req, res, next) {
|
||||
if (req.method === "GET") {
|
||||
if (req.headers["AuthorizationToken"]) {
|
||||
if (TokenManeger.CheckToken(req.headers["AuthorizationToken"], "all")) {
|
||||
req.token = req.headers["AuthorizationToken"];
|
||||
return next();
|
||||
}
|
||||
} else if (req.method === "GET") {
|
||||
if (req.query.token) {
|
||||
if (BdsChecks.token_verify(req.query.token)) {
|
||||
if (TokenManeger.CheckToken(req.query.token, "all")) {
|
||||
req.token = req.query.token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.headers.token) {
|
||||
if (BdsChecks.token_verify(req.headers.token)) {
|
||||
if (TokenManeger.CheckToken(req.headers.token, "all")) {
|
||||
req.token = req.headers.token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.query.Token) {
|
||||
if (BdsChecks.token_verify(req.query.Token)) {
|
||||
if (TokenManeger.CheckToken(req.query.Token, "all")) {
|
||||
req.token = req.query.Token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.headers.Token) {
|
||||
if (BdsChecks.token_verify(req.headers.Token)) {
|
||||
if (TokenManeger.CheckToken(req.headers.Token, "all")) {
|
||||
req.token = req.headers.token;
|
||||
return next();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (req.body.token) {
|
||||
if (BdsChecks.token_verify(req.body.token)) {
|
||||
if (TokenManeger.CheckToken(req.body.token, "all")) {
|
||||
req.token = req.body.token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.headers.token) {
|
||||
if (BdsChecks.token_verify(req.headers.token)) {
|
||||
if (TokenManeger.CheckToken(req.headers.token, "all")) {
|
||||
req.token = req.headers.token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.body.Token) {
|
||||
if (BdsChecks.token_verify(req.body.Token)) {
|
||||
if (TokenManeger.CheckToken(req.body.Token, "all")) {
|
||||
req.token = req.body.Token;
|
||||
return next();
|
||||
}
|
||||
} else if (req.headers.Token) {
|
||||
if (BdsChecks.token_verify(req.headers.Token)) {
|
||||
if (TokenManeger.CheckToken(req.headers.Token, "all")) {
|
||||
req.token = req.headers.Token;
|
||||
return next();
|
||||
}
|
||||
@ -432,58 +435,7 @@ function API(port_api = 1932, callback = port => {console.log("Bds Maneger Core
|
||||
return port;
|
||||
}
|
||||
|
||||
// Bds Maneger Core API token Register
|
||||
const path_tokens = path.join(BdsSettings.bds_dir, "bds_tokens.json");
|
||||
/**
|
||||
*
|
||||
* Register new Token to API and more features in the Bds Maneger Core.
|
||||
*
|
||||
* @param {Array} Admin_Scoper - Array of Admin Scoper (Soon will be implemented)
|
||||
* @returns {String} Token - Token of the API
|
||||
*/
|
||||
function token_register(Admin_Scoper = ["web_admin", "admin"]) {
|
||||
Admin_Scoper = Array.from(Admin_Scoper).filter(scoper => /admin/.test(scoper));
|
||||
let tokens = [];
|
||||
if (fs.existsSync(path_tokens)) tokens = JSON.parse(fs.readFileSync(path_tokens, "utf8"));
|
||||
// Get UUID
|
||||
const getBdsUUId = randomUUID().split("-");
|
||||
const bdsuid = "bds_" + (getBdsUUId[0]+getBdsUUId[2].slice(0, 15));
|
||||
// Save BdsUUID
|
||||
tokens.push({
|
||||
token: bdsuid,
|
||||
date: new Date(),
|
||||
scopers: Admin_Scoper
|
||||
});
|
||||
fs.writeFileSync(path_tokens, JSON.stringify(tokens, null, 4), "utf8");
|
||||
return bdsuid;
|
||||
}
|
||||
|
||||
// Bds Maneger Core API Delete token
|
||||
/**
|
||||
*
|
||||
* Delete Token of the API
|
||||
*
|
||||
* @param {String} Token - Token of the API to delete
|
||||
* @returns {Boolean} - True if the token is deleted
|
||||
*/
|
||||
function delete_token(Token = "") {
|
||||
if (!Token) return false;
|
||||
if (typeof Token !== "string") return false;
|
||||
let tokens = [];
|
||||
if (fs.existsSync(path_tokens)) tokens = JSON.parse(fs.readFileSync(path_tokens, "utf8"));
|
||||
if (tokens.filter(token => token.token === Token).length > 0) {
|
||||
fs.writeFileSync(path_tokens, JSON.stringify(tokens, null, 4), "utf8");
|
||||
return true;
|
||||
} else return false;
|
||||
}
|
||||
|
||||
// Check Exists Tokens Files
|
||||
if (!(fs.existsSync(path_tokens))) token_register();
|
||||
|
||||
module.exports.api = API;
|
||||
module.exports.token_register = token_register;
|
||||
module.exports.delete_token = delete_token;
|
||||
module.exports.TokensFilePath = path_tokens;
|
||||
module.exports.BdsRoutes = {
|
||||
App: app,
|
||||
Server: Server
|
||||
|
@ -96,7 +96,7 @@ var Config = {
|
||||
telegram: {
|
||||
admins: ["all_users"],
|
||||
ban: ["Steve_mine_mine"],
|
||||
token: null
|
||||
token: ""
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,49 +1,44 @@
|
||||
const fs = require("fs");
|
||||
const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
let Tokens = [
|
||||
{
|
||||
Token: "",
|
||||
Email: "",
|
||||
TelegramID: null,
|
||||
TelegramID: 0,
|
||||
Scoped: "admin"
|
||||
},
|
||||
{
|
||||
Token: "",
|
||||
Email: "",
|
||||
TelegramID: "",
|
||||
TelegramID: null,
|
||||
Scoped: "user"
|
||||
}
|
||||
];
|
||||
|
||||
/*
|
||||
const TokenFile = BdsSettings
|
||||
const BdsSettings = require("./BdsSettings");
|
||||
const TokenFile = path.join(BdsSettings.bds_dir, "BdsToken.json");
|
||||
const Save = () => fs.writeFileSync(TokenFile, JSON.stringify(Tokens, null, 2));
|
||||
if (fs.existsSync(TokenFile)) Tokens = JSON.parse(fs.readFileSync(TokenFile, "utf8"));
|
||||
else {
|
||||
Tokens = [];
|
||||
Save();
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Register new Token to Bds Maneger Core
|
||||
*
|
||||
*/
|
||||
function CreateToken(Email = "", TelegramID = null, AdminScoped = "admin") {
|
||||
if (!Email) throw new Error("Required Email");
|
||||
if (!/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(Email)) throw new Error("Email is invalid");
|
||||
if (Tokens.find(a => a.Email === Email)) throw new Error("this Email is already in use.");
|
||||
function CreateToken(AdminScoped = "admin", TelegramID = null) {
|
||||
if (!(AdminScoped === "admin" || AdminScoped === "user")) throw new Error("Invalid Admin Scoped, valid use admin and user");
|
||||
const GetRandomUUID = crypto.randomUUID().split("-");
|
||||
const TokenObject = {
|
||||
Token: `BdsTks_${GetRandomUUID[0]}${GetRandomUUID[GetRandomUUID.length - 1]}`,
|
||||
Email: Email,
|
||||
TelegramID: TelegramID,
|
||||
Scoped: AdminScoped
|
||||
}
|
||||
Tokens.push(TokenObject);
|
||||
return TokenObject;;
|
||||
Save();
|
||||
return TokenObject;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -53,22 +48,56 @@ function DeleteToken(Token = "") {
|
||||
if (!Token) throw new Error("Inform valid Token");
|
||||
if (!(Tokens.find(token => token.Token === Token))) throw new Error("this token not exists.");
|
||||
Tokens = Tokens.filter(token => token.Token !== Token);
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for is valid Token
|
||||
*/
|
||||
function CheckToken(Token = "", RequiredPrivilegied = true) {
|
||||
function CheckToken(Token = "", Scope = "admin") {
|
||||
if (!Token) throw new Error("Inform valid Token");
|
||||
if (!(Scope === "admin" || Scope === "user" || Scope === "all")) throw new Error("Invalid Scope, valid use admin and user");
|
||||
// Tmp Tokens
|
||||
let TmpTokens = Tokens;
|
||||
if (RequiredPrivilegied) TmpTokens = TmpTokens.filter(token => token.Scoped === "admin");
|
||||
if (TmpTokens.find(token.Token === Token)) return true; else return false;
|
||||
if (Scope !== "all") {
|
||||
if (Scope === "user") TmpTokens = TmpTokens.filter(token => token.Scoped === "user");
|
||||
else if (Scope === "admin") TmpTokens = TmpTokens.filter(token => token.Scoped === "admin");
|
||||
}
|
||||
// Check if Token exists
|
||||
if (TmpTokens.find(token => token.Token === Token)) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update TelegramID for Token
|
||||
*/
|
||||
function UpdateTelegramID(Token = "", TelegramID = null) {
|
||||
if (!Token) throw new Error("Inform valid Token");
|
||||
if (!TelegramID) throw new Error("Inform valid TelegramID");
|
||||
if (!(CheckToken(Token, "all"))) throw new Error("this token not exists.");
|
||||
Tokens = Tokens.map(token => {
|
||||
if (token.Token === Token) token.TelegramID = TelegramID;
|
||||
return token;
|
||||
});
|
||||
Save();
|
||||
return;
|
||||
}
|
||||
|
||||
/** */
|
||||
function CheckTelegramID(TelegramID = null) {
|
||||
if (!TelegramID) throw new Error("Inform valid TelegramID");
|
||||
if (Tokens.find(token => token.TelegramID === TelegramID)) return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
// Export module
|
||||
module.exports = {
|
||||
CreateToken,
|
||||
DeleteToken,
|
||||
CheckToken
|
||||
CheckToken,
|
||||
UpdateTelegramID,
|
||||
CheckTelegramID,
|
||||
TokenFile,
|
||||
GetAllTokens: () => Tokens
|
||||
}
|
||||
|
Reference in New Issue
Block a user