From 5c57b23abf5a1399e9572a9348150e41a7bf0477 Mon Sep 17 00:00:00 2001 From: unknownpersonog <104310243+unknownpersonog@users.noreply.github.com> Date: Sun, 30 Jul 2023 15:33:40 +0530 Subject: [PATCH 01/20] Testing releases --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index 3eefcb9..7dea76e 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.0.0 +1.0.1 From 61f70a60529a4419988189500bed55e2373ed54a Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sun, 30 Jul 2023 15:53:26 +0530 Subject: [PATCH 02/20] Ping command to get API Status --- src/routes/index.ts | 10 +++++++++- version.txt | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/routes/index.ts b/src/routes/index.ts index 6e073d9..700afad 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,8 +1,16 @@ -import { Router } from 'express'; +import { Request, Response, Router } from 'express'; import usersRouter from './users'; const router = Router(); router.use('/users', usersRouter); +router.use('/ping', (res: Response) => { + try { + res.status(200).send('Pong!'); + } + catch (err) { + res.status(501).send('Internal Server Error') + } +}); export default router; \ No newline at end of file diff --git a/version.txt b/version.txt index 7dea76e..7f20734 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.0.1 +1.0.1 \ No newline at end of file From d86b33de3853a9851007960d87c739fb41cfd14e Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sun, 30 Jul 2023 16:05:24 +0530 Subject: [PATCH 03/20] Fix for ping --- src/routes/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/routes/index.ts b/src/routes/index.ts index 700afad..ca25587 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -5,9 +5,10 @@ const router = Router(); router.use('/users', usersRouter); -router.use('/ping', (res: Response) => { +router.use('/ping', async (req: Request, res: Response) => { try { res.status(200).send('Pong!'); + return; } catch (err) { res.status(501).send('Internal Server Error') From 7927b9f5a0ed4e0a8b6e204103e53abbe4c689a0 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sun, 30 Jul 2023 17:13:02 +0530 Subject: [PATCH 04/20] Ping now returns time taken to process using headers --- package.json | 6 ++++-- src/routes/index.ts | 22 ++++++++++++++-------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 41b3163..7ea02d4 100644 --- a/package.json +++ b/package.json @@ -32,13 +32,14 @@ "@types/nodemailer": "^6.4.8", "@types/passport": "^1.0.12", "@types/passport-discord": "^0.1.6", + "@types/response-time": "^2.3.5", "nodemon": "^2.0.22", "ts-node": "^10.9.1", "typescript": "^5.1.6" }, "dependencies": { - "axios": "^1.4.0", "adm-zip": "^0.5.10", + "axios": "^1.4.0", "connect-mongo": "^5.0.0", "cors": "^2.8.5", "dotenv": "^16.3.1", @@ -47,6 +48,7 @@ "mongoose": "^7.3.1", "nodemailer": "^6.9.3", "passport": "^0.6.0", - "passport-discord": "^0.1.4" + "passport-discord": "^0.1.4", + "response-time": "^2.3.2" } } diff --git a/src/routes/index.ts b/src/routes/index.ts index ca25587..bf50c98 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,17 +1,23 @@ -import { Request, Response, Router } from 'express'; +import { NextFunction, Request, Response, Router } from 'express'; +import responseTime from 'response-time'; import usersRouter from './users'; const router = Router(); router.use('/users', usersRouter); -router.use('/ping', async (req: Request, res: Response) => { +router.use('/ping', responseTime()) + +router.get('/ping', async (req: Request, res: Response, next: NextFunction) => { try { - res.status(200).send('Pong!'); - return; - } - catch (err) { - res.status(501).send('Internal Server Error') + const responseObj = { + message: 'Pong!', + }; + + res.json(responseObj); + } catch (err) { + res.status(501).send('Internal Server Error'); } -}); + }); + export default router; \ No newline at end of file From f82471e95b637b9c4d81ec00eb619033d772995a Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sun, 30 Jul 2023 20:56:22 +0530 Subject: [PATCH 05/20] Added /addvps (#1 Test) --- src/database/schemas/index.ts | 4 +- src/database/schemas/vps.ts | 10 ++++ src/routes/index.ts | 4 +- src/routes/vps/add/index.ts | 108 ++++++++++++++++++++++++++++++++++ src/routes/vps/index.ts | 7 +++ 5 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 src/database/schemas/vps.ts create mode 100644 src/routes/vps/add/index.ts create mode 100644 src/routes/vps/index.ts diff --git a/src/database/schemas/index.ts b/src/database/schemas/index.ts index 83558b6..652baf1 100644 --- a/src/database/schemas/index.ts +++ b/src/database/schemas/index.ts @@ -1,2 +1,4 @@ import DiscordAPI from './DiscordAPI' -export { DiscordAPI }; \ No newline at end of file +import vps from './vps' + +export { DiscordAPI, vps }; \ No newline at end of file diff --git a/src/database/schemas/vps.ts b/src/database/schemas/vps.ts new file mode 100644 index 0000000..d73c467 --- /dev/null +++ b/src/database/schemas/vps.ts @@ -0,0 +1,10 @@ +import mongoose from "mongoose"; + +const vpsSchema = new mongoose.Schema({ + id: { type: Number, required: true, unique: true }, + name: { type: String, required: true }, + os: { type: String, required: true }, + port: { type: Number, required: false, unique: true }, +}); + + export default mongoose.model('vpsdata', vpsSchema) \ No newline at end of file diff --git a/src/routes/index.ts b/src/routes/index.ts index bf50c98..45bc811 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,11 +1,11 @@ import { NextFunction, Request, Response, Router } from 'express'; import responseTime from 'response-time'; import usersRouter from './users'; - +import vpsRouter from './vps'; const router = Router(); router.use('/users', usersRouter); - +router.use('/vps', vpsRouter) router.use('/ping', responseTime()) router.get('/ping', async (req: Request, res: Response, next: NextFunction) => { diff --git a/src/routes/vps/add/index.ts b/src/routes/vps/add/index.ts new file mode 100644 index 0000000..4b0942e --- /dev/null +++ b/src/routes/vps/add/index.ts @@ -0,0 +1,108 @@ +import { Request, Response, Router } from 'express'; +import { vps } from '../../../database/schemas'; + +const router = Router(); +interface RequestData { + req: Request; + res: Response; + } + + const requestQueue: RequestData[] = []; // Specify the type of the requestQueue array + + router.post('/', async (req: Request, res: Response) => { + try { + const requestData: RequestData = { + req, + res, + }; + requestQueue.push(requestData); + + if (requestQueue.length === 1) { + // Process the request immediately if it's the only one in the queue + await processRequest(requestData); + } else { + // The request is added to the queue, and it will be processed later + await waitForRequestCompletion(requestData); + } + } catch (err) { + console.error('Error processing request:', err); + res.status(500).send('Internal Server Error'); + } + }); + + async function processRequest(requestData: RequestData) { + try { + const vpsPort = await getLastId() + 5001; + const vpsName = requestData.req.body.vps_name; + const vpsOs = requestData.req.body.vps_os; + const vpsId = await getLastId() + 1; + + if (!vpsName || !vpsOs) { + return requestData.res.status(400).send('Invalid Request Body!'); + } + + const existingVPS = await vps.findOne({ vpsId }); + if (existingVPS) { + return requestData.res.status(409).send('VPS already exists'); + } + + const newVPS = new vps({ + port: vpsPort, + name: vpsName, + os: vpsOs, + id: vpsId, + }); + + await newVPS.save(); + + requestData.res.status(200).send('VPS created successfully'); + } catch (err) { + console.error('Error creating vps:', err); + requestData.res.status(500).send('Internal Server Error'); + } finally { + // After processing the request, remove it from the queue + const index = requestQueue.indexOf(requestData); + if (index !== -1) { + requestQueue.splice(index, 1); + } + + // If there are other requests in the queue, process the next one + if (requestQueue.length > 0) { + const nextRequest = requestQueue[0]; + await processRequest(nextRequest); + } + } + } + + function waitForRequestCompletion(requestData: RequestData) { + return new Promise((resolve) => { + const checkQueue = () => { + if (requestData === requestQueue[0]) { + // If this request is the first in the queue, start processing it + processRequest(requestData).then(() => resolve()); + } else { + // If this request is not first in the queue, wait and check again + setTimeout(checkQueue, 100); + } + }; + checkQueue(); + }); + } + + +async function getLastId() { + let lastId = 0; + + try { + const existingVpsData = await vps.findOne({}, {}, { sort: { id: -1 } }); + if (existingVpsData) { + lastId = existingVpsData.id; + } + } catch (err) { + console.error("Error while fetching lastId:", err); + } + + return lastId; + } + +export default router; \ No newline at end of file diff --git a/src/routes/vps/index.ts b/src/routes/vps/index.ts new file mode 100644 index 0000000..b57b12f --- /dev/null +++ b/src/routes/vps/index.ts @@ -0,0 +1,7 @@ +import { Router } from 'express'; +import addVPSRouter from './add' +const router = Router(); + +router.use('/add', addVPSRouter) + +export default router; \ No newline at end of file From 5087a326bae4d0e3743c3df65d148dfb07afc2c5 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Mon, 31 Jul 2023 22:01:50 +0530 Subject: [PATCH 06/20] Fixed Queues (Older Alternative) Test #2 --- package.json | 1 + src/routes/vps/add/index.ts | 74 ++++++------------------------------- 2 files changed, 12 insertions(+), 63 deletions(-) diff --git a/package.json b/package.json index 7ea02d4..7e2a270 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "cors": "^2.8.5", "dotenv": "^16.3.1", "express": "^4.18.2", + "express-queue": "^0.0.13", "express-session": "^1.17.3", "mongoose": "^7.3.1", "nodemailer": "^6.9.3", diff --git a/src/routes/vps/add/index.ts b/src/routes/vps/add/index.ts index 4b0942e..936b460 100644 --- a/src/routes/vps/add/index.ts +++ b/src/routes/vps/add/index.ts @@ -1,49 +1,24 @@ import { Request, Response, Router } from 'express'; import { vps } from '../../../database/schemas'; +// @ts-ignore +import queue from 'express-queue'; const router = Router(); -interface RequestData { - req: Request; - res: Response; - } - - const requestQueue: RequestData[] = []; // Specify the type of the requestQueue array - - router.post('/', async (req: Request, res: Response) => { - try { - const requestData: RequestData = { - req, - res, - }; - requestQueue.push(requestData); - - if (requestQueue.length === 1) { - // Process the request immediately if it's the only one in the queue - await processRequest(requestData); - } else { - // The request is added to the queue, and it will be processed later - await waitForRequestCompletion(requestData); - } - } catch (err) { - console.error('Error processing request:', err); - res.status(500).send('Internal Server Error'); - } - }); - - async function processRequest(requestData: RequestData) { +router.use('/', queue({ activeLimit: 1, queuedLimit: -1 })) +router.post('/', async (req: Request, res: Response) => { try { const vpsPort = await getLastId() + 5001; - const vpsName = requestData.req.body.vps_name; - const vpsOs = requestData.req.body.vps_os; + const vpsName = req.body.vps_name; + const vpsOs = req.body.vps_os; const vpsId = await getLastId() + 1; if (!vpsName || !vpsOs) { - return requestData.res.status(400).send('Invalid Request Body!'); + return res.status(400).send('Invalid Request Body!'); } const existingVPS = await vps.findOne({ vpsId }); if (existingVPS) { - return requestData.res.status(409).send('VPS already exists'); + return res.status(409).send('VPS already exists'); } const newVPS = new vps({ @@ -55,39 +30,12 @@ interface RequestData { await newVPS.save(); - requestData.res.status(200).send('VPS created successfully'); + res.status(200).send('VPS created successfully'); } catch (err) { console.error('Error creating vps:', err); - requestData.res.status(500).send('Internal Server Error'); - } finally { - // After processing the request, remove it from the queue - const index = requestQueue.indexOf(requestData); - if (index !== -1) { - requestQueue.splice(index, 1); - } - - // If there are other requests in the queue, process the next one - if (requestQueue.length > 0) { - const nextRequest = requestQueue[0]; - await processRequest(nextRequest); - } + res.status(500).send('Internal Server Error'); } - } - - function waitForRequestCompletion(requestData: RequestData) { - return new Promise((resolve) => { - const checkQueue = () => { - if (requestData === requestQueue[0]) { - // If this request is the first in the queue, start processing it - processRequest(requestData).then(() => resolve()); - } else { - // If this request is not first in the queue, wait and check again - setTimeout(checkQueue, 100); - } - }; - checkQueue(); - }); - } +}); async function getLastId() { From 6722e43a0af175a6b27e7485b168fcf89bcd9b96 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Tue, 1 Aug 2023 18:14:20 +0530 Subject: [PATCH 07/20] Added /assignvps --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index 7f20734..b123147 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.0.1 \ No newline at end of file +1.1 \ No newline at end of file From 1a6d24e87b071b8ab725594b0130916e1522c0e3 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Tue, 1 Aug 2023 18:15:01 +0530 Subject: [PATCH 08/20] Added /assignvps --- src/database/schemas/vps.ts | 3 +- src/routes/vps/assign/index.ts | 60 ++++++++++++++++++++++++++++++++++ src/routes/vps/index.ts | 4 ++- 3 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 src/routes/vps/assign/index.ts diff --git a/src/database/schemas/vps.ts b/src/database/schemas/vps.ts index d73c467..6e4abe2 100644 --- a/src/database/schemas/vps.ts +++ b/src/database/schemas/vps.ts @@ -4,7 +4,8 @@ const vpsSchema = new mongoose.Schema({ id: { type: Number, required: true, unique: true }, name: { type: String, required: true }, os: { type: String, required: true }, - port: { type: Number, required: false, unique: true }, + port: { type: Number, required: true, unique: true }, + owner: { type: String, default: "N/A", required: false }, }); export default mongoose.model('vpsdata', vpsSchema) \ No newline at end of file diff --git a/src/routes/vps/assign/index.ts b/src/routes/vps/assign/index.ts new file mode 100644 index 0000000..13592b1 --- /dev/null +++ b/src/routes/vps/assign/index.ts @@ -0,0 +1,60 @@ +import { Request, Response, Router } from 'express'; +import { DiscordAPI, vps } from '../../../database/schemas'; +// @ts-ignore +import queue from 'express-queue'; +const router = Router(); + +router.use('/', queue({ activeLimit: 1, queuedLimit: -1 })) +router.post('/', async(req: Request, res: Response) => { + const discordId = req.body.discordId; + const plan = req.body.plan; + const availableVPSId = await assignNextAvailableVPS(); + + if (availableVPSId === 0) { + return res.status(500).send('No VPS in stock') + } + + try { + await vps.findOneAndUpdate( + { id: availableVPSId, owner: 'N/A' }, + { $set: { owner: discordId } }, + { new: true } // Return the updated VPS document. + ); + try { + await DiscordAPI.findOneAndUpdate( + { discordId: discordId, 'vps.id': 'N/A' }, + { $set: { "vps.$.id": availableVPSId } }, + { new: true } + ) + } + catch (err) { + return res.status(500).send('Error while updating user data') + } + res.status(200).send(`VPS ${availableVPSId} assigned to Discord user ${discordId}`); + } + catch (err) { + return res.status(500).send('Internal Server Error') + } +}) + +async function assignNextAvailableVPS() { + try { + // Find the first available VPS with owner tag "N/A" by sorting the VPS collection in ascending order of the ID. + const firstAvailableVPS = await vps + .findOne({ owner: 'N/A' }) + .sort({ id: 1 }) + .select({ id: 1, _id: 0 }) + + if (!firstAvailableVPS) { + return 0; + } + + // If the first available VPS has the owner tag "N/A," return it as the next available VPS. + return firstAvailableVPS.id.toString();; + } catch (err) { + console.error('Error assigning VPS:', err); + throw err; // You can handle the error appropriately based on your use case. + } +} + +export default router; \ No newline at end of file diff --git a/src/routes/vps/index.ts b/src/routes/vps/index.ts index b57b12f..eb4de81 100644 --- a/src/routes/vps/index.ts +++ b/src/routes/vps/index.ts @@ -1,7 +1,9 @@ import { Router } from 'express'; -import addVPSRouter from './add' +import addVPSRouter from './add'; +import assignVPSRouter from './assign'; const router = Router(); router.use('/add', addVPSRouter) +router.use('/assign', assignVPSRouter) export default router; \ No newline at end of file From 3148b826cebf83436d86b4b68e247086d1cca073 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sat, 5 Aug 2023 21:15:05 +0530 Subject: [PATCH 09/20] vps is now a array instead --- src/database/schemas/DiscordAPI.ts | 6 ++---- src/routes/users/create/index.ts | 2 +- src/routes/vps/assign/index.ts | 4 ++-- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/database/schemas/DiscordAPI.ts b/src/database/schemas/DiscordAPI.ts index 6702489..452f3b2 100644 --- a/src/database/schemas/DiscordAPI.ts +++ b/src/database/schemas/DiscordAPI.ts @@ -6,11 +6,9 @@ const discordAPISchema = new mongoose.Schema({ verificationToken: { type: String, required: false }, verificationTokenExpiresAt: { type: Date, required: false }, verified: { type: String, required: false, default: 'false' }, - vps: [ - { - id: { type: String, default: 'N/A' } + vps: { + id: { type: String, default: '0' } } - ] }); export default mongoose.model('discordUsers', discordAPISchema) \ No newline at end of file diff --git a/src/routes/users/create/index.ts b/src/routes/users/create/index.ts index 477519e..571d59e 100644 --- a/src/routes/users/create/index.ts +++ b/src/routes/users/create/index.ts @@ -19,7 +19,7 @@ router.post('/', async (req: Request, res: Response) => { const newUser = new DiscordAPI({ email, discordId, - vps: [{ id: 'N/A' }] + vps: { id: '0' } }); await newUser.save(); diff --git a/src/routes/vps/assign/index.ts b/src/routes/vps/assign/index.ts index 13592b1..6d6f494 100644 --- a/src/routes/vps/assign/index.ts +++ b/src/routes/vps/assign/index.ts @@ -22,8 +22,8 @@ router.post('/', async(req: Request, res: Response) => { ); try { await DiscordAPI.findOneAndUpdate( - { discordId: discordId, 'vps.id': 'N/A' }, - { $set: { "vps.$.id": availableVPSId } }, + { discordId: discordId }, + { $set: { "vps.id": availableVPSId } }, { new: true } ) } From 5434f71048213269ddfcb26d09383d4f96e52570 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Sun, 6 Aug 2023 11:55:42 +0530 Subject: [PATCH 10/20] vps info and more changed --- src/database/schemas/vps.ts | 3 +++ src/routes/vps/add/index.ts | 6 ++++++ src/routes/vps/index.ts | 19 ++++++++++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/database/schemas/vps.ts b/src/database/schemas/vps.ts index 6e4abe2..6524632 100644 --- a/src/database/schemas/vps.ts +++ b/src/database/schemas/vps.ts @@ -6,6 +6,9 @@ const vpsSchema = new mongoose.Schema({ os: { type: String, required: true }, port: { type: Number, required: true, unique: true }, owner: { type: String, default: "N/A", required: false }, + pass: { type: String, required: true }, + user: { type: String, required: true }, + ip: { type: String, required: true } }); export default mongoose.model('vpsdata', vpsSchema) \ No newline at end of file diff --git a/src/routes/vps/add/index.ts b/src/routes/vps/add/index.ts index 936b460..b0c740d 100644 --- a/src/routes/vps/add/index.ts +++ b/src/routes/vps/add/index.ts @@ -10,6 +10,9 @@ router.post('/', async (req: Request, res: Response) => { const vpsPort = await getLastId() + 5001; const vpsName = req.body.vps_name; const vpsOs = req.body.vps_os; + const vpsPass = req.body.vps_pass; + const vpsUser = req.body.vps_user; + const vpsIp = req.body.vps_ip const vpsId = await getLastId() + 1; if (!vpsName || !vpsOs) { @@ -26,6 +29,9 @@ router.post('/', async (req: Request, res: Response) => { name: vpsName, os: vpsOs, id: vpsId, + pass: vpsPass, + user: vpsUser, + ip: vpsIp }); await newVPS.save(); diff --git a/src/routes/vps/index.ts b/src/routes/vps/index.ts index eb4de81..e842798 100644 --- a/src/routes/vps/index.ts +++ b/src/routes/vps/index.ts @@ -1,9 +1,26 @@ -import { Router } from 'express'; +import { Request, Response, Router } from 'express'; import addVPSRouter from './add'; import assignVPSRouter from './assign'; +import { vps } from '../../database/schemas'; const router = Router(); router.use('/add', addVPSRouter) router.use('/assign', assignVPSRouter) +router.get('/info/:vpsId', async (req: Request, res: Response) => { + try { + const vpsId = req.params.vpsId; + + const vpsX = await vps.findOne({ id: vpsId }); + + if (!vpsX) { + return res.status(404).send('VPS not found'); + } + + res.send(vpsX); + } catch (err) { + console.error('Error retrieving user:', err); + res.status(500).send('Internal Server Error'); + } + }); export default router; \ No newline at end of file From 46ad0a49002b4501a39101b40e4811daada8f217 Mon Sep 17 00:00:00 2001 From: unknownpersonog <104310243+unknownpersonog@users.noreply.github.com> Date: Tue, 8 Aug 2023 11:08:57 +0530 Subject: [PATCH 11/20] Create README.md --- README.md | 135 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..12d13bb --- /dev/null +++ b/README.md @@ -0,0 +1,135 @@ + +# UnknownVPS API + +Application Programming Interface (API) for UnknownVPS and can be used for various other purposes as well. + +Brought by UnknownVPS Team + + +## Acknowledgements + + - [LongZ3r](https://github.com/LongZ3r) - Discord Bot Contribution + + + +## Deployment + +To deploy this project on your trusted infrastructure. +This guide considers you have Node 16 or 18 installed and you are doing all things in one go. + +##### Step 1 - Make a new directory (Name is changable) +```bash + mkdir -p UnknownVPS +``` +##### Step 2 - Install curl (or any package) to get files. +```bash + sudo apt-get install curl -y +``` +##### Step 3 - Change Directory +```bash + cd UnknownVPS +``` +##### Step 4 - Get the package.json +```bash + curl -Lo package.json "https://github.com/unknownpersonog/unknownvps-v2/raw/master/package.json" +``` +##### Step 5 - Get updater.js +```bash + curl -Lo updater.js "https://github.com/unknownpersonog/unknownvps-v2/raw/master/updater.js" +``` +##### Step 6 - Install Dependencies +```bash + npm i +``` +##### Step 7 - Run updater.js +```bash + node updater.js +``` +##### Step 8 - Change directory to unknownvps-api/dist +```bash + cd unknownvps-api/dist +``` +##### Step 9 - Create a .env file and fill the required details from example env in the repository +```bash + nano .env +``` +##### Step 10 - Run the API +```bash + node index.js +``` +## API Reference + +#### Ping API + +```http + GET /api/ping +``` + +| Parameter | Type | Description | +| :-------- | :------- | :------------------------- | +| `None` | `string` | Get API Response Time | + +#### Create User + +```http + POST /api/users/create +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `email` | `string` | **Required**. Email of user to create. | +| `discordId` | `string` | **Required**. Discord Id of user to create. | + +#### Verify User +```http + POST /api/users/verify/mail +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `email` | `string` | **Required**. Email of user to create. | +| `discordId` | `string` | **Required**. Discord Id of user to verify. | + +```http + POST /api/users/verify/token +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `token` | `string` | **Required**. Token received on email | +| `discordId` | `string` | **Required**. Discord Id of user to verify. | + +#### User Info + +```http + GET /api/users/info/${discordId} +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `discordId` | `string` | **Required**. Discord Id of user to get data from. | + +#### Add VPS + +```http + POST /api/vps/add +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `vps_name` | `string` | **Required**. Name of VPS. | +| `vps_os` | `string` | **Required**. OS of VPS. | +| `vps_pass` | `string` | **Required**. Password of VPS for the defined user. | +| `vps_user` | `string` | **Required**. User for VPS. | +| `vps_ip` | `string` | **Required**. IP to access VPS. | + +#### Assign VPS + +```http + POST /api/vps/assign +``` + +| Parameter | Type | Description | +| :-------- | :------- | :-------------------------------- | +| `discordId` | `string` | **Required**. Discord ID to assign VPS to. | + From 72d2d3fd0722ce9a4cedeaf38ce34a0ecbb53cc8 Mon Sep 17 00:00:00 2001 From: unknownpersonog <104310243+unknownpersonog@users.noreply.github.com> Date: Tue, 8 Aug 2023 11:09:58 +0530 Subject: [PATCH 12/20] Update version.txt --- version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.txt b/version.txt index b123147..45a1b3f 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.1 \ No newline at end of file +1.1.2 From 0e3138cbb258e8d496d1a139712805282f5f40e0 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Tue, 8 Aug 2023 11:12:42 +0530 Subject: [PATCH 13/20] Minor Fix --- src/routes/vps/add/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/vps/add/index.ts b/src/routes/vps/add/index.ts index b0c740d..759d12b 100644 --- a/src/routes/vps/add/index.ts +++ b/src/routes/vps/add/index.ts @@ -12,7 +12,7 @@ router.post('/', async (req: Request, res: Response) => { const vpsOs = req.body.vps_os; const vpsPass = req.body.vps_pass; const vpsUser = req.body.vps_user; - const vpsIp = req.body.vps_ip + const vpsIp = req.body.vps_ip; const vpsId = await getLastId() + 1; if (!vpsName || !vpsOs) { From f4c1694d34cc5b9540e903826decbb17887127ae Mon Sep 17 00:00:00 2001 From: unknownpersonog <104310243+unknownpersonog@users.noreply.github.com> Date: Tue, 8 Aug 2023 11:16:26 +0530 Subject: [PATCH 14/20] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 12d13bb..43e0f3a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,12 @@ Application Programming Interface (API) for UnknownVPS and can be used for vario Brought by UnknownVPS Team + +## Official API Hook +#### The API is officially hooked into a discord bot +Bot Link: [Discord Bot by LongZ3r](https://github.com/longz3r/unknownvps-discord-bot) + + ## Acknowledgements - [LongZ3r](https://github.com/LongZ3r) - Discord Bot Contribution From 2f32edb894064814736820d55bd5b5387e608c22 Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Fri, 6 Oct 2023 16:47:35 +0530 Subject: [PATCH 15/20] Changes: - All responses are returned as JSON now - Authorization has been added - Experimental Plans Feature - Moved SMTP to settings.json - Fixed a typo on server start - Example settings.json - Removed unused packages --- package.json | 5 ----- settings.json | 10 +++++++++ settings.json.example | 10 +++++++++ src/database/index.ts | 2 +- src/database/schemas/DiscordAPI.ts | 6 +++++- src/database/schemas/index.ts | 1 - src/database/schemas/vps.ts | 3 ++- src/index.ts | 4 ++-- src/routes/index.ts | 6 +++--- src/routes/users/create/index.ts | 15 +++++++------- src/routes/users/index.ts | 7 +++---- src/routes/users/verify/index.ts | 33 +++++++++++++++--------------- src/routes/vps/add/index.ts | 14 +++++++------ src/routes/vps/assign/index.ts | 22 ++++++++++---------- src/routes/vps/index.ts | 9 ++++---- src/services/checkAuthorization.ts | 33 ++++++++++++++++++++++++++++++ src/services/settingsParser.ts | 9 ++++++++ src/utils/createApp.ts | 19 ++++++++--------- src/utils/types.ts | 14 ++++++++++++- version.txt | 2 +- 20 files changed, 150 insertions(+), 74 deletions(-) create mode 100644 settings.json create mode 100644 settings.json.example create mode 100644 src/services/checkAuthorization.ts create mode 100644 src/services/settingsParser.ts diff --git a/package.json b/package.json index 7e2a270..07cd443 100644 --- a/package.json +++ b/package.json @@ -25,13 +25,10 @@ }, "homepage": "https://github.com/unknownpersonog/unknownvps-client#readme", "devDependencies": { - "@types/axios": "^0.14.0", - "@types/cors": "^2.8.13", "@types/express": "^4.17.17", "@types/express-session": "^1.17.7", "@types/nodemailer": "^6.4.8", "@types/passport": "^1.0.12", - "@types/passport-discord": "^0.1.6", "@types/response-time": "^2.3.5", "nodemon": "^2.0.22", "ts-node": "^10.9.1", @@ -41,7 +38,6 @@ "adm-zip": "^0.5.10", "axios": "^1.4.0", "connect-mongo": "^5.0.0", - "cors": "^2.8.5", "dotenv": "^16.3.1", "express": "^4.18.2", "express-queue": "^0.0.13", @@ -49,7 +45,6 @@ "mongoose": "^7.3.1", "nodemailer": "^6.9.3", "passport": "^0.6.0", - "passport-discord": "^0.1.4", "response-time": "^2.3.2" } } diff --git a/settings.json b/settings.json new file mode 100644 index 0000000..184d9f6 --- /dev/null +++ b/settings.json @@ -0,0 +1,10 @@ +{ + "companyName": "UnknownVPS", + "smtp": { + "host": "smtp-relay.brevo.com", + "port": "587", + "user": "drnehapawar98@gmail.com", + "pass": "YSTw86G7X50bLMrR", + "mail": "admin@unknownvps.eu.org" + } +} \ No newline at end of file diff --git a/settings.json.example b/settings.json.example new file mode 100644 index 0000000..0e4e5a6 --- /dev/null +++ b/settings.json.example @@ -0,0 +1,10 @@ +{ + "companyName": "Company Name goes here..", + "smtp": { + "host": "SMTP Host goes here", + "port": "SMTP Port goes here", + "user": "SMTP User goes here", + "pass": "SMTP Password goes here", + "mail": "SMTP Mail goes here" + } +} \ No newline at end of file diff --git a/src/database/index.ts b/src/database/index.ts index 5b0ec58..b8bd94d 100644 --- a/src/database/index.ts +++ b/src/database/index.ts @@ -3,6 +3,6 @@ import mongoose from 'mongoose'; export async function connectDb() { await mongoose .connect(`${process.env.MONGODB_DATABASE_URI}`) - .then(() => console.log('Connected to Databased.')) + .then(() => console.log('Connected to Database.')) .catch((err) => console.log('Error occured while connecting: ' + err)) } diff --git a/src/database/schemas/DiscordAPI.ts b/src/database/schemas/DiscordAPI.ts index 452f3b2..3b4c0a8 100644 --- a/src/database/schemas/DiscordAPI.ts +++ b/src/database/schemas/DiscordAPI.ts @@ -6,9 +6,13 @@ const discordAPISchema = new mongoose.Schema({ verificationToken: { type: String, required: false }, verificationTokenExpiresAt: { type: Date, required: false }, verified: { type: String, required: false, default: 'false' }, - vps: { + admin: { type: String, required: false }, + token: { type: String, required: false }, + vps: [ + { id: { type: String, default: '0' } } + ] }); export default mongoose.model('discordUsers', discordAPISchema) \ No newline at end of file diff --git a/src/database/schemas/index.ts b/src/database/schemas/index.ts index 652baf1..f62c109 100644 --- a/src/database/schemas/index.ts +++ b/src/database/schemas/index.ts @@ -1,4 +1,3 @@ import DiscordAPI from './DiscordAPI' import vps from './vps' - export { DiscordAPI, vps }; \ No newline at end of file diff --git a/src/database/schemas/vps.ts b/src/database/schemas/vps.ts index 6524632..369635f 100644 --- a/src/database/schemas/vps.ts +++ b/src/database/schemas/vps.ts @@ -7,8 +7,9 @@ const vpsSchema = new mongoose.Schema({ port: { type: Number, required: true, unique: true }, owner: { type: String, default: "N/A", required: false }, pass: { type: String, required: true }, + plan: { type: String, required: true }, user: { type: String, required: true }, - ip: { type: String, required: true } + ip: { type: String, required: true }, }); export default mongoose.model('vpsdata', vpsSchema) \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index d9ea487..6255a77 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,9 +4,9 @@ config(); import { connectDb } from './database' const PORT = process.env.PORT || 3001; - +const ENV = process.env.ENVIRONMENT || 'PRODUCTION'; async function main() { - console.log(`Running in ${process.env.ENVIRONMENT} mode.`) + console.log(`Running in ${ENV} mode.`) try { await connectDb(); const app = createApp(); diff --git a/src/routes/index.ts b/src/routes/index.ts index 45bc811..7648dff 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -5,8 +5,8 @@ import vpsRouter from './vps'; const router = Router(); router.use('/users', usersRouter); -router.use('/vps', vpsRouter) -router.use('/ping', responseTime()) +router.use('/vps', vpsRouter); +router.use('/ping', responseTime()); router.get('/ping', async (req: Request, res: Response, next: NextFunction) => { try { @@ -16,7 +16,7 @@ router.get('/ping', async (req: Request, res: Response, next: NextFunction) => { res.json(responseObj); } catch (err) { - res.status(501).send('Internal Server Error'); + res.status(501).json({ error: 'Internal Server Error'}); } }); diff --git a/src/routes/users/create/index.ts b/src/routes/users/create/index.ts index 571d59e..e43b04e 100644 --- a/src/routes/users/create/index.ts +++ b/src/routes/users/create/index.ts @@ -1,4 +1,4 @@ -import express, { Request, Response, Router } from "express"; +import { Request, Response, Router } from "express"; import { DiscordAPI } from "../../../database/schemas"; const router = Router(); @@ -6,28 +6,29 @@ router.post('/', async (req: Request, res: Response) => { try { const discordId = req.body.discordId; const email = req.body.email; - const vps = req.body.vps; if (!discordId || !email) { - return res.status(400).send('Invalid Request Body!') + return res.status(400).json({ error: 'Invalid Request Body!'}) } const existingUser = await DiscordAPI.findOne({ discordId }); if (existingUser) { - return res.status(409).send('User already exists'); + return res.status(409).json({ error: 'User already exists' }); } const newUser = new DiscordAPI({ email, discordId, - vps: { id: '0' } + vps: [ + { id: '0' } + ] }); await newUser.save(); - res.status(200).send('User created successfully'); + res.status(200).json({ message: 'User created successfully' }); } catch (err) { console.error('Error creating user:', err); - res.status(500).send('Internal Server Error'); + return res.status(500).json({ error: 'Internal Server Error' }); } }); diff --git a/src/routes/users/index.ts b/src/routes/users/index.ts index 12c12b8..73f496f 100644 --- a/src/routes/users/index.ts +++ b/src/routes/users/index.ts @@ -3,7 +3,6 @@ const router = Router(); import createUserRouter from './create'; import verifyEmailRouter from './verify'; import { DiscordAPI } from "../../database/schemas"; -import { PartialInfo } from "../../utils/types"; router.use('/create', createUserRouter) router.use('/verify', verifyEmailRouter) @@ -15,13 +14,13 @@ router.get('/info/:discordId', async (req: Request, res: Response) => { const user = await DiscordAPI.findOne({ discordId }); if (!user) { - return res.status(404).send('User not found'); + return res.status(404).json({ error: 'User not found'}); } - res.send(user); + res.json(user); } catch (err) { console.error('Error retrieving user:', err); - res.status(500).send('Internal Server Error'); + res.status(500).json({ error: 'Internal Server Error' }); } }); diff --git a/src/routes/users/verify/index.ts b/src/routes/users/verify/index.ts index 8ae0918..cdd9c2b 100644 --- a/src/routes/users/verify/index.ts +++ b/src/routes/users/verify/index.ts @@ -1,8 +1,8 @@ import { config } from 'dotenv' import { Request, Response, Router } from "express"; -import crypto from 'crypto'; import nodemailer from 'nodemailer'; import { DiscordAPI } from "../../../database/schemas"; +import { settingsParser } from '../../../services/settingsParser'; config(); const router = Router(); @@ -12,7 +12,7 @@ router.post('/mail', async(req: Request, res: Response) => { const email = req.body.email; const userCheck = await DiscordAPI.findOne({ discordId }); if (!userCheck) { - return res.status(404).send('User not found') + return res.status(404).json({ error: 'User not found' }) } await DiscordAPI.findOneAndUpdate( { discordId }, @@ -26,19 +26,20 @@ router.post('/mail', async(req: Request, res: Response) => { { discordId }, { verificationToken, verificationTokenExpiresAt: expiresAt } ); - + + const settings = settingsParser(); const transporter = nodemailer.createTransport({ - host: String(process.env.SMTP_HOST), - port: Number(process.env.SMTP_PORT), + host: String(settings.smtp.host), + port: Number(settings.smtp.port), secure: false, // upgrade later with STARTTLS auth: { - user: String(process.env.SMTP_USER), - pass: String(process.env.SMTP_PASS), + user: String(settings.smtp.user), + pass: String(settings.smtp.pass), }, }); const mailOptions = { - from: `${process.env.COMPANY_NAME} <${process.env.SMTP_MAIL}>`, + from: `${settings.companyName} <${settings.smtp.mail}>`, to: email, subject: 'Email Verification', text: `Your code for verification is: @@ -98,7 +99,7 @@ router.post('/mail', async(req: Request, res: Response) => { }; transporter.sendMail(mailOptions); - res.status(200).send('Email Sent'); + res.status(200).json({ message: 'Email Sent' }); } catch (error) { console.error('Error sending verification email:', error); res.status(500).json({ error: 'An error occurred while sending the verification email.' }); @@ -110,14 +111,14 @@ router.post('/token', async(req: Request, res: Response) => { const discordId = req.body.discordId; if (!token || !discordId) { - return res.status(404).send('Invalid Request'); + return res.status(404).json({ error: 'Invalid Request' }); } try { const user = await DiscordAPI.findOne({ discordId }); if (!user) { - return res.status(404).send('User not found'); + return res.status(404).json({ error: 'User not found' }); } const expiresAt = user.verificationTokenExpiresAt; @@ -127,12 +128,12 @@ router.post('/token', async(req: Request, res: Response) => { { discordId }, { $unset: { verificationToken: '', verificationTokenExpiresAt: '' } } ); - return res.status(400).send('Token Expired'); + return res.status(400).json({ error: 'Token Expired' }); } if (user.verified === 'true') { - return res.status(400).send('User already verified'); + return res.status(400).json({ error: 'User already verified'}); } if (user.verificationToken === token) { @@ -145,13 +146,13 @@ router.post('/token', async(req: Request, res: Response) => { { $unset: { verificationToken: '', verificationTokenExpiresAt: '' } } ); - return res.status(200).send('Verified'); + return res.status(200).json({ message: 'Verified' }); } else { - return res.status(404).send('Invalid Token'); + return res.status(404).json({ error: 'Invalid Token' }); } } catch (error) { console.error('Error verifying token:', error); - res.status(500).json({ error: 'An error occurred while verifying the token.' }); + return res.status(500).json({ error: 'An error occurred while verifying the token.' }); } }); diff --git a/src/routes/vps/add/index.ts b/src/routes/vps/add/index.ts index 759d12b..b6ac5f9 100644 --- a/src/routes/vps/add/index.ts +++ b/src/routes/vps/add/index.ts @@ -13,17 +13,18 @@ router.post('/', async (req: Request, res: Response) => { const vpsPass = req.body.vps_pass; const vpsUser = req.body.vps_user; const vpsIp = req.body.vps_ip; + const vpsPlan = req.body.vps_plan; const vpsId = await getLastId() + 1; - if (!vpsName || !vpsOs) { - return res.status(400).send('Invalid Request Body!'); + if (!vpsName || !vpsOs || !vpsPort || !vpsPass || !vpsUser || !vpsIp || !vpsPlan) { + return res.status(400).json({ error: 'Invalid Request Body!' }); } const existingVPS = await vps.findOne({ vpsId }); if (existingVPS) { - return res.status(409).send('VPS already exists'); + return res.status(409).json({ error: 'VPS already exists' }); } - + const newVPS = new vps({ port: vpsPort, name: vpsName, @@ -31,15 +32,16 @@ router.post('/', async (req: Request, res: Response) => { id: vpsId, pass: vpsPass, user: vpsUser, + plan: vpsPlan, ip: vpsIp }); await newVPS.save(); - res.status(200).send('VPS created successfully'); + res.status(200).json({ message: 'VPS created successfully' }); } catch (err) { console.error('Error creating vps:', err); - res.status(500).send('Internal Server Error'); + res.status(500).json({ error: 'Internal Server Error' }); } }); diff --git a/src/routes/vps/assign/index.ts b/src/routes/vps/assign/index.ts index 6d6f494..f0d630b 100644 --- a/src/routes/vps/assign/index.ts +++ b/src/routes/vps/assign/index.ts @@ -8,10 +8,10 @@ router.use('/', queue({ activeLimit: 1, queuedLimit: -1 })) router.post('/', async(req: Request, res: Response) => { const discordId = req.body.discordId; const plan = req.body.plan; - const availableVPSId = await assignNextAvailableVPS(); + const availableVPSId = await assignNextAvailableVPS(plan); if (availableVPSId === 0) { - return res.status(500).send('No VPS in stock') + return res.status(500).json({ error: 'No VPS in stock' }) } try { @@ -23,25 +23,26 @@ router.post('/', async(req: Request, res: Response) => { try { await DiscordAPI.findOneAndUpdate( { discordId: discordId }, - { $set: { "vps.id": availableVPSId } }, + { $push: { "vps": { id: availableVPSId } } }, { new: true } - ) + ); } catch (err) { - return res.status(500).send('Error while updating user data') + console.log(err) + return res.status(500).json({ error: 'Error while updating user data' }) } - res.status(200).send(`VPS ${availableVPSId} assigned to Discord user ${discordId}`); + res.status(200).json({ messsage: `VPS ${availableVPSId} assigned to Discord user ${discordId}` }); } catch (err) { - return res.status(500).send('Internal Server Error') + return res.status(500).json({ error: 'Internal Server Error' }); } }) -async function assignNextAvailableVPS() { +async function assignNextAvailableVPS(plan: string) { try { // Find the first available VPS with owner tag "N/A" by sorting the VPS collection in ascending order of the ID. const firstAvailableVPS = await vps - .findOne({ owner: 'N/A' }) + .findOne({ owner: 'N/A', plan: plan }) .sort({ id: 1 }) .select({ id: 1, _id: 0 }) @@ -52,8 +53,7 @@ async function assignNextAvailableVPS() { // If the first available VPS has the owner tag "N/A," return it as the next available VPS. return firstAvailableVPS.id.toString();; } catch (err) { - console.error('Error assigning VPS:', err); - throw err; // You can handle the error appropriately based on your use case. + return console.error('Error assigning VPS:', err); } } diff --git a/src/routes/vps/index.ts b/src/routes/vps/index.ts index e842798..8a4098d 100644 --- a/src/routes/vps/index.ts +++ b/src/routes/vps/index.ts @@ -2,6 +2,7 @@ import { Request, Response, Router } from 'express'; import addVPSRouter from './add'; import assignVPSRouter from './assign'; import { vps } from '../../database/schemas'; + const router = Router(); router.use('/add', addVPSRouter) @@ -13,13 +14,13 @@ router.get('/info/:vpsId', async (req: Request, res: Response) => { const vpsX = await vps.findOne({ id: vpsId }); if (!vpsX) { - return res.status(404).send('VPS not found'); + return res.status(404).json({ error: 'VPS not found' }); } - - res.send(vpsX); + + res.status(200).json(vpsX); } catch (err) { console.error('Error retrieving user:', err); - res.status(500).send('Internal Server Error'); + return res.status(500).json({ error: 'Internal Server Error' }); } }); diff --git a/src/services/checkAuthorization.ts b/src/services/checkAuthorization.ts new file mode 100644 index 0000000..b6d6c3d --- /dev/null +++ b/src/services/checkAuthorization.ts @@ -0,0 +1,33 @@ +import { NextFunction, Request, Response } from "express"; + +// Define a middleware to check for authorization and admin status +async function checkAuthorization(req: Request, res: Response, next: NextFunction) { + try { + // Check if the token exists in the database + const token = req.headers['x-access-token']; + + if (!token) { + // Token is missing, return a 403 Forbidden response + return res.status(403).json({ message: 'Authorization required' }); + } + + const foundToken = process.env.ADMIN_TOKEN + + if (!foundToken) { + // Token does not exist in the database, return a 403 Forbidden response + return res.status(403).json({ message: 'Authorization required' }); + } + + if (token === foundToken) { + next(); + } + else { + res.status(403).send('Authorized Access Only') + } + } catch (error) { + console.error('Error checking authorization:', error); + res.status(500).json({ message: 'Server error' }); + } +} + +export { checkAuthorization }; diff --git a/src/services/settingsParser.ts b/src/services/settingsParser.ts new file mode 100644 index 0000000..a684792 --- /dev/null +++ b/src/services/settingsParser.ts @@ -0,0 +1,9 @@ +import * as fs from 'fs'; +import { Settings } from '../utils/types'; + +export function settingsParser() { +const rawSettingsData = fs.readFileSync('../../settings.json', 'utf8'); +const settingsData: { settings: Settings } = JSON.parse(rawSettingsData); + +return settingsData.settings; +} \ No newline at end of file diff --git a/src/utils/createApp.ts b/src/utils/createApp.ts index 760a86a..385a428 100644 --- a/src/utils/createApp.ts +++ b/src/utils/createApp.ts @@ -1,10 +1,10 @@ import { config } from 'dotenv'; import express, { Express } from 'express'; -import cors from 'cors'; import session from 'express-session'; -import passport from 'passport'; import routes from '../routes'; +import passport from 'passport'; import store from 'connect-mongo'; +import { checkAuthorization } from '../services/checkAuthorization'; config(); @@ -15,9 +15,6 @@ export function createApp(): Express { app.use(express.json()); app.use(express.urlencoded()); - // Using CORS to block external requests - app.use(cors({ origin: ['http://0.0.0.0'], credentials: true })); - app.use( session({ secret: 'CKDJVBIBVPBVAPFJDJKAHFHYEBFUJIAJAJK', @@ -29,12 +26,14 @@ export function createApp(): Express { }), }) ); - - // Passport basic setup - app.use(passport.initialize()); - app.use(passport.session()); + // Enable Passport + app.use(passport.initialize()); + app.use(passport.session()); + + app.use((req, res, next) => setTimeout(() => next(), 800)); + // Render /api as default - app.use('/api', routes); + app.use('/api', checkAuthorization, routes); return app; } \ No newline at end of file diff --git a/src/utils/types.ts b/src/utils/types.ts index 185766b..da93bc7 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -7,4 +7,16 @@ export type PartialInfo = { id: String, } ], -} \ No newline at end of file +} + +export interface Settings { + companyName: String, + + smtp: { + host: String, + port: Number, + user: String, + pass: String, + mail: String + } +} diff --git a/version.txt b/version.txt index 45a1b3f..26aaba0 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.1.2 +1.2.0 From 79dae04e77f8fa82250022ef407d5a887b6c058b Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Fri, 6 Oct 2023 16:51:28 +0530 Subject: [PATCH 16/20] Added settings.json to .gitignore --- .gitignore | 3 ++- settings.json | 10 ---------- 2 files changed, 2 insertions(+), 11 deletions(-) delete mode 100644 settings.json diff --git a/.gitignore b/.gitignore index c09421f..faa9777 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .env node_modules yarn.lock -dist \ No newline at end of file +dist +settings.json \ No newline at end of file diff --git a/settings.json b/settings.json deleted file mode 100644 index 184d9f6..0000000 --- a/settings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "companyName": "UnknownVPS", - "smtp": { - "host": "smtp-relay.brevo.com", - "port": "587", - "user": "drnehapawar98@gmail.com", - "pass": "YSTw86G7X50bLMrR", - "mail": "admin@unknownvps.eu.org" - } -} \ No newline at end of file From 0023753e247e39c3e225206073c0ca52d4dd6b3a Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Fri, 6 Oct 2023 19:33:59 +0530 Subject: [PATCH 17/20] Readme to master --- README.md | 7 +++++-- version.txt | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 43e0f3a..4ed1639 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,11 @@ This guide considers you have Node 16 or 18 installed and you are doing all thin ```bash nano .env ``` -##### Step 10 - Run the API +##### Step 10 - Create a settings.json file and fill the required details from example settings.json in the repository +```bash + nano settings.json +``` +##### Step 11 - Run the API ```bash node index.js ``` @@ -138,4 +142,3 @@ This guide considers you have Node 16 or 18 installed and you are doing all thin | Parameter | Type | Description | | :-------- | :------- | :-------------------------------- | | `discordId` | `string` | **Required**. Discord ID to assign VPS to. | - diff --git a/version.txt b/version.txt index 26aaba0..6085e94 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.2.0 +1.2.1 From c52cb0ab453ddf3040009caa62c16d64634e81ad Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Wed, 18 Oct 2023 18:50:05 +0530 Subject: [PATCH 18/20] error --- src/services/settingsParser.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/settingsParser.ts b/src/services/settingsParser.ts index a684792..c83f275 100644 --- a/src/services/settingsParser.ts +++ b/src/services/settingsParser.ts @@ -2,7 +2,7 @@ import * as fs from 'fs'; import { Settings } from '../utils/types'; export function settingsParser() { -const rawSettingsData = fs.readFileSync('../../settings.json', 'utf8'); +const rawSettingsData = fs.readFileSync('settings.json', 'utf8'); const settingsData: { settings: Settings } = JSON.parse(rawSettingsData); return settingsData.settings; From 92ae72d3b0e66ec18754060f54beb934f978434a Mon Sep 17 00:00:00 2001 From: unknownpersonog Date: Thu, 19 Oct 2023 15:33:05 +0530 Subject: [PATCH 19/20] Removed settings.json and switched to env. --- .env-example | 8 +++++++- src/routes/users/verify/index.ts | 14 ++++++-------- src/services/settingsParser.ts | 9 --------- src/utils/types.ts | 14 +------------- 4 files changed, 14 insertions(+), 31 deletions(-) delete mode 100644 src/services/settingsParser.ts diff --git a/.env-example b/.env-example index 33aa8d9..70002ad 100644 --- a/.env-example +++ b/.env-example @@ -1,4 +1,10 @@ PORT=3001 ENVIRONMENT= MONGODB_DATABASE_URI= -ADMIN_TOKEN= \ No newline at end of file +ADMIN_TOKEN= +COMPANY= +SMTP_HOST= +SMTP_USER= +SMTP_PASS= +SMTP_MAIL= +SMTP_PORT= \ No newline at end of file diff --git a/src/routes/users/verify/index.ts b/src/routes/users/verify/index.ts index 2531d2a..5820d1e 100644 --- a/src/routes/users/verify/index.ts +++ b/src/routes/users/verify/index.ts @@ -2,7 +2,6 @@ import { config } from 'dotenv' import { Request, Response, Router } from "express"; import nodemailer from 'nodemailer'; import { DiscordAPI } from "../../../database/schemas"; -import { settingsParser } from '../../../services/settingsParser'; config(); const router = Router(); @@ -27,19 +26,18 @@ router.post('/mail', async(req: Request, res: Response) => { { verificationToken, verificationTokenExpiresAt: expiresAt } ); - const settings = settingsParser(); const transporter = nodemailer.createTransport({ - host: String(settings.smtp.host), - port: Number(settings.smtp.port), + host: String(process.env.SMTP_HOST), + port: Number(process.env.SMTP_PORT), secure: false, // upgrade later with STARTTLS auth: { - user: String(settings.smtp.user), - pass: String(settings.smtp.pass), + user: String(process.env.SMTP_USER), + pass: String(process.env.SMTP_PASS), }, }); const mailOptions = { - from: `${settings.companyName} <${settings.smtp.mail}>`, + from: `${process.env.COMPANY} <${process.env.SMTP_MAIL}>`, to: email, subject: 'Email Verification', text: `Your code for verification is: @@ -78,7 +76,7 @@ router.post('/mail', async(req: Request, res: Response) => {

Please use the verification code below to sign in.

${verificationToken}

If you didn’t request this, you can ignore this email.

-

Thanks,
${settings.companyName}

+

Thanks,
${process.env.COMPANY}

Date: Thu, 19 Oct 2023 15:55:00 +0530 Subject: [PATCH 20/20] Version Upgrade, README and removed traces of settings.json --- README.md | 8 +++----- settings.json.example | 10 ---------- version.txt | 2 +- 3 files changed, 4 insertions(+), 16 deletions(-) delete mode 100644 settings.json.example diff --git a/README.md b/README.md index 4ed1639..b6d4945 100644 --- a/README.md +++ b/README.md @@ -59,11 +59,7 @@ This guide considers you have Node 16 or 18 installed and you are doing all thin ```bash nano .env ``` -##### Step 10 - Create a settings.json file and fill the required details from example settings.json in the repository -```bash - nano settings.json -``` -##### Step 11 - Run the API +##### Step 10 - Run the API ```bash node index.js ``` @@ -142,3 +138,5 @@ This guide considers you have Node 16 or 18 installed and you are doing all thin | Parameter | Type | Description | | :-------- | :------- | :-------------------------------- | | `discordId` | `string` | **Required**. Discord ID to assign VPS to. | + +### These API routes can change without being updated on every updated, check code for better infomation \ No newline at end of file diff --git a/settings.json.example b/settings.json.example deleted file mode 100644 index 0e4e5a6..0000000 --- a/settings.json.example +++ /dev/null @@ -1,10 +0,0 @@ -{ - "companyName": "Company Name goes here..", - "smtp": { - "host": "SMTP Host goes here", - "port": "SMTP Port goes here", - "user": "SMTP User goes here", - "pass": "SMTP Password goes here", - "mail": "SMTP Mail goes here" - } -} \ No newline at end of file diff --git a/version.txt b/version.txt index 6085e94..23aa839 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.2.1 +1.2.2