Skip to content

Commit

Permalink
📚Added use of homium-lib
Browse files Browse the repository at this point in the history
  • Loading branch information
VoDACode committed Sep 26, 2023
1 parent 222cd00 commit 91e92c0
Show file tree
Hide file tree
Showing 64 changed files with 1,687 additions and 1,790 deletions.
18 changes: 11 additions & 7 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@
"version": "0.2.0",
"configurations": [
{
"name": "ts-node",
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/backend/src/index.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"skipFiles": ["<node_internals>/**"],
"outFiles": [
"${workspaceFolder}/backend/dist/**/*.js"
]
"args": [
"${relativeFile}"
],
"runtimeArgs": [
"-r",
"ts-node/register"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
}
]
}
834 changes: 736 additions & 98 deletions backend/package-lock.json

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
},
"homepage": "https://github.com/VoDACode/Homium#readme",
"dependencies": {
"@types/express": "^4.17.15",
"@types/express": "^4.17.18",
"@types/express-ws": "^3.0.1",
"@types/node": "^18.11.18",
"archiver": "^5.3.1",
Expand All @@ -41,9 +41,10 @@
"express-ws": "^5.0.2",
"extract-zip": "^2.0.1",
"fs-extra": "^11.1.1",
"homium-lib": "^1.1.2",
"http-proxy-middleware": "^2.0.6",
"ip": "^2.0.0",
"mongodb": "^4.13.0",
"mongodb": "^6.1.0",
"mqtt": "^4.3.7",
"node-downloader-helper": "^2.1.9",
"node-telegram-bot-api": "^0.61.0",
Expand All @@ -67,6 +68,7 @@
"rimraf": "^3.0.2",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.4"
"typescript": "^4.9.4",
"typescript-node": "^0.1.3"
}
}
45 changes: 24 additions & 21 deletions backend/src/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,13 @@ import { exec } from 'child_process';
import express from 'express';
import fs from 'fs-extra';
import path from 'path';
import { IExtension } from './types/IExtension';
import extensions from './services/extensions';
import db from './db';
import { UserModel } from './models/UserModel';
import { uuid } from 'uuidv4';
import { ExtensionModel } from './models/ExtensionModel';
import { Logger, logService } from './services/LogService';

import { DownloaderHelper } from 'node-downloader-helper';
import extract from 'extract-zip'


const logger = new Logger('boot');
import { serviceManager, IDatabaseService, ILogService, ILogger, IExtensionsService } from 'homium-lib/services';
import { ExtensionModel, UserModel } from 'homium-lib/models';
import { Extension } from 'homium-lib/extension';

export function bootExtensions(app: express.Application) {
return _bootExtensions(app, 'all');
Expand All @@ -25,6 +19,7 @@ export function bootNewExtensions(app: express.Application) {
}

export function loadControllers(app: express.Application) {
const logger = serviceManager.get(ILogger, 'Boot');
logger.info('Loading controllers...');
const controllersPath = path.join(__dirname, 'controllers');
fs.readdirSync(controllersPath).forEach((file) => {
Expand All @@ -51,27 +46,32 @@ export function loadControllers(app: express.Application) {
}

export async function firstStart() {
const logger = serviceManager.get(ILogger, 'Boot');
let firstStart = false;
logger.info('Checking first start...');
const db = serviceManager.get(IDatabaseService);
if (await db.users.countDocuments() === 0) {
logger.info('First start detected. Creating root user...');
let root = new UserModel("root", "toor", undefined, undefined, UserModel.getTemplatePermissions('admin'));
await db.users.insertOne(root);
firstStart = true;
}
if (firstStart) {
logger.info('First start detected. Creating new linux user...');
exec('useradd -m -s /bin/bash -p $(openssl passwd -1 toor) homium', (err, stdout, stderr) => {
if (err) {
logger.error('Error while creating linux user: ' + err);
}
logger.info('Linux user created.');
});
}
// if (firstStart) {
// logger.info('First start detected. Creating new linux user...');
// exec('useradd -m -s /bin/bash -p $(openssl passwd -1 toor) homium', (err, stdout, stderr) => {
// if (err) {
// logger.error('Error while creating linux user: ' + err);
// }
// logger.info('Linux user created.');
// });
// }
logger.info('First start check complete.');
}

export async function checkForUpdates() {
const logger = serviceManager.get(ILogger, 'Boot');
let logService = serviceManager.get(ILogService);

let subDir = '';
let installPath = path.join(__dirname, '..', '..', '..');
let newVersion = '';
Expand Down Expand Up @@ -345,8 +345,11 @@ export async function checkForUpdates() {
}

function _bootExtensions(app: express.Application, mode: 'onlyNew' | 'all') {
const logger = serviceManager.get(ILogger, 'Boot');
logger.info('Booting extensions...');
const extensionsPath = path.join(__dirname, 'extensions');
const db = serviceManager.get(IDatabaseService);
const extensions = serviceManager.get(IExtensionsService);
fs.readdirSync(extensionsPath).forEach(async (file) => {
let isExist = false;
let firstStart = false;
Expand Down Expand Up @@ -420,9 +423,9 @@ function _bootExtensions(app: express.Application, mode: 'onlyNew' | 'all') {

if (!isExist) {
const original = new (require(path.join(extensionsPath, file)))(packageJson.id);
const extension: IExtension = original as IExtension;
if (!(original.__proto__ instanceof IExtension)) {
logger.warn(`Extension ${file} is not extending IExtension. Skipping...`);
const extension: Extension = original as Extension;
if (!(original.__proto__ instanceof Extension)) {
logger.warn(`Extension ${file} is not extending Extension. Skipping...`);
return;
}
logger.info(`Extension ${file} booted.`);
Expand Down
2 changes: 1 addition & 1 deletion backend/src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express from 'express';
import { authGuard, refresh, signin, signout } from '../guards/AuthGuard';
import { authGuard, refresh, signin, signout } from 'homium-lib/utils/auth-guard';
const router = express.Router();

router.post('/signin', signin);
Expand Down
28 changes: 19 additions & 9 deletions backend/src/controllers/bot.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import express from 'express';
import { uuid } from 'uuidv4';
import db from '../db';
import { authGuard, getPermissions, getUser } from '../guards/AuthGuard';
import { BotModel, BotViewModel } from '../models/BotModel';
import crypto, { Hash } from 'crypto';
import { ClientPermissions } from '../models/ClientPermissions';
import { UserModel } from '../models/UserModel';
import { authGuard, getPermissions, getUser } from 'homium-lib/utils/auth-guard';
import crypto from 'crypto';
import { fetch } from 'cross-fetch';
import { serviceManager, IDatabaseService } from 'homium-lib/services';
import { BotModel, BotViewModel } from 'homium-lib/models/bot.model';
import { UserModel } from 'homium-lib/models';
import { ClientPermissions } from 'homium-lib/models/permission.model';


const router = express.Router();
Expand All @@ -21,6 +21,7 @@ router.get('/list', authGuard, async (req, res) => {
res.status(403).send("Permission denied!");
return;
}
const db = serviceManager.get(IDatabaseService);
res.send(await db.bots.find({}).map((bot) => new BotViewModel(bot)).toArray());
});

Expand All @@ -30,6 +31,7 @@ router.get('/list/:id', authGuard, async (req, res) => {
res.status(403).send("Permission denied!");
return;
}
const db = serviceManager.get(IDatabaseService);
let bot = await db.bots.findOne({ id: req.params.id });
if (!bot) {
res.status(404).send("Bot not found!");
Expand All @@ -45,6 +47,8 @@ router.post('/create', authGuard, async (req, res) => {
return;
}

const db = serviceManager.get(IDatabaseService);

const name = req.body.name;
const description = req.body.description || "";
const isActivated = req.body.isActivated || true;
Expand Down Expand Up @@ -107,6 +111,7 @@ router.get('/getApiKey/:id', authGuard, async (req, res) => {
res.status(403).send("Permission denied!");
return;
}
const db = serviceManager.get(IDatabaseService);
let bot = await db.bots.findOne({ id: req.params.id });
if (!bot) {
res.status(404).send("Bot not found!");
Expand All @@ -121,6 +126,7 @@ router.put('/regenerate/:id', authGuard, async (req, res) => {
res.status(403).send("Permission denied!");
return;
}
const db = serviceManager.get(IDatabaseService);
let bot = await db.bots.findOne({ id: req.params.id });
if (!bot) {
res.status(404).send("Bot not found!");
Expand All @@ -145,6 +151,8 @@ router.put('/update', authGuard, async (req, res) => {
return;
}

const db = serviceManager.get(IDatabaseService);

const id: string | undefined = req.body.id;
const name: string | undefined = req.body.name;
const description: string = req.body.description ?? "";
Expand Down Expand Up @@ -206,6 +214,8 @@ router.delete('/delete', authGuard, async (req, res) => {
return;
}

const db = serviceManager.get(IDatabaseService);

let bot = await db.bots.findOne({ id: id });
if (!bot) {
res.status(404).send("Bot not found!");
Expand Down Expand Up @@ -275,7 +285,7 @@ router.get('/oath2/verify', authGuard, async (req, res) => {
let key: string = req.query.code as string;
let event = req.query.event as string;

if(!key || !event) {
if (!key || !event) {
res.send({
message: "Missing required fields",
success: false
Expand All @@ -286,8 +296,8 @@ router.get('/oath2/verify', authGuard, async (req, res) => {
let oauth2Key = oauth2Keys.get(key);
if (oauth2Key !== undefined && oauth2Key.event === event) {
let code = crypto.randomBytes(Math.ceil(OATH2_KEY_LENGTH / 2))
.toString('hex')
.slice(0, OATH2_KEY_LENGTH);
.toString('hex')
.slice(0, OATH2_KEY_LENGTH);
oauth2Key.callback(code, null);
res.send({
code: code,
Expand Down
19 changes: 15 additions & 4 deletions backend/src/controllers/extensions.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import * as express from "express";
import { authGuard, hasPermission } from "../guards/AuthGuard";
import extensions from "../services/extensions";
import { authGuard, hasPermission } from 'homium-lib/utils/auth-guard';
import { serviceManager, IExtensionsService } from "homium-lib/services";

const router = express.Router();

router.get("/", authGuard, (req, res) => {
router.get("/", authGuard, async (req, res) => {
if (await hasPermission(req, p => p.extensions.read) == false) {
res.status(403).send("Permission denied").end();
return;
}

const extensions = serviceManager.get(IExtensionsService);

let list: any = extensions.allInfo;
for (let i = 0; i < list.length; i++) {
delete list[i]["_id"];
delete list[i].storage;
list[i].urls = {
static: `${req.headers.host}/extensions/${list[i].id}/static/`,
Expand All @@ -23,12 +31,14 @@ router.get("/:id", authGuard, async (req, res) => {
}

let id = req.params.id;
const extensions = serviceManager.get(IExtensionsService);
let info: any = extensions.allInfo.find(e => e.id == id);
if (!info) {
res.status(404).send("Extension not found").end();
return;
}


delete info["_id"];
delete info.storage;
info.urls = {
static: `${req.headers.host}/extensions/${info.id}/static/`,
Expand All @@ -45,6 +55,7 @@ router.get("/:id/events", authGuard, async (req, res) => {
}

let id = req.params.id;
const extensions = serviceManager.get(IExtensionsService);
let extension = extensions.get(id, 'id');
if (!extension) {
res.status(404).send("Extension not found").end();
Expand Down
5 changes: 3 additions & 2 deletions backend/src/controllers/menu.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import express from 'express';
import { authGuard } from '../guards/AuthGuard';
import extensions from '../services/extensions';
import { authGuard } from 'homium-lib/utils/auth-guard';
import { serviceManager, IExtensionsService } from 'homium-lib/services';

const router = express.Router();

router.get('/extensions', authGuard, async (req, res) => {
const extensions = serviceManager.get(IExtensionsService);
res.status(200).send(extensions.allInfo);
});

Expand Down
Loading

0 comments on commit 91e92c0

Please sign in to comment.