Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

Setup new backend

Smaug67399226bc944536
diff --git a/backend-old/.env.example b/backend-old/.env.example
new file mode 100644
index 00000000..60fe6ba6
--- /dev/null
+++ b/backend-old/.env.example
@@ -0,0 +1,8 @@
+PORT=3001
+DATABASE_USER=
+DATABASE_PASSWORD=
+NODE_ENV=development
+JWT_SECRET=
+
+DOMAIN_CLIENT=http://domain:port
+FRONT_DOMAIN=domain
\ No newline at end of file
diff --git a/backend-old/.gitignore b/backend-old/.gitignore
new file mode 100644
index 00000000..3080cc13
--- /dev/null
+++ b/backend-old/.gitignore
@@ -0,0 +1,21 @@
+#Nodejs
+node_modules
+
+#Public dir
+public/uploads/images/*
+public/uploads/webp/*
+
+!public/uploads/images/default
+!public/uploads/webp/default
+
+#ENV
+.env
+.env.development
+.env.production
+
+#Config
+prod.config.ts
+prod.config.js
+
+#Build
+dist
\ No newline at end of file
diff --git a/backend-old/.prettierrc b/backend-old/.prettierrc
new file mode 100644
index 00000000..77f27419
--- /dev/null
+++ b/backend-old/.prettierrc
@@ -0,0 +1,7 @@
+{
+ "singleQuote": true,
+ "printWidth": 130,
+ "trailingComma": "all",
+ "endOfLine": "lf",
+ "arrowParens": "avoid"
+}
diff --git a/backend-old/App.ts b/backend-old/App.ts
new file mode 100644
index 00000000..8ed529d1
--- /dev/null
+++ b/backend-old/App.ts
@@ -0,0 +1,74 @@
+import { readdirSync } from 'fs';
+import { join } from 'path';
+import express from 'express';
+import { Pool } from 'mysql2';
+import type { Request, Response } from 'express';
+
+import db from './models/db';
+import Logger from './utils/Logger';
+import { checkAndChange } from './utils/functions';
+import { Snowflake } from './utils/Snowflake';
+import type { config } from './config';
+
+export class App {
+ private app;
+ public port: string;
+ public snowflake: Snowflake;
+ public db: Pool;
+ public config: typeof config;
+ public logger: typeof Logger;
+
+ constructor(c: typeof config) {
+ Logger.debug(`Starting in ${process.env.NODE_ENV} mode...`);
+ this.logger = Logger;
+ this.config = c;
+ this.app = express();
+ this.port = process.env.PORT || '3000';
+ this.snowflake = new Snowflake(1661327668261);
+ this.db = db('127.0.0.1', process.env.DATABASE_USER, process.env.DATABASE_PASSWORD, 'alexandrie', 3306);
+ }
+ private async handleRoutes() {
+ const directories = readdirSync(join(__dirname, 'routes'));
+ for (const dir of directories) {
+ const routes = readdirSync(join(__dirname, `routes/${dir}`)).filter(file => file.endsWith('.js') || file.endsWith('.ts'));
+ for (const file of routes) {
+ const getFile = (await import(join(__dirname, `routes/${dir}/${file}`))).default;
+ const fileInfos = getFile(this) as Iroute;
+ this.app.use(`/api/v${fileInfos.version}/${fileInfos.route}`, fileInfos.router());
+ Logger.info(`Loaded route:`, `/api/v${fileInfos.version}/${fileInfos.route}`);
+ }
+ }
+ }
+ private handleMiddlewares(): void {
+ this.app.use(express.urlencoded({ extended: true, limit: `20mb` }));
+ this.app.use(express.json({ limit: `20mb` }));
+ this.app.set('trust proxy', true);
+ this.app.use(function (req: Request, res: Response, next: Function) {
+ const origin = req.headers.origin;
+ if (!origin || ![process.env.DOMAIN_CLIENT, process.env.DOMAIN_DASHBOARD].includes(origin)) return next();
+ res.setHeader('Access-Control-Allow-Origin', origin);
+ res.setHeader(
+ 'Access-Control-Allow-Headers',
+ 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',
+ );
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
+ next();
+ });
+ if (process.env.NODE_ENV !== 'production') {
+ Logger.warn('Morgan is enabled in development mode.');
+ const morgan = require('morgan')('dev');
+ this.app.use(morgan);
+ }
+ }
+ public async start() {
+ this.handleMiddlewares();
+ await this.handleRoutes();
+ this.app.listen(this.port, () => {
+ Logger.success(`Started on port ${this.port}`);
+ });
+ this.app.all('*', (_: Request, res: Response) => {
+ res.status(404).json(checkAndChange(new Error('404 not found')));
+ });
+ }
+}
diff --git a/backend-old/bun.lockb b/backend-old/bun.lockb
new file mode 100755
index 00000000..b071c123
Binary files /dev/null and b/backend-old/bun.lockb differ
diff --git a/backend-old/classes/BackupManager.ts b/backend-old/classes/BackupManager.ts
new file mode 100644
index 00000000..2535a984
--- /dev/null
+++ b/backend-old/classes/BackupManager.ts
@@ -0,0 +1,22 @@
+import Base from './Base';
+import { JsonStreamStringify } from 'json-stream-stringify';
+import { createWriteStream } from 'fs';
+import { Validator } from './Validator';
+
+export class BackupManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({});
+
+ public saveBackup(user_id: string, file_path: string) {
+ return new Promise((resolve, reject) => {
+ const stream = this.app.db.query('SELECT * from `documents` WHERE `author_id` = ?', [user_id]).stream();
+ const writeStream = createWriteStream(file_path);
+ new JsonStreamStringify(stream).pipe(writeStream).on('error', (err: Error) => reject(err));
+
+ writeStream.on('finish', () => resolve(file_path));
+ });
+ }
+}
diff --git a/backend-old/classes/Base.ts b/backend-old/classes/Base.ts
new file mode 100644
index 00000000..672d88ae
--- /dev/null
+++ b/backend-old/classes/Base.ts
@@ -0,0 +1,14 @@
+import { App } from '../App';
+import Validator from './Validator';
+
+export default abstract class Base {
+ // Define the app main class
+ readonly app: App;
+
+ constructor(app: App) {
+ if (!app) throw new Error('App is not defined');
+ this.app = app;
+ }
+
+ public abstract validator: Validator;
+}
diff --git a/backend-old/classes/CategoriesManager.ts b/backend-old/classes/CategoriesManager.ts
new file mode 100644
index 00000000..43c89a41
--- /dev/null
+++ b/backend-old/classes/CategoriesManager.ts
@@ -0,0 +1,85 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { Category, CategoryDB } from '../types';
+
+export class CategoriesManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'category id invalid' },
+ name: { minLength: 1, maxLength: 50, type: 'string', error: 'category name invalid' },
+ icon: { maxLength: 10_000, type: 'string', error: 'category icon invalid', optional: true },
+ order: { type: 'number', error: 'category order invalid', optional: true },
+ role: { type: 'number', minLength: 1, maxLength: 2, error: 'category role invalid' },
+ workspace_id: { maxLength: 50, type: 'string', error: 'category workspace id invalid', optional: true },
+ parent_id: { maxLength: 50, type: 'string', error: 'category parent id invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'category author id invalid' },
+ });
+
+ public getAll(author_id: Category['author_id']): Promise<Category[]> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<CategoryDB[]>(
+ 'SELECT * FROM `categories` WHERE `author_id` = ? ORDER BY `order`',
+ [author_id],
+ (err, themes) => {
+ if (err) return reject('Internal database error.');
+ resolve(themes);
+ },
+ );
+ });
+ }
+ public get(id: Category['id'], author_id: Category['author_id']): Promise<Category | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<CategoryDB[]>(
+ 'SELECT * FROM `categories` WHERE `id` = ? AND `author_id` = ?',
+ [id, author_id],
+ (err, themes) => {
+ if (err) return reject('Internal database error.');
+ resolve(themes[0]);
+ },
+ );
+ });
+ }
+
+ public add(data: Category): Promise<Category> {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query(
+ 'INSERT INTO categories (`id`, `name`,`icon`, `order`, `role`, `workspace_id`, `parent_id`, `author_id`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+ [data.id, data.name, data.icon, data.order, data.role, data.workspace_id, data.parent_id, data.author_id],
+ err => {
+ if (err) return reject('Internal database error.');
+ else resolve(data);
+ },
+ );
+ });
+ }
+
+ update(data: Category): Promise<Category> {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query(
+ 'UPDATE categories SET name = ?, icon = ?, `order` = ?, role = ?, workspace_id = ?, parent_id = ? WHERE id = ?',
+ [data.name, data.icon, data.order, data.role, data.workspace_id, data.parent_id, data.id],
+ err => {
+ if (err) return reject('Internal database error.');
+ else resolve(data);
+ },
+ );
+ });
+ }
+
+ public delete(id: Category['id']): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ if (!id) return reject(new Error('id must be provided'));
+ this.app.db.query('DELETE FROM categories WHERE id = ?', [id], err => {
+ if (err) return reject('Internal database error.');
+ else resolve(true);
+ });
+ });
+ }
+}
diff --git a/backend-old/classes/ConnectionsLogsManager.ts b/backend-old/classes/ConnectionsLogsManager.ts
new file mode 100644
index 00000000..9ce1be51
--- /dev/null
+++ b/backend-old/classes/ConnectionsLogsManager.ts
@@ -0,0 +1,135 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { ConnectionLog, ConnectionLogDB } from '../types';
+
+export class ConnectionsLogsManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log id invalid' },
+ user_id: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log user id invalid' },
+ ip_adress: { maxLength: 50, type: 'string', error: 'connection log ip adress invalid', optional: true },
+ user_agent: { maxLength: 200, type: 'string', error: 'connection log user agent invalid', optional: true },
+ location: { maxLength: 200, type: 'string', error: 'connection log location invalid', optional: true },
+ type: { minLength: 1, maxLength: 10, type: 'string', error: 'connection log type invalid' },
+ timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log timestamp invalid' },
+ });
+
+ public getConnections(user_id: string): Promise<ConnectionLogDB[]> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM connections_logs WHERE user_id = ?',
+ [user_id],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results);
+ },
+ );
+ });
+ }
+ public getLastConnection(user_id: string): Promise<ConnectionLogDB | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM connections_logs WHERE user_id = ? ORDER BY timestamp DESC LIMIT 1',
+ [user_id],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results?.[0]);
+ },
+ );
+ });
+ }
+ public createConnection(connection: ConnectionLog) {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'INSERT INTO connections_logs (id, user_id, ip_adress, user_agent, location, type, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ [
+ connection.id,
+ connection.user_id,
+ connection.ip_adress,
+ connection.user_agent,
+ connection.location,
+ connection.type,
+ connection.timestamp,
+ ],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve(connection);
+ },
+ );
+ });
+ }
+
+ public validate(data: ConnectionLog): string | false {
+ if (!data.id || data.id.length > 50) return 'connection log id invalid';
+ if (!data.user_id || data.user_id.length > 50) return 'connection log user id invalid';
+ if (data.ip_adress && data.ip_adress.length > 50) return 'connection log ip adress invalid';
+ if (data.user_agent && data.user_agent.length > 200) return 'connection log user agent invalid';
+ if (data.location && data.location.length > 200) return 'connection log location invalid';
+ if (!data.type || data.type.length > 10) return 'connection log type invalid';
+ if (!data.timestamp || data.timestamp.length > 50) return 'connection log timestamp invalid';
+ return false;
+ }
+ async getLocationFromIp(ip: string): Promise<string> {
+ const ipType = this.ipType(ip);
+ const location_id = ipType === 'ipv4' ? await this.getLocationIdFromIpV4(ip) : await this.getLocationIdFromIpV6(ip);
+ if (!location_id) return 'Unknown';
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM City_Locations_fr WHERE geoname_id = ?',
+ [location_id],
+ async (err, results) => {
+ if (err) return reject(err);
+ const result = results?.[0];
+ if (!result) return resolve('Unknown');
+ resolve(
+ `${result.city_name ? result.city_name + ', ' : ''}${
+ result.subdivision_1_name ? result.subdivision_1_name + ', ' : ''
+ }${result.country_name ? result.country_name : ''}`,
+ );
+ },
+ );
+ });
+ }
+ private ipType(ip: string): string {
+ if (ip.includes(':')) return 'ipv6';
+ return 'ipv4';
+ }
+ private getLocationIdFromIpV4(ip: string): Promise<string | undefined> {
+ const ip_int = ip
+ .split('.')
+ .map(Number)
+ .reduce((acc, cur, i) => acc + cur * 256 ** (3 - i), 0)
+ .toString();
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM City_IPv4_complete WHERE ? BETWEEN network_start_integer AND network_last_integer',
+ [ip_int],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results?.[0]?.geoname_id);
+ },
+ );
+ });
+ }
+ private getLocationIdFromIpV6(ip: string): Promise<string | undefined> {
+ const ip_int = ip
+ .split(':')
+ .map(str => BigInt(parseInt(str, 16)))
+ .reduce(function (int, value) {
+ return BigInt(int) * BigInt(65536) + BigInt(value);
+ });
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM City_IPv6_complete WHERE ? BETWEEN network_start_integer AND network_last_integer',
+ [ip_int],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results?.[0]?.geoname_id);
+ },
+ );
+ });
+ }
+}
diff --git a/backend-old/classes/DocumentsManager.ts b/backend-old/classes/DocumentsManager.ts
new file mode 100644
index 00000000..5907755f
--- /dev/null
+++ b/backend-old/classes/DocumentsManager.ts
@@ -0,0 +1,127 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { Document, DocumentDB } from '../types';
+
+export class DocumentsManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'Document id invalid' },
+ name: { minLength: 1, maxLength: 50, type: 'string', error: 'Document name invalid' },
+ description: { maxLength: 255, type: 'string', error: 'Document description invalid', optional: true },
+ tags: { maxLength: 200, type: 'string', error: 'Document tags invalid', optional: true },
+ category: { maxLength: 50, type: 'string', error: 'Document category invalid', optional: true },
+ parent_id: { maxLength: 50, type: 'string', error: 'Document parent id invalid', optional: true },
+ accessibility: { minLength: 1, maxLength: 3, type: 'number', error: 'Document accessibility invalid' },
+ content_markdown: { maxLength: 4_294_967_295, type: 'string', error: 'Document content markdown invalid', optional: true },
+ content_html: { maxLength: 4_294_967_295, type: 'string', error: 'Document content html invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'Document author id invalid' },
+ created_timestamp: { maxLength: 50, type: 'string', error: 'Document created timestamp invalid' },
+ updated_timestamp: { maxLength: 50, type: 'string', error: 'Document updated timestamp invalid' },
+ });
+
+ public getAll(user_id: string) {
+ return new Promise<Document[]>((resolve, reject) => {
+ this.app.db.query<DocumentDB[]>(
+ `SELECT id, name, description, tags, category, parent_id, accessibility, author_id, created_timestamp, updated_timestamp FROM documents WHERE author_id = ? ORDER BY name`,
+ [user_id],
+ (err, result) => {
+ if (err) return reject('Internal database error.');
+ resolve(result);
+ },
+ );
+ });
+ }
+
+ public getAllByCategory(category: string) {
+ return new Promise<Document[]>((resolve, reject) => {
+ if (!category) return reject(new Error('category must be provided'));
+ this.app.db.query<DocumentDB[]>(
+ 'SELECT * FROM documents WHERE category = ? AND `accessibility` = 1 ORDER BY `name`',
+ [category],
+ (err, result) => {
+ if (err) return reject('Internal database error.');
+ resolve(result);
+ },
+ );
+ });
+ }
+ get(id: string, author_id: string) {
+ return new Promise<Document | undefined>((resolve, reject) => {
+ this.app.db.query<DocumentDB[]>(
+ 'SELECT * FROM documents WHERE id = ? AND author_id = ?',
+ [id, author_id],
+ (err, result) => {
+ if (err) return reject('Internal database error.');
+ resolve(result[0]);
+ },
+ );
+ });
+ }
+ public add(data: Document) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<DocumentDB[]>(
+ 'INSERT INTO documents (`id`, `name`, `description`, `tags`, `category`, `parent_id`, `accessibility`, `content_markdown`, `content_html`, `author_id`, `created_timestamp`, `updated_timestamp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ [
+ data.id,
+ data.name,
+ data.description,
+ data.tags,
+ data.category,
+ data.parent_id,
+ data.accessibility,
+ data.content_markdown,
+ data.content_html,
+ data.author_id,
+ data.created_timestamp,
+ data.updated_timestamp,
+ ],
+ err => {
+ console.log(err);
+
+ if (err) return reject('Internal database error.');
+ resolve(data);
+ },
+ );
+ });
+ }
+ public put(id: string, data: Omit<Document, 'id' | 'created_timestamp'>) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<DocumentDB[]>(
+ 'UPDATE documents SET name = ?, description = ?, tags = ?, category = ?, parent_id = ?, accessibility = ?, content_markdown = ?, content_html = ?, updated_timestamp = ? WHERE id = ?',
+ [
+ data.name,
+ data.description,
+ data.tags,
+ data.category,
+ data.parent_id,
+ data.accessibility,
+ data.content_markdown,
+ data.content_html,
+ data.updated_timestamp,
+ id,
+ ],
+ err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id, ...data });
+ },
+ );
+ });
+ }
+
+ public delete(id: string) {
+ return new Promise((resolve, reject) => {
+ if (!id) return reject(new Error('id must be provided'));
+ this.app.db.query<DocumentDB[]>('DELETE FROM documents WHERE id = ?', [id], err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
+ }
+}
diff --git a/backend-old/classes/RessourcesManager.ts b/backend-old/classes/RessourcesManager.ts
new file mode 100644
index 00000000..403135fb
--- /dev/null
+++ b/backend-old/classes/RessourcesManager.ts
@@ -0,0 +1,93 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { IObject, Ressource, RessourceDB } from '../types';
+
+export class RessourcesManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource id invalid' },
+ filename: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource filename invalid' },
+ file_size: { type: 'number', error: 'ressource file size invalid' },
+ file_type: { minLength: 1, maxLength: 100, type: 'string', error: 'ressource file type invalid' },
+ original_path: { minLength: 1, maxLength: 100, type: 'string', error: 'ressource original path invalid' },
+ transformed_path: { maxLength: 100, type: 'string', error: 'ressource transformed path invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource author id invalid' },
+ created_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource created timestamp invalid' },
+ });
+
+ public getRessources(user_id: string): Promise<Ressource[]> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<RessourceDB[]>('SELECT * FROM ressources WHERE author_id = ?', [user_id], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results);
+ });
+ });
+ }
+ public getRessource(ressource_id: string): Promise<Ressource | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<RessourceDB[]>('SELECT * FROM ressources WHERE id = ?', [ressource_id], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results[0]);
+ });
+ });
+ }
+
+ public getUserRessourcesSize(user_id: string): Promise<number> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<RessourceDB[]>(
+ 'SELECT SUM(file_size) as size FROM ressources WHERE author_id = ?',
+ [user_id],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results[0]?.size);
+ },
+ );
+ });
+ }
+
+ public createRessource(ressource: Ressource): Promise<IObject> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<RessourceDB[]>(
+ 'INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path,author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+ [
+ ressource.id,
+ ressource.filename,
+ ressource.file_size,
+ ressource.file_type,
+ ressource.original_path,
+ ressource.transformed_path,
+ ressource.author_id,
+ ressource.created_timestamp,
+ ],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve(ressource);
+ },
+ );
+ });
+ }
+
+ public deleteRessource(ressource_id: string): Promise<IObject> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<RessourceDB[]>('DELETE FROM ressources WHERE id = ?', [ressource_id], async err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id: ressource_id });
+ });
+ });
+ }
+
+ public validate(data: Ressource): string | false {
+ if (!data.id || data.id.length > 50) return 'ressource id invalid';
+ if (!data.filename || data.filename.length > 50) return 'ressource filename invalid';
+ if (!data.file_size) return 'ressource file size invalid';
+ if (!data.file_type || data.file_type.length > 100) return 'ressource file type invalid';
+ if (!data.original_path || data.original_path.length > 100) return 'ressource original path invalid';
+ if (data.transformed_path && data.transformed_path.length > 100) return 'ressource transformed path invalid';
+ if (!data.author_id || data.author_id.length > 50) return 'ressource author id invalid';
+ if (!data.created_timestamp || data.created_timestamp.length > 50) return 'ressource created timestamp invalid';
+ return false;
+ }
+}
diff --git a/backend-old/classes/SessionsManager.ts b/backend-old/classes/SessionsManager.ts
new file mode 100644
index 00000000..4d3f2add
--- /dev/null
+++ b/backend-old/classes/SessionsManager.ts
@@ -0,0 +1,110 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { Session, SessionDB } from '../types';
+
+export class SessionsManager extends Base {
+ constructor(app: App) {
+ super(app);
+ this.deleteOldSessions();
+ setInterval(() => this.deleteOldSessions(), 1000 * 60 * 60); // 1 hour
+ }
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'session id invalid' },
+ user_id: { minLength: 1, maxLength: 50, type: 'string', error: 'session user id invalid' },
+ refresh_token: { maxLength: 200, type: 'string', error: 'session refresh token invalid', optional: true },
+ expire_token: { minLength: 1, maxLength: 50, type: 'string', error: 'session expire token invalid' },
+ last_refresh_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last refresh invalid' },
+ active: { type: 'number', error: 'session active invalid' },
+ login_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last login invalid' },
+ logout_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last logout invalid' },
+ });
+
+ public getSession(token: string): Promise<Session | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>('SELECT * FROM sessions WHERE refresh_token = ?', [token], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results[0]);
+ });
+ });
+ }
+ public createConnection(session: Session) {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>(
+ 'INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, login_timestamp, logout_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+ [
+ session.id,
+ session.user_id,
+ session.refresh_token,
+ session.expire_token,
+ session.last_refresh_timestamp,
+ session.active,
+ session.login_timestamp,
+ session.logout_timestamp,
+ ],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve(session);
+ },
+ );
+ });
+ }
+ public updateConnection(session: Session): Promise<Session> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>(
+ 'UPDATE sessions SET refresh_token = ?, expire_token = ?, last_refresh_timestamp = ?, active = ?, login_timestamp = ?, logout_timestamp = ? WHERE id = ?',
+ [
+ session.refresh_token,
+ session.expire_token,
+ session.last_refresh_timestamp,
+ session.active,
+ session.login_timestamp,
+ session.logout_timestamp,
+ session.id,
+ ],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve(session);
+ },
+ );
+ });
+ }
+ deleteSession(refresh_token: string): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>('DELETE FROM sessions WHERE refresh_token = ?', [refresh_token], async err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
+ }
+ markSessionInactive(refresh_token: string): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>('UPDATE sessions SET active = 0 WHERE refresh_token = ?', [refresh_token], async err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
+ }
+ markAllSessionsInactive(user_id: string): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<SessionDB[]>('UPDATE sessions SET active = 0 WHERE user_id = ?', [user_id], async err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
+ }
+
+ deleteOldSessions(): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ this.app.logger.info('[SESSIONS] Deleting old sessions...');
+ this.app.db.query<SessionDB[]>(
+ 'DELETE FROM sessions WHERE expire_token < ? OR active = 0',
+ [Date.now().toString()],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ },
+ );
+ });
+ }
+}
diff --git a/backend-old/classes/UsersManager.ts b/backend-old/classes/UsersManager.ts
new file mode 100644
index 00000000..4d1b3e39
--- /dev/null
+++ b/backend-old/classes/UsersManager.ts
@@ -0,0 +1,119 @@
+import Base from './Base';
+import { Validator } from './Validator';
+import type { User, UserDB } from '../types';
+
+export class UsersManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+
+ public validator = new Validator({
+ id: { maxLength: 50, type: 'string', error: 'user id invalid' },
+ username: { minLength: 5, maxLength: 25, type: 'string', error: 'user username invalid' },
+ firstname: { maxLength: 25, type: 'string', error: 'user firstname invalid', optional: true },
+ lastname: { maxLength: 25, type: 'string', error: 'user lastname invalid', optional: true },
+ role: { minLength: 1, maxLength: 3, type: 'number', error: 'user role invalid' },
+ avatar: { maxLength: 75, type: 'string', error: 'user avatar invalid', optional: true },
+ email: { maxLength: 50, type: 'string', error: 'user email invalid' },
+ password: { maxLength: 255, type: 'string', error: 'user password invalid' },
+ created_timestamp: { maxLength: 50, type: 'string', error: 'user created timestamp invalid' },
+ updated_timestamp: { maxLength: 50, type: 'string', error: 'user updated timestamp invalid' },
+ });
+
+ public get(username: string): Promise<UserDB | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>('SELECT * FROM users WHERE username = ? LIMIT 1', [username], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results[0]);
+ });
+ });
+ }
+ public getAll(): Promise<UserDB[]> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>(
+ 'SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp FROM users ORDER BY created_timestamp',
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results);
+ },
+ );
+ });
+ }
+ public exists(username: string): Promise<boolean> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>('SELECT id FROM users WHERE username = ? LIMIT 1', [username], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(!!results[0]);
+ });
+ });
+ }
+ public getPublic(id: string): Promise<UserDB> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>(
+ 'SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp FROM users WHERE id = ?',
+ [id],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ if (!results[0]) return reject('Bad id.');
+ resolve(results[0]);
+ },
+ );
+ });
+ }
+ public getById(id: string): Promise<UserDB> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>('SELECT * FROM users WHERE id = ?', [id], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ if (!results[0]) return reject('Bad user id.');
+ resolve(results[0]);
+ });
+ });
+ }
+ public post(data: User) {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<UserDB[]>(
+ 'INSERT INTO users (id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ [
+ data.id,
+ data.username,
+ data.firstname,
+ data.lastname,
+ data.role,
+ data.avatar,
+ data.email,
+ data.password,
+ data.created_timestamp,
+ data.updated_timestamp,
+ ],
+ err => {
+ if (err) return reject('Internal database error.');
+ resolve(data);
+ },
+ );
+ });
+ }
+ public put(id: string, data: Omit<User, 'id' | 'password' | 'created_timestamp'>) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<UserDB[]>(
+ 'UPDATE users SET firstname = ?, lastname = ?, avatar = ?, email = ?, updated_timestamp = ? WHERE id = ?',
+ [data.firstname, data.lastname, data.avatar, data.email, data.updated_timestamp, id],
+ err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id, ...data });
+ },
+ );
+ });
+ }
+ public updatePassword(data: Pick<User, 'password' | 'id'>) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<UserDB[]>('UPDATE users SET password = ? WHERE id = ?', [data.password, data.id], err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
+ }
+}
diff --git a/backend-old/classes/Validator.ts b/backend-old/classes/Validator.ts
new file mode 100644
index 00000000..d9b2a738
--- /dev/null
+++ b/backend-old/classes/Validator.ts
@@ -0,0 +1,50 @@
+import Logger from '../utils/Logger';
+type FieldConfig = {
+ minLength?: number;
+ maxLength?: number;
+ type?: 'string' | 'number' | 'boolean';
+ optional?: boolean;
+ error: string;
+};
+
+type ValidationConfig = {
+ [key: string]: FieldConfig;
+};
+
+export class Validator {
+ private config: ValidationConfig;
+
+ constructor(config: ValidationConfig) {
+ this.config = config;
+ }
+
+ public validate(data: Partial<Record<string, any>>): string | false {
+ for (const field in data) {
+ if (!data.hasOwnProperty(field)) continue;
+ const value = data[field];
+ const fieldConfig = this.config[field];
+ if (!fieldConfig) continue; // Skip validation for fields not in the config
+
+ if (fieldConfig.optional && !value) {
+ continue;
+ }
+
+ if (fieldConfig.type && typeof value !== fieldConfig.type) {
+ return fieldConfig.error;
+ }
+
+ if (fieldConfig.minLength && value.length < fieldConfig.minLength) {
+ return fieldConfig.error;
+ }
+
+ if (fieldConfig.maxLength && value.length > fieldConfig.maxLength) {
+ return fieldConfig.error;
+ }
+ }
+ Logger.success(`Validation passed for ${Object.keys(data)}`);
+
+ return false;
+ }
+}
+
+export default Validator;
diff --git a/backend-old/classes/index.ts b/backend-old/classes/index.ts
new file mode 100644
index 00000000..edd8ce98
--- /dev/null
+++ b/backend-old/classes/index.ts
@@ -0,0 +1,7 @@
+export * from './BackupManager';
+export * from './CategoriesManager';
+export * from './ConnectionsLogsManager';
+export * from './SessionsManager';
+export * from './DocumentsManager';
+export * from './RessourcesManager';
+export * from './UsersManager';
diff --git a/backend-old/config.ts b/backend-old/config.ts
new file mode 100644
index 00000000..04bc135a
--- /dev/null
+++ b/backend-old/config.ts
@@ -0,0 +1,12 @@
+import { resolve } from 'path';
+import type ms from 'ms';
+
+export const config = {
+ max_file_size: 20 * 1024 * 1024, // 20MB
+ upload_path: resolve(__dirname, '../uploads'),
+ access_token_expiration: '1800s' as ms.StringValue,
+ access_token_expiration_ms: 1800 * 1000, // 30 minutes
+ refresh_token_expiration: 7 * 24 * 60 * 60 * 1000,
+ // in octets
+ max_user_size: 1000 * 1024 * 1024, // 1GB
+};
diff --git a/backend-old/controllers/BaseController.ts b/backend-old/controllers/BaseController.ts
new file mode 100644
index 00000000..546a5599
--- /dev/null
+++ b/backend-old/controllers/BaseController.ts
@@ -0,0 +1,15 @@
+import * as utils from '../utils';
+import type Base from '../classes/Base';
+
+export default abstract class BaseController<T extends Base> {
+ public app: App;
+
+ protected manager: T;
+
+ protected utils = utils;
+
+ constructor(manager: T) {
+ this.app = manager.app;
+ this.manager = manager;
+ }
+}
diff --git a/backend-old/controllers/article.controller.go b/backend-old/controllers/article.controller.go
new file mode 100644
index 00000000..6661f733
--- /dev/null
+++ b/backend-old/controllers/article.controller.go
@@ -0,0 +1,27 @@
+package controllers
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+)
+
+
+type Person struct {
+ Name string
+ Age int
+ City string
+ Pincode int
+}
+
+func GetDocument(c *gin.Context) {
+ data := Person{
+ Name: "Mark",
+ Age: 30,
+ City: "NY",
+ Pincode: 777,
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "Data": data,
+ })
+}
diff --git a/backend-old/controllers/auth.controller.ts b/backend-old/controllers/auth.controller.ts
new file mode 100644
index 00000000..6e3b4949
--- /dev/null
+++ b/backend-old/controllers/auth.controller.ts
@@ -0,0 +1,157 @@
+import { randomBytes } from 'crypto';
+import { sign } from 'jsonwebtoken';
+import { compare } from 'bcrypt';
+
+import BaseController from './BaseController';
+import { UsersManager, SessionsManager, ConnectionsLogsManager } from '../classes';
+
+import type { Session, User, ConnectionLog } from '../types';
+import type { Request, Response } from 'express';
+
+export default class Authentification extends BaseController<UsersManager> {
+ sessions: SessionsManager;
+ logs: ConnectionsLogsController;
+ constructor(app: App) {
+ super(new UsersManager(app));
+ this.sessions = new SessionsManager(app);
+ this.logs = new ConnectionsLogsController(app);
+ }
+ public async login(req: Request, res: Response) {
+ try {
+ const user = await this.manager.get(req.body.username);
+ if (!user) throw 'Bad username or password.';
+ if (!(await this.check_password(user, req.body.password))) throw 'Bad username or password.';
+ const session: Session = {
+ id: this.app.snowflake.generate().toString(),
+ user_id: user.id,
+ refresh_token: this.generate_refresh_token(),
+ expire_token: (Date.now() + this.app.config.refresh_token_expiration).toString(),
+ last_refresh_timestamp: '0',
+ active: 1,
+ login_timestamp: Date.now().toString(),
+ logout_timestamp: '0',
+ };
+
+ await this.sessions.createConnection(session);
+ const accessToken = this.sign_access_token(user);
+ this.set_cookies(res, accessToken, session.refresh_token);
+ const { password, ...userWithoutPassword } = user;
+ res.status(200).json(this.utils.success({ auth: true, user: userWithoutPassword }));
+ this.logs.add(req, 'login', user.id);
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async logout(req: Request, res: Response) {
+ try {
+ res.clearCookie('user_auth', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_id', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_token', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_refresh_token', { domain: process.env.FRONT_DOMAIN });
+
+ // Mark session as inactive
+ const refreshToken = req.cookies.user_refresh_token;
+ if (refreshToken) await this.sessions.markSessionInactive(refreshToken);
+
+ res.status(200).json(this.utils.success({ auth: false }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async logout_all(req: Request, res: Response) {
+ try {
+ const refreshToken = req.cookies.user_refresh_token;
+ if (!req.user_id) throw 'No user id provided';
+ if (refreshToken) await this.sessions.markAllSessionsInactive(req.user_id);
+ res.clearCookie('user_auth', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_id', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_token', { domain: process.env.FRONT_DOMAIN });
+ res.clearCookie('user_refresh_token', { domain: process.env.FRONT_DOMAIN });
+ res.status(200).json(this.utils.success({ auth: false }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+
+ public async refresh_session(req: Request, res: Response) {
+ this.app.logger.info(`[AUTH] Refreshing access token...`);
+ req.cookies = this.utils.parseCookies(req.headers.cookie);
+ const refreshToken = req.cookies.user_refresh_token;
+ try {
+ if (!refreshToken) throw 'No refresh token provided';
+ // Check if refresh token is valid
+ const session = await this.sessions.getSession(refreshToken);
+ if (!session) throw 'Session not found';
+ if (BigInt(session.expire_token) < Date.now()) throw 'Refresh_token expired';
+
+ // Check if user still exists
+ const user = await this.manager.getById(session?.user_id);
+ if (!user) throw 'User not found'; // if user deleted account
+
+ const new_session: Session = await this.sessions.updateConnection({
+ ...session,
+ refresh_token: this.generate_refresh_token(),
+ expire_token: (Date.now() + this.app.config.refresh_token_expiration).toString(),
+ last_refresh_timestamp: Date.now().toString(),
+ });
+ const accessToken = this.sign_access_token(user);
+ this.set_cookies(res, accessToken, new_session.refresh_token);
+ res.status(200).json(this.utils.success({ auth: true }));
+ this.app.logger.success(`[AUTH] User ${user.username} refreshed token.`);
+ } catch (e) {
+ this.app.logger.error(`[AUTH] Error while refreshing token: ${e}`);
+ //this.sessions.deleteSession(refreshToken);
+ res.status(401).json(this.utils.error(e));
+ }
+ }
+ private async check_password(user: User, password: string): Promise<boolean> {
+ if (!password || !user.password) return false;
+ const valid = await compare(password, user.password);
+ return valid;
+ }
+ private sign_access_token(user: User): string {
+ return sign({ userId: user.id, role: user.role }, process.env.JWT_SECRET || '', {
+ expiresIn: this.app.config.access_token_expiration,
+ });
+ }
+ private generate_refresh_token(): string {
+ return randomBytes(40).toString('hex');
+ }
+ private set_cookies(res: Response, accessToken: string, refreshToken: string): void {
+ res.cookie('user_token', `${accessToken}`, {
+ ...this.utils.COOKIE_CONFIG,
+ maxAge: this.app.config.access_token_expiration_ms,
+ });
+ res.cookie('user_refresh_token', `${refreshToken}`, {
+ ...this.utils.COOKIE_CONFIG,
+ maxAge: this.app.config.refresh_token_expiration,
+ });
+ }
+}
+
+class ConnectionsLogsController extends BaseController<ConnectionsLogsManager> {
+ constructor(app: App) {
+ super(new ConnectionsLogsManager(app));
+ }
+
+ async add(req: Request, type: string, user_id: string) {
+ this.app.logger.info(`[CONNECTIONS LOGS] Adding connection log...`);
+ try {
+ const ip = req.ip || req.headers['x-forwarded-for']?.toString() || req.socket.remoteAddress || '';
+ const location = await this.manager.getLocationFromIp(ip);
+ const connectionLog: ConnectionLog = {
+ id: this.app.snowflake.generate().toString(),
+ user_id,
+ ip_adress: ip,
+ user_agent: req.get('user-agent'),
+ location,
+ type,
+ timestamp: Date.now().toString(),
+ };
+ const err = this.manager.validate(connectionLog);
+ if (!err) this.manager.createConnection(connectionLog);
+ } catch (e) {
+ this.app.logger.error(`[CONNECTIONS LOGS] Error while adding connection log: ${e}`);
+ }
+ }
+}
diff --git a/backend-old/controllers/backups.controller.ts b/backend-old/controllers/backups.controller.ts
new file mode 100644
index 00000000..a58f98dd
--- /dev/null
+++ b/backend-old/controllers/backups.controller.ts
@@ -0,0 +1,45 @@
+import * as fs from 'fs/promises';
+import * as path from 'path';
+import type { Request, Response } from 'express';
+import BaseController from './BaseController';
+import { BackupManager } from '../classes';
+
+export default class BackupController extends BaseController<any> {
+ constructor(app: any) {
+ super(new BackupManager(app));
+ this.app = app;
+ }
+
+ async add(req: Request, res: Response) {
+ const userId = req.user_id;
+ if (!userId) return res.status(401).send({ message: 'Unauthorized' });
+ const date = new Date().toISOString().split('T')[0];
+ const timestamp = Date.now();
+ const name = `backup-${date}-${timestamp}.json`;
+
+ const backupDir = path.join(this.app.config.upload_path, 'backups', userId);
+ const backupFile = path.join(backupDir, name);
+
+ try {
+ // Check if the directory exists
+ try {
+ await fs.access(backupDir);
+ // If directory exists, clean it
+ const files = await fs.readdir(backupDir);
+ await Promise.all(files.map(file => fs.unlink(path.join(backupDir, file))));
+ } catch (error: any) {
+ if (error.code === 'ENOENT') {
+ // If directory does not exist, create it
+ await fs.mkdir(backupDir, { recursive: true });
+ } else {
+ throw error;
+ }
+ }
+
+ await this.manager.saveBackup(userId, backupFile);
+ return res.status(201).json(this.utils.success({ url: `/backups/${req.user_id}/${name}` }));
+ } catch (err) {
+ return res.status(500).json(this.utils.error(err));
+ }
+ }
+}
diff --git a/backend-old/controllers/categories.controller.ts b/backend-old/controllers/categories.controller.ts
new file mode 100644
index 00000000..f6274cbb
--- /dev/null
+++ b/backend-old/controllers/categories.controller.ts
@@ -0,0 +1,58 @@
+import BaseController from './BaseController';
+import { CategoriesManager } from '../classes';
+import type { Request, Response } from 'express';
+
+export default class CategoriesController extends BaseController<CategoriesManager> {
+ constructor(app: App) {
+ super(new CategoriesManager(app));
+ }
+ getAll(req: Request, res: Response) {
+ this.manager
+ .getAll(req.user_id!)
+ .then((result: any) => res.status(200).json(this.utils.success(result)))
+ .catch((err: Error) => res.status(500).json(this.utils.error(err)));
+ }
+
+ add(req: Request, res: Response) {
+ this.manager
+ .add({
+ id: this.app.snowflake.generate().toString(),
+ name: req.body.name,
+ icon: req.body.icon,
+ order: req.body.order || 0,
+ role: req.body.role || 1,
+ parent_id: req.body.parent_id || null,
+ workspace_id: req.body.workspace_id || null,
+ author_id: req.user_id!,
+ })
+ .then(r => res.status(201).json(this.utils.success(r)))
+ .catch(err => res.status(500).json(this.utils.error(err)));
+ }
+
+ async update(req: Request, res: Response) {
+ try {
+ const db_cat = await this.manager.get(req.params.id!, req.user_id!);
+ if (!db_cat) return res.status(404).json(this.utils.error('Category not found or unauthorized.'));
+ const r = await this.manager.update({
+ id: req.params.id!,
+ name: req.body.name,
+ icon: req.body.icon,
+ order: req.body.order,
+ role: req.body.role,
+ parent_id: req.body.parent_id,
+ workspace_id: req.body.workspace_id,
+ author_id: req.user_id!,
+ });
+ return res.status(200).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+
+ delete(req: Request, res: Response) {
+ this.manager
+ .delete(req.params.id!)
+ .then(r => res.status(200).json(this.utils.success(r)))
+ .catch(err => res.status(500).json(this.utils.error(err)));
+ }
+}
diff --git a/backend-old/controllers/cdn.controller.ts b/backend-old/controllers/cdn.controller.ts
new file mode 100644
index 00000000..21b8184f
--- /dev/null
+++ b/backend-old/controllers/cdn.controller.ts
@@ -0,0 +1,112 @@
+import { access, constants, unlink } from 'fs';
+import sharp from 'sharp';
+import BaseController from './BaseController';
+import { RessourcesManager } from '../classes';
+import type { Ressource } from '../types';
+import type { Request, Response } from 'express';
+
+export function convertImageToWebp(upload_path: string, filename: string): Promise<string[]> {
+ return new Promise((resolve, reject) => {
+ const path = `${upload_path}/images/${filename}`;
+ access(path, constants.F_OK, err => {
+ if (err) return reject(new Error('File not found.'));
+ return sharp(path)
+ .toFile(`${upload_path}/webp/${filename.split('.')[0]}.webp`)
+ .then(() => resolve([`/images/${filename}`, `/webp/${filename.split('.')[0]}.webp`]))
+ .catch(() => reject(new Error('Error converting image.')));
+ });
+ });
+}
+export default class RessourcesController extends BaseController<RessourcesManager> {
+ constructor(app: App) {
+ super(new RessourcesManager(app));
+ }
+
+ async get(req: Request, res: Response) {
+ if (!req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ return this.manager
+ .getRessources(req.user_id)
+ .then((result: Ressource[]) => res.status(200).json(this.utils.success(result)))
+ .catch(e => res.status(500).json(this.utils.error(e)));
+ }
+
+ async add(req: Request, res: Response) {
+ try {
+ if (typeof req.files != 'object' || !('file' in req.files) || !req.files.file[0]) {
+ throw new Error('No file provided.');
+ }
+ const file = req.files['file'][0];
+ const filename = file.filename;
+
+ if (!filename) throw new Error('No file provided.');
+ const ressource: Ressource = {
+ id: this.app.snowflake.generate().toString(),
+ filename: file.originalname,
+ file_size: file.size,
+ file_type: file.mimetype,
+ original_path: '',
+ transformed_path: '',
+ author_id: req.user_id!,
+ created_timestamp: Date.now().toString(),
+ };
+ if (Object.keys(this.utils.MIME_TYPES_IMAGE).includes(file.mimetype)) {
+ const converted = await convertImageToWebp(this.app.config.upload_path, filename);
+ ressource.original_path = String(converted[0]);
+ ressource.transformed_path = String(converted[1]);
+ } else ressource.original_path = `/other/${filename}`;
+
+ this.manager
+ .createRessource(ressource)
+ .then(r => res.status(201).json(this.utils.success(r)))
+ .catch(err => res.status(500).json(this.utils.error(err)));
+ } catch (err) {
+ res.status(500).json(this.utils.error(err));
+ }
+ }
+
+ async addAvatar(req: Request, res: Response) {
+ try {
+ if (typeof req.files != 'object' || !('file' in req.files) || !req.files.file[0]) {
+ throw new Error('No file provided.');
+ }
+ const file = req.files['file'][0];
+ const filename = file.filename;
+ if (!filename) throw new Error('No file provided.');
+ if (Object.keys(this.utils.MIME_TYPES_IMAGE).includes(file.mimetype)) {
+ const converted = await convertImageToWebp(this.app.config.upload_path, filename);
+ res.status(201).json(this.utils.success({ original_path: converted[0], transformed_path: converted[1] }));
+ }
+ } catch (err) {
+ res.status(500).json(this.utils.error(err));
+ }
+ }
+
+ async delete(req: Request, res: Response) {
+ if (!req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ if (!req.params.id) return res.status(400).json(this.utils.error('No id provided.'));
+ const ressource = await this.manager.getRessource(req.params.id);
+ if (!ressource) return res.status(404).json(this.utils.error('Ressource not found.'));
+ if (ressource.author_id !== req.user_id) return res.status(403).json(this.utils.error('Unauthorized'));
+ try {
+ await this.manager.deleteRessource(req.params.id);
+ if (ressource.original_path) await deleteFile(`${this.app.config.upload_path}/${ressource.original_path}`);
+ if (ressource.transformed_path) await deleteFile(`${this.app.config.upload_path}/${ressource.transformed_path}`);
+ return res.status(200).json(this.utils.success('Ressource deleted.'));
+ } catch (err) {
+ return res.status(500).json(this.utils.error(err));
+ }
+ }
+}
+
+function deleteFile(path: string): Promise<void> {
+ // Check if file exists and permissions are correct before deleting
+ return new Promise((resolve, reject) => {
+ access(path, constants.F_OK, err => {
+ if (err) return reject(new Error('File not found.'));
+ unlink(path, err => {
+ if (err) return reject(new Error('Error deleting file.'));
+ resolve();
+ });
+ });
+ });
+}
diff --git a/backend-old/controllers/documents.controller.ts b/backend-old/controllers/documents.controller.ts
new file mode 100644
index 00000000..755e9ca3
--- /dev/null
+++ b/backend-old/controllers/documents.controller.ts
@@ -0,0 +1,81 @@
+import BaseController from './BaseController';
+import { DocumentsManager } from '../classes';
+import type { Response, Request } from 'express';
+import type { Document } from '../types';
+
+export default class DocumentsController extends BaseController<DocumentsManager> {
+ constructor(app: App) {
+ super(new DocumentsManager(app));
+ }
+
+ getAllDocuments(req: Request, res: Response) {
+ this.manager
+ .getAll(req.user_id!)
+ .then((result: Partial<Document>[]) => res.status(200).json(this.utils.success(result)))
+ .catch(e => res.status(500).json(this.utils.error(e)));
+ }
+ async getDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ return res.status(200).json(this.utils.success(db_doc));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+ async add(req: Request, res: Response) {
+ const document: Document = {
+ id: this.app.snowflake.generate().toString(),
+ name: req.body.name,
+ description: req.body.description,
+ tags: req.body.tags,
+ category: req.body.category,
+ parent_id: req.body.parent_id,
+ accessibility: req.body.accessibility,
+ content_markdown: req.body.content_markdown,
+ content_html: req.body.content_html,
+ author_id: req.user_id!,
+ created_timestamp: Date.now().toString(),
+ updated_timestamp: Date.now().toString(),
+ };
+ try {
+ const r = await this.manager.add(document);
+ return res.status(201).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+ async updateDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ const result = await this.manager.put(req.params.id as string, {
+ name: req.body.name,
+ description: req.body.description,
+ tags: req.body.tags,
+ category: req.body.category,
+ parent_id: req.body.parent_id,
+ accessibility: req.body.accessibility,
+ content_markdown: req.body.content_markdown,
+ content_html: req.body.content_html,
+ author_id: db_doc.author_id,
+ updated_timestamp: Date.now().toString(),
+ });
+ return res.status(200).json(this.utils.success(result));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+ async deleteDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ return this.manager
+ .delete(req.params.id as string)
+ .then(r => res.status(200).json(this.utils.success(r)))
+ .catch(e => res.status(500).json(this.utils.error(e)));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+}
diff --git a/backend-old/controllers/index.ts b/backend-old/controllers/index.ts
new file mode 100644
index 00000000..4d82bc13
--- /dev/null
+++ b/backend-old/controllers/index.ts
@@ -0,0 +1,5 @@
+export * from './documents.controller';
+export * from './auth.controller';
+export * from './categories.controller';
+export * from './cdn.controller';
+export * from './backups.controller';
diff --git a/backend-old/controllers/stats.controller.ts b/backend-old/controllers/stats.controller.ts
new file mode 100644
index 00000000..4a65e051
--- /dev/null
+++ b/backend-old/controllers/stats.controller.ts
@@ -0,0 +1,10 @@
+import BaseController from './BaseController';
+import { RessourcesManager } from '../classes';
+//import type { Ressource } from '../types';
+//import type { Request, Response } from 'express';
+
+export default class RessourcesController extends BaseController<RessourcesManager> {
+ constructor(app: App) {
+ super(new RessourcesManager(app));
+ }
+}
diff --git a/backend-old/controllers/users.controller.ts b/backend-old/controllers/users.controller.ts
new file mode 100644
index 00000000..a609f0ad
--- /dev/null
+++ b/backend-old/controllers/users.controller.ts
@@ -0,0 +1,108 @@
+import { hash } from 'bcrypt';
+import BaseController from './BaseController';
+import { UsersManager, ConnectionsLogsManager, DocumentsManager } from '../classes';
+import { DEFAULT_DOCUMENT } from '../utils';
+
+import type { Request, Response } from 'express';
+
+export default class Authentification extends BaseController<UsersManager> {
+ connections: ConnectionsLogsManager;
+ documents: DocumentsManager;
+ constructor(app: App) {
+ super(new UsersManager(app));
+ this.connections = new ConnectionsLogsManager(app);
+ this.documents = new DocumentsManager(app);
+ }
+ public async getMe(req: Request, res: Response) {
+ try {
+ const user = await this.manager.getPublic(req.user_id as string);
+ const last_connection = await this.connections.getLastConnection(req.user_id as string);
+ res.status(200).json(this.utils.success({ user, last_connection }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async getById(req: Request, res: Response) {
+ try {
+ const user = await this.manager.getPublic(req.params.id as string);
+ const last_connection = await this.connections.getLastConnection(req.params.id as string);
+ res.status(200).json(this.utils.success({ user, last_connection }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async getAll(_: Request, res: Response) {
+ try {
+ const users = await this.manager.getAll();
+ res.status(200).json(this.utils.success({ users }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async post(req: Request, res: Response) {
+ try {
+ const passwordStr = req.body.password as string;
+ if (!passwordStr) return res.status(400).json(this.utils.error('Password must be provided.'));
+ const hashed = await hash(passwordStr, 10);
+ const user = await this.manager.exists(req.body.username || '');
+ if (user) return res.status(400).json(this.utils.error('Username already taken.'));
+ const data = {
+ id: this.app.snowflake.generate().toString(),
+ username: req.body.username as string,
+ firstname: req.body.firstname as string,
+ lastname: req.body.lastname as string,
+ role: 1,
+ avatar: req.body.avatar as string,
+ email: req.body.email as string,
+ password: hashed,
+ created_timestamp: Date.now().toString(),
+ updated_timestamp: Date.now().toString(),
+ };
+ const error = this.manager.validator.validate(data);
+ if (error) return res.status(400).json(this.utils.error(error));
+ const r = await this.manager.post(data);
+ await this.documents.add({
+ id: this.app.snowflake.generate().toString(),
+ author_id: data.id,
+ created_timestamp: Date.now().toString(),
+ updated_timestamp: Date.now().toString(),
+ ...DEFAULT_DOCUMENT,
+ });
+ return res.status(201).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async update(req: Request, res: Response) {
+ const user_db = await this.manager.getById(req.params.id!);
+ if (!user_db) return res.status(404).json(this.utils.error('User not found.'));
+ if (req.params.id != req.user_id && req.user_role !== 2) return res.status(401).json(this.utils.error('Unauthorized'));
+ return this.manager
+ .put(req.params.id!, {
+ username: user_db.username,
+ firstname: req.body.firstname ?? user_db.firstname,
+ lastname: req.body.lastname ?? user_db.lastname,
+ role: user_db.role,
+ avatar: req.body.avatar ?? user_db.avatar,
+ email: req.body.email ?? user_db.email,
+ updated_timestamp: Date.now().toString(),
+ })
+ .then(r => res.status(200).json(this.utils.success(r)))
+ .catch(e => res.status(500).json(this.utils.error(e)));
+ }
+ public async updatePassword(req: Request, res: Response) {
+ try {
+ const passwordStr = req.body.password as string;
+ if (!passwordStr) return res.status(400).json(this.utils.error('Password must be provided.'));
+ if (req.params.id != req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ const hashed = await hash(passwordStr, 10);
+ const r = await this.manager.updatePassword({
+ id: req.params.id!,
+ password: hashed,
+ });
+ return res.status(200).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
+}
diff --git a/backend-old/custom.d.ts b/backend-old/custom.d.ts
new file mode 100644
index 00000000..b740349c
--- /dev/null
+++ b/backend-old/custom.d.ts
@@ -0,0 +1,6 @@
+declare namespace Express {
+ export interface Request {
+ user_id?: string;
+ user_role?: number;
+ }
+}
diff --git a/backend-old/database/alexandrie.sql b/backend-old/database/alexandrie.sql
new file mode 100644
index 00000000..869fddf7
--- /dev/null
+++ b/backend-old/database/alexandrie.sql
@@ -0,0 +1,243 @@
+-- MySQL dump 10.13 Distrib 8.0.39, for Linux (x86_64)
+--
+-- Host: 127.0.0.1 Database: alexandrie
+-- ------------------------------------------------------
+-- Server version 8.0.39-0ubuntu0.24.04.1
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!50503 SET NAMES utf8mb4 */;
+/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
+/*!40103 SET TIME_ZONE='+00:00' */;
+/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
+/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
+/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
+/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
+
+--
+-- Table structure for table `City_IPv4_complete`
+--
+
+DROP TABLE IF EXISTS `City_IPv4_complete`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `City_IPv4_complete` (
+ `network_start_integer` bigint DEFAULT NULL,
+ `network_last_integer` bigint DEFAULT NULL,
+ `geoname_id` int DEFAULT NULL,
+ `registered_country_geoname_id` int DEFAULT NULL,
+ `represented_country_geoname_id` text,
+ `is_anonymous_proxy` int DEFAULT NULL,
+ `is_satellite_provider` int DEFAULT NULL,
+ `postal_code` text,
+ `latitude` double DEFAULT NULL,
+ `longitude` double DEFAULT NULL,
+ `accuracy_radius` int DEFAULT NULL,
+ `is_anycast` text,
+ KEY `City_IPv4_complete_City_Locations_fr_geoname_id_fk` (`geoname_id`),
+ CONSTRAINT `City_IPv4_complete_City_Locations_fr_geoname_id_fk` FOREIGN KEY (`geoname_id`) REFERENCES `City_Locations_fr` (`geoname_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `City_IPv6_complete`
+--
+
+DROP TABLE IF EXISTS `City_IPv6_complete`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `City_IPv6_complete` (
+ `network_start_integer` double DEFAULT NULL,
+ `network_last_integer` double DEFAULT NULL,
+ `geoname_id` int DEFAULT NULL,
+ `registered_country_geoname_id` int DEFAULT NULL,
+ `represented_country_geoname_id` text,
+ `is_anonymous_proxy` int DEFAULT NULL,
+ `is_satellite_provider` int DEFAULT NULL,
+ `postal_code` text,
+ `latitude` double DEFAULT NULL,
+ `longitude` text,
+ `accuracy_radius` text,
+ `is_anycast` text,
+ KEY `City_IPv6_complete_City_Locations_fr_geoname_id_fk` (`geoname_id`),
+ CONSTRAINT `City_IPv6_complete_City_Locations_fr_geoname_id_fk` FOREIGN KEY (`geoname_id`) REFERENCES `City_Locations_fr` (`geoname_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `City_Locations_fr`
+--
+
+DROP TABLE IF EXISTS `City_Locations_fr`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `City_Locations_fr` (
+ `geoname_id` int NOT NULL,
+ `locale_code` text,
+ `continent_code` text,
+ `continent_name` text,
+ `country_iso_code` text,
+ `country_name` text,
+ `subdivision_1_iso_code` text,
+ `subdivision_1_name` text,
+ `subdivision_2_iso_code` text,
+ `subdivision_2_name` text,
+ `city_name` text,
+ `metro_code` text,
+ `time_zone` text,
+ `is_in_european_union` text,
+ PRIMARY KEY (`geoname_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `categories`
+--
+
+DROP TABLE IF EXISTS `categories`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `categories` (
+ `id` varchar(50) NOT NULL,
+ `name` varchar(50) NOT NULL,
+ `icon` text,
+ `order` int DEFAULT NULL,
+ `role` int default 1 NOT NULL, /* '1 = category; 2 = workspace' */
+ `workspace_id` varchar(50) DEFAULT NULL,
+ `parent_id` varchar(50) DEFAULT NULL,
+ `author_id` varchar(50) NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `categories_categories_id_fk` (`parent_id`),
+ KEY `categories_users_id_fk` (`author_id`),
+ CONSTRAINT `categories_categories_id_fk` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`),
+ CONSTRAINT `categories_users_id_fk` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `connections_logs`
+--
+
+DROP TABLE IF EXISTS `connections_logs`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `connections_logs` (
+ `id` varchar(50) NOT NULL,
+ `user_id` varchar(50) NOT NULL,
+ `ip_adress` varchar(50) DEFAULT NULL,
+ `user_agent` varchar(200) DEFAULT NULL,
+ `location` varchar(100) DEFAULT NULL,
+ `type` varchar(10) NOT NULL,
+ `timestamp` bigint NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `connections_logs_users_id_fk` (`user_id`),
+ CONSTRAINT `connections_logs_users_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `documents`
+--
+
+DROP TABLE IF EXISTS `documents`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `documents` (
+ `id` varchar(50) NOT NULL,
+ `name` varchar(50) NOT NULL,
+ `description` varchar(255) DEFAULT NULL,
+ `tags` varchar(200) DEFAULT NULL,
+ `category` varchar(50) DEFAULT NULL,
+ `parent_id` varchar(50) DEFAULT NULL,
+ `accessibility` tinyint(1) NOT NULL,
+ `content_markdown` longtext,
+ `content_html` longtext,
+ `author_id` varchar(50) NOT NULL,
+ `created_timestamp` bigint NOT NULL,
+ `updated_timestamp` bigint NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `author_id` (`author_id`),
+ KEY `category` (`category`),
+ KEY `documents_ibfk_3` (`parent_id`),
+ CONSTRAINT `documents_ibfk_2` FOREIGN KEY (`category`) REFERENCES `categories` (`id`),
+ CONSTRAINT `documents_ibfk_3` FOREIGN KEY (`parent_id`) REFERENCES `documents` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `documents_users_id_fk` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `ressources`
+--
+
+DROP TABLE IF EXISTS `ressources`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `ressources` (
+ `id` varchar(50) NOT NULL,
+ `filename` varchar(50) NOT NULL,
+ `file_size` int NOT NULL,
+ `file_type` varchar(100) NOT NULL,
+ `original_path` varchar(100) NOT NULL,
+ `transformed_path` varchar(100) DEFAULT NULL,
+ `author_id` varchar(50) NOT NULL,
+ `created_timestamp` bigint NOT NULL,
+ PRIMARY KEY (`id`),
+ KEY `ressources_users_id_fk` (`author_id`),
+ CONSTRAINT `ressources_users_id_fk` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='For CDN';
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `sessions`
+--
+
+DROP TABLE IF EXISTS `sessions`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `sessions` (
+ `id` varchar(50) NOT NULL,
+ `user_id` varchar(50) NOT NULL,
+ `refresh_token` varchar(255) DEFAULT NULL,
+ `expire_token` bigint DEFAULT NULL,
+ `last_refresh_timestamp` bigint DEFAULT NULL,
+ `active` int DEFAULT NULL,
+ `login_timestamp` bigint DEFAULT NULL,
+ `logout_timestamp` bigint DEFAULT NULL,
+ PRIMARY KEY (`id`),
+ KEY `users_auth_users_id_fk` (`user_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
+--
+-- Table structure for table `users`
+--
+
+DROP TABLE IF EXISTS `users`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!50503 SET character_set_client = utf8mb4 */;
+CREATE TABLE `users` (
+ `id` varchar(50) NOT NULL,
+ `username` varchar(25) NOT NULL,
+ `firstname` varchar(25) DEFAULT NULL,
+ `lastname` varchar(25) DEFAULT NULL,
+ `role` int NOT NULL DEFAULT '1' COMMENT '1 = user; 2 = admin',
+ `avatar` varchar(75) DEFAULT NULL,
+ `email` varchar(50) NOT NULL,
+ `created_timestamp` bigint NOT NULL,
+ `password` varchar(255) NOT NULL,
+ `updated_timestamp` bigint NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
+
+/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
+/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
+/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
+/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
+
+-- Dump completed on 2024-08-11 10:57:24
diff --git a/backend-old/global.d.ts b/backend-old/global.d.ts
new file mode 100644
index 00000000..a5624352
--- /dev/null
+++ b/backend-old/global.d.ts
@@ -0,0 +1,6 @@
+declare global {
+ type App = import('./App').App;
+ type Iroute = import('./types').Iroute;
+}
+
+export {};
diff --git a/backend-old/go.mod b/backend-old/go.mod
new file mode 100644
index 00000000..d8a76cfa
--- /dev/null
+++ b/backend-old/go.mod
@@ -0,0 +1,35 @@
+module Smaug6739/Alexandrie
+
+go 1.23.1
+
+require (
+ filippo.io/edwards25519 v1.1.0 // indirect
+ github.com/bytedance/sonic v1.13.1 // indirect
+ github.com/bytedance/sonic/loader v0.2.4 // indirect
+ github.com/cloudwego/base64x v0.1.5 // indirect
+ github.com/cloudwego/iasm v0.2.0 // indirect
+ github.com/gabriel-vasile/mimetype v1.4.8 // indirect
+ github.com/gin-contrib/sse v1.0.0 // indirect
+ github.com/gin-gonic/gin v1.10.0 // indirect
+ github.com/go-playground/locales v0.14.1 // indirect
+ github.com/go-playground/universal-translator v0.18.1 // indirect
+ github.com/go-playground/validator/v10 v10.25.0 // indirect
+ github.com/go-sql-driver/mysql v1.9.1 // indirect
+ github.com/goccy/go-json v0.10.5 // indirect
+ github.com/json-iterator/go v1.1.12 // indirect
+ github.com/klauspost/cpuid/v2 v2.2.10 // indirect
+ github.com/leodido/go-urn v1.4.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+ github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.3 // indirect
+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
+ github.com/ugorji/go/codec v1.2.12 // indirect
+ golang.org/x/arch v0.15.0 // indirect
+ golang.org/x/crypto v0.36.0 // indirect
+ golang.org/x/net v0.37.0 // indirect
+ golang.org/x/sys v0.31.0 // indirect
+ golang.org/x/text v0.23.0 // indirect
+ google.golang.org/protobuf v1.36.5 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
+)
diff --git a/backend-old/go.sum b/backend-old/go.sum
new file mode 100644
index 00000000..8a5584c9
--- /dev/null
+++ b/backend-old/go.sum
@@ -0,0 +1,82 @@
+filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
+filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
+github.com/bytedance/sonic v1.13.1 h1:Jyd5CIvdFnkOWuKXr+wm4Nyk2h0yAFsr8ucJgEasO3g=
+github.com/bytedance/sonic v1.13.1/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
+github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
+github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
+github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
+github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
+github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
+github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
+github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
+github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
+github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=
+github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=
+github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
+github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
+github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
+github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
+github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=
+github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
+github.com/go-sql-driver/mysql v1.9.1 h1:FrjNGn/BsJQjVRuSa8CBrM5BWA9BWoXXat3KrtSb/iI=
+github.com/go-sql-driver/mysql v1.9.1/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
+github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
+github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
+github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
+github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
+github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
+github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
+github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
+github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
+github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
+github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
+github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
+github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
+github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
+github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
+golang.org/x/arch v0.15.0 h1:QtOrQd0bTUnhNVNndMpLHNWrDmYzZ2KDqSrEymqInZw=
+golang.org/x/arch v0.15.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE=
+golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
+golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
+golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
+golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
+golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
+golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
+google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
+google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
diff --git a/backend-old/main.go b/backend-old/main.go
new file mode 100644
index 00000000..f8d8595b
--- /dev/null
+++ b/backend-old/main.go
@@ -0,0 +1,72 @@
+package main
+
+import (
+ "database/sql"
+ "fmt"
+ "time"
+
+ _ "github.com/go-sql-driver/mysql"
+)
+
+func DBConection() (conecction *sql.DB) {
+ Driver := "mysql"
+ User := "root"
+ Password := "root"
+ Host := "localhost"
+ Port := "3306"
+ Database := "alexandrie"
+
+ conection, err := sql.Open(Driver, User+":"+Password+"@tcp("+Host+":"+Port+")/"+Database)
+
+ if err != nil {
+ panic(err.Error())
+ }
+ conection.SetConnMaxLifetime(time.Minute * 3)
+ conection.SetMaxOpenConns(10)
+ conection.SetMaxIdleConns(10)
+ return conection
+}
+func main() {
+ db := DBConection()
+ defer db.Close()
+
+rows, err := db.Query("SELECT * FROM users")
+ if err != nil {
+ // handle error
+ fmt.Println(err)
+ panic(err)
+ }
+ defer rows.Close()
+
+ // process the query results
+ for rows.Next() {
+ // scan the row into a variable
+ var id int
+ var username string
+ var firstname string
+ var lastname string
+ var role string
+ var avatar string
+ var email string
+ var password string
+ var created_timestamp string
+ var updated_timestamp string
+ err = rows.Scan(&id, &username, &firstname,&lastname,&role,&avatar,&email,&password,&created_timestamp,&updated_timestamp)
+ if err != nil {
+ // handle error
+ }
+
+ // do something with the data
+ fmt.Printf("id: %d, name: %s\n", id, username)
+ }
+
+ // check for errors from iterating over rows.Next()
+ if err = rows.Err(); err != nil {
+ // handle error
+ }
+
+ //router.Init()
+
+
+}
+
diff --git a/backend-old/main.ts b/backend-old/main.ts
new file mode 100644
index 00000000..506fa154
--- /dev/null
+++ b/backend-old/main.ts
@@ -0,0 +1,13 @@
+import { resolve } from 'path';
+import { config as constants } from './config';
+import { App } from './App';
+import { config } from 'dotenv';
+
+config({
+ path: resolve(__dirname, '../.env'),
+});
+
+const server: App = new App(constants);
+server.start();
+
+export { server };
diff --git a/backend-old/middlewares/auth.ts b/backend-old/middlewares/auth.ts
new file mode 100644
index 00000000..16ad5e4b
--- /dev/null
+++ b/backend-old/middlewares/auth.ts
@@ -0,0 +1,23 @@
+import { verify } from 'jsonwebtoken';
+import { parseCookies, error } from '../utils';
+import type { Request, Response } from 'express';
+
+if (!process.env.JWT_SECRET) throw 'Missing JWT_SECRET';
+
+export default (req: Request, res: Response, next: Function) => {
+ try {
+ req.cookies = parseCookies(req.headers.cookie);
+ if (!req.cookies) throw 'Missing token cookies.';
+ if (!req.cookies.user_token) throw 'Missing token cookies.';
+ verify(req.cookies.user_token, process.env.JWT_SECRET!, async (err: any, decoded: any) => {
+ if (err) {
+ return res.status(401).json(error('Bad access token.'));
+ }
+ req.user_id = decoded.userId;
+ req.user_role = decoded.role;
+ return next();
+ });
+ } catch (err) {
+ res.status(401).json(error(err));
+ }
+};
diff --git a/backend-old/middlewares/is_admin.ts b/backend-old/middlewares/is_admin.ts
new file mode 100644
index 00000000..b4a18b03
--- /dev/null
+++ b/backend-old/middlewares/is_admin.ts
@@ -0,0 +1,11 @@
+import { error } from '../utils';
+import type { Request, Response } from 'express';
+
+export default (req: Request, res: Response, next: Function) => {
+ try {
+ if (req.user_role !== 2) throw 'Unauthorized';
+ return next();
+ } catch (err) {
+ res.status(403).json(error(err));
+ }
+};
diff --git a/backend-old/middlewares/multer.cdn.ts b/backend-old/middlewares/multer.cdn.ts
new file mode 100644
index 00000000..ce9053a9
--- /dev/null
+++ b/backend-old/middlewares/multer.cdn.ts
@@ -0,0 +1,46 @@
+import multer from 'multer';
+import { RessourcesManager } from '../classes';
+import { server } from '../main';
+import { MIME_TYPES_IMAGE, ACCEPTED_MIME_TYPES } from '../utils/constants';
+import { config } from '../config';
+import type { IObject } from '../types';
+import type { Request } from 'express';
+
+const manager = new RessourcesManager(server);
+
+const storage = multer.diskStorage({
+ destination: (_, file: Express.Multer.File, callback: Function) => {
+ if (Object.keys(MIME_TYPES_IMAGE).includes(file.mimetype)) return callback(null, `${config.upload_path}/images`);
+ callback(null, `${config.upload_path}/other`);
+ },
+ filename: (_, file: IObject, callback: Function) => {
+ const mimetype = file.mimetype as keyof typeof ACCEPTED_MIME_TYPES;
+ const extension = ACCEPTED_MIME_TYPES[mimetype];
+ const fullName = `${Date.now().toString()}.${extension}`;
+ callback(null, fullName);
+ },
+});
+
+export default multer({
+ storage: storage,
+ limits: {
+ fileSize: config.max_file_size,
+ },
+ fileFilter: async (req: Request, file: Express.Multer.File, cb: Function) => {
+ const mimetype = file.mimetype as unknown as keyof typeof ACCEPTED_MIME_TYPES;
+ if (ACCEPTED_MIME_TYPES[mimetype]) {
+ try {
+ const user_size = await manager.getUserRessourcesSize(req.user_id!);
+ if (user_size > config.max_user_size) return cb(new Error('Max upload size reached.'));
+ cb(null, true);
+ } catch {
+ cb(new Error('INTERNAL_ERROR'));
+ }
+ } else cb(new Error('BAD_MIMETYPE'));
+ },
+}).fields([
+ {
+ name: 'file',
+ maxCount: 1,
+ },
+]);
diff --git a/backend-old/models/database.drawio b/backend-old/models/database.drawio
new file mode 100644
index 00000000..3e129d64
--- /dev/null
+++ b/backend-old/models/database.drawio
@@ -0,0 +1,137 @@
+<mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="0" pageScale="1" background="none" math="0" shadow="0">
+ <root>
+ <mxCell id="0" />
+ <mxCell id="1" parent="0" />
+ <mxCell id="node3" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;City_IPv4_complete&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; network_start_integer: bigint&lt;br/&gt; network_last_integer: bigint&lt;br/&gt; geoname_id: int&lt;br/&gt; registered_country_geoname_id: int&lt;br/&gt; represented_country_geoname_id: text&lt;br/&gt; is_anonymous_proxy: int&lt;br/&gt; is_satellite_provider: int&lt;br/&gt; postal_code: text&lt;br/&gt; latitude: double&lt;br/&gt; longitude: double&lt;br/&gt; accuracy_radius: int&lt;br/&gt; is_anycast: text&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="552" y="234" width="274" height="327" as="geometry" />
+ </mxCell>
+ <mxCell id="node2" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;City_IPv6_complete&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; network_start_integer: double&lt;br/&gt; network_last_integer: double&lt;br/&gt; geoname_id: int&lt;br/&gt; registered_country_geoname_id: int&lt;br/&gt; represented_country_geoname_id: text&lt;br/&gt; is_anonymous_proxy: int&lt;br/&gt; is_satellite_provider: int&lt;br/&gt; postal_code: text&lt;br/&gt; latitude: double&lt;br/&gt; longitude: text&lt;br/&gt; accuracy_radius: text&lt;br/&gt; is_anycast: text&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="877" y="234" width="274" height="327" as="geometry" />
+ </mxCell>
+ <mxCell id="node8" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;City_Locations_fr&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; locale_code: text&lt;br/&gt; continent_code: text&lt;br/&gt; continent_name: text&lt;br/&gt; country_iso_code: text&lt;br/&gt; country_name: text&lt;br/&gt; subdivision_1_iso_code: text&lt;br/&gt; subdivision_1_name: text&lt;br/&gt; subdivision_2_iso_code: text&lt;br/&gt; subdivision_2_name: text&lt;br/&gt; city_name: text&lt;br/&gt; metro_code: text&lt;br/&gt; time_zone: text&lt;br/&gt; is_in_european_union: text&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; geoname_id: int&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="990" y="645" width="206" height="376" as="geometry" />
+ </mxCell>
+ <mxCell id="node4" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;categories&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; name: varchar(50)&lt;br/&gt; icon: text&lt;br/&gt; order: int&lt;br/&gt; parent_id: varchar(50)&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; id: varchar(50)&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="43" y="440" width="166" height="160" as="geometry" />
+ </mxCell>
+ <mxCell id="node1" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;connections&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; id: varchar(50)&lt;br/&gt; user_id: varchar(50)&lt;br/&gt; ip_adress: varchar(50)&lt;br/&gt; user_agent: varchar(200)&lt;br/&gt; location: varchar(100)&lt;br/&gt; type: varchar(10)&lt;br/&gt; timestamp: bigint&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="287" y="306" width="186" height="207" as="geometry" />
+ </mxCell>
+ <mxCell id="node7" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;documents&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; name: varchar(50)&lt;br/&gt; description: varchar(255)&lt;br/&gt; tags: varchar(200)&lt;br/&gt; category: varchar(50)&lt;br/&gt; parent_id: varchar(50)&lt;br/&gt; accessibility: tinyint(1)&lt;br/&gt; content_markdown: longtext&lt;br/&gt; content_html: longtext&lt;br/&gt; author_id: varchar(50)&lt;br/&gt; created_timestamp: bigint&lt;br/&gt; updated_timestamp: bigint&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; id: varchar(50)&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="692" y="613" width="208" height="328" as="geometry" />
+ </mxCell>
+ <mxCell id="node5" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;ressources /* For CDN */&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; id: varchar(50)&lt;br/&gt; filename: varchar(50)&lt;br/&gt; file_size: int&lt;br/&gt; file_type: varchar(100)&lt;br/&gt; original_path: varchar(100)&lt;br/&gt; transformed_path: varchar(100)&lt;br/&gt; author_id: varchar(50)&lt;br/&gt; created_timestamp: bigint&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="-168" y="873" width="225" height="231" as="geometry" />
+ </mxCell>
+ <mxCell id="node0" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;users&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; username: varchar(25)&lt;br/&gt; firstname: varchar(25)&lt;br/&gt; lastname: varchar(25)&lt;br/&gt; avatar: varchar(75)&lt;br/&gt; email: varchar(50)&lt;br/&gt; password: varchar(255)&lt;br/&gt; created_timestamp: bigint&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; id: varchar(50)&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="304" y="635" width="190" height="232" as="geometry" />
+ </mxCell>
+ <mxCell id="node6" parent="1" vertex="1" value="&lt;p style=&quot;margin:0px;margin-top:4px;text-align:center;&quot;&gt;&lt;b&gt;users_auth&lt;/b&gt;&lt;/p&gt;&lt;hr size=&quot;1&quot;/&gt;&lt;p style=&quot;margin:0 0 0 4px;line-height:1.6;&quot;&gt; user_id: varchar(50)&lt;br/&gt; refresh_token: varchar(255)&lt;br/&gt; expire_token: bigint&lt;br/&gt; last_login: bigint&lt;br/&gt; last_logout: bigint&lt;/p&gt;" style="verticalAlign=top;align=left;overflow=fill;fontSize=14;fontFamily=Helvetica;html=1;rounded=0;shadow=0;comic=0;labelBackgroundColor=none;strokeWidth=1;">
+ <mxGeometry x="-168" y="635" width="204" height="159" as="geometry" />
+ </mxCell>
+ <mxCell id="edge8" edge="1" value="" parent="1" source="node3" target="node8" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.500;entryY=0.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="689" y="595" />
+ <mxPoint x="1093" y="595" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label50" parent="edge8" vertex="1" connectable="0" value="geoname_id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="744" y="567" as="geometry" />
+ </mxCell>
+ <mxCell id="edge7" edge="1" value="" parent="1" source="node2" target="node8" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=0.000;exitDx=0;exitDy=0;entryX=1.000;entryY=0.422;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="1014" y="213" />
+ <mxPoint x="1282" y="213" />
+ <mxPoint x="1282" y="804" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label44" parent="edge7" vertex="1" connectable="0" value="geoname_id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="1201" y="758" as="geometry" />
+ </mxCell>
+ <mxCell id="edge1" edge="1" value="" parent="1" source="node4" target="node4" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=0.000;exitDx=0;exitDy=0;entryX=0.000;entryY=0.500;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="126" y="336" />
+ <mxPoint x="26" y="336" />
+ <mxPoint x="26" y="520" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label8" parent="edge1" vertex="1" connectable="0" value="parent_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="41" y="336" as="geometry" />
+ </mxCell>
+ <mxCell id="edge6" edge="1" value="" parent="1" source="node1" target="node0" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.250;entryY=1.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="380" y="579" />
+ <mxPoint x="271" y="579" />
+ <mxPoint x="271" y="941" />
+ <mxPoint x="352" y="941" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label38" parent="edge6" vertex="1" connectable="0" value="user_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="283" y="918" as="geometry" />
+ </mxCell>
+ <mxCell id="edge2" edge="1" value="" parent="1" source="node7" target="node4" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.000;exitY=0.195;exitDx=0;exitDy=0;entryX=0.500;entryY=1.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="508" y="677" />
+ <mxPoint x="508" y="619" />
+ <mxPoint x="126" y="619" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label14" parent="edge2" vertex="1" connectable="0" value="category:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="531" y="657" as="geometry" />
+ </mxCell>
+ <mxCell id="edge0" edge="1" value="" parent="1" source="node7" target="node7" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=1.000;exitY=0.500;exitDx=0;exitDy=0;entryX=0.500;entryY=1.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="958" y="777" />
+ <mxPoint x="958" y="1060" />
+ <mxPoint x="796" y="1060" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label2" parent="edge0" vertex="1" connectable="0" value="parent_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="842" y="1028" as="geometry" />
+ </mxCell>
+ <mxCell id="edge3" edge="1" value="" parent="1" source="node7" target="node0" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.250;exitY=1.000;exitDx=0;exitDy=0;entryX=0.750;entryY=1.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="744" y="1060" />
+ <mxPoint x="447" y="1060" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label20" parent="edge3" vertex="1" connectable="0" value="author_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="470" y="1015" as="geometry" />
+ </mxCell>
+ <mxCell id="edge5" edge="1" value="" parent="1" source="node5" target="node0" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.509;entryY=1.000;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="-55" y="1139" />
+ <mxPoint x="401" y="1139" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label32" parent="edge5" vertex="1" connectable="0" value="author_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="138" y="1119" as="geometry" />
+ </mxCell>
+ <mxCell id="edge4" edge="1" value="" parent="1" source="node6" target="node0" style="html=1;rounded=1;edgeStyle=orthogonalEdgeStyle;dashed=0;startArrow=none;endArrow=block;endSize=12;strokeColor=#595959;exitX=0.500;exitY=1.000;exitDx=0;exitDy=0;entryX=0.000;entryY=0.915;entryDx=0;entryDy=0;">
+ <mxGeometry width="50" height="50" relative="1" as="geometry">
+ <Array as="points">
+ <mxPoint x="-66" y="847" />
+ </Array>
+ </mxGeometry>
+ </mxCell>
+ <mxCell id="label26" parent="edge4" vertex="1" connectable="0" value="user_id:id" style="edgeLabel;resizable=0;html=1;align=left;verticalAlign=top;strokeColor=default;">
+ <mxGeometry x="74" y="809" as="geometry" />
+ </mxCell>
+ </root>
+</mxGraphModel>
\ No newline at end of file
diff --git a/backend-old/models/database.png b/backend-old/models/database.png
new file mode 100644
index 00000000..d9380b70
Binary files /dev/null and b/backend-old/models/database.png differ
diff --git a/backend-old/models/db.ts b/backend-old/models/db.ts
new file mode 100644
index 00000000..26e9e5f5
--- /dev/null
+++ b/backend-old/models/db.ts
@@ -0,0 +1,13 @@
+import { createPool } from 'mysql2';
+
+function getConnection(host?: string, user?: string, password?: string, db_name?: string, port?: number) {
+ return createPool({
+ host: host,
+ user: user,
+ password: password,
+ database: db_name,
+ port: port,
+ });
+}
+
+export default getConnection;
diff --git a/backend-old/package.json b/backend-old/package.json
new file mode 100644
index 00000000..b2184e5c
--- /dev/null
+++ b/backend-old/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "docs",
+ "version": "1.0.0",
+ "description": "",
+ "main": "dist/main.js",
+ "scripts": {
+ "start": "bun dist/main.js",
+ "clean": "rm -rf dist && echo 'Done.'",
+ "build": "tsc",
+ "build:watch": "tsc --watch"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Smaug6739/docs.git"
+ },
+ "author": "",
+ "license": "ISC",
+ "bugs": {
+ "url": "https://github.com/Smaug6739/docs/issues"
+ },
+ "homepage": "https://github.com/Smaug6739/docs#readme",
+ "devDependencies": {
+ "@types/bcrypt": "^5.0.2",
+ "@types/bun": "^1.2.4",
+ "@types/express": "^4.17.21",
+ "@types/jsonwebtoken": "^9.0.9",
+ "@types/multer": "^1.4.12",
+ "morgan": "^1.10.0",
+ "nodemon": "^3.1.9",
+ "typescript": "^5.8.2"
+ },
+ "dependencies": {
+ "bcrypt": "^5.1.1",
+ "dotenv": "^16.4.7",
+ "express": "^4.21.2",
+ "json-stream-stringify": "^3.1.6",
+ "jsonwebtoken": "^9.0.2",
+ "multer": "^1.4.5-lts.1",
+ "mysql2": "^3.13.0",
+ "sharp": "^0.33.5",
+ "tslib": "^2.8.1"
+ }
+}
diff --git a/backend-old/router/router.go b/backend-old/router/router.go
new file mode 100644
index 00000000..96175006
--- /dev/null
+++ b/backend-old/router/router.go
@@ -0,0 +1,19 @@
+package router
+
+import (
+ documents "Smaug6739/Alexandrie/router/routes"
+
+ "github.com/gin-gonic/gin"
+)
+
+func Init() {
+ router := NewRouter()
+ router.Run("localhost:8080")
+}
+
+func NewRouter() *gin.Engine {
+ router := gin.New()
+ mainGroup := router.Group("/api")
+ documents.Routes(mainGroup)
+ return router
+}
\ No newline at end of file
diff --git a/backend-old/router/routes/documents.go b/backend-old/router/routes/documents.go
new file mode 100644
index 00000000..8d29f09a
--- /dev/null
+++ b/backend-old/router/routes/documents.go
@@ -0,0 +1,14 @@
+package documents
+
+import (
+ "Smaug6739/Alexandrie/controllers"
+
+ "github.com/gin-gonic/gin"
+)
+
+func Routes(router *gin.RouterGroup) {
+ documents := router.Group("/documents")
+
+ documents.GET("/", controllers.GetDocument)
+
+}
\ No newline at end of file
diff --git a/backend-old/routes/v1/auth.ts b/backend-old/routes/v1/auth.ts
new file mode 100644
index 00000000..7687198e
--- /dev/null
+++ b/backend-old/routes/v1/auth.ts
@@ -0,0 +1,20 @@
+import { Router } from 'express';
+import AuthCtrl from '../../controllers/auth.controller';
+import authMid from '../../middlewares/auth';
+
+const AuthRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ return {
+ route: 'auth',
+ version: 1,
+ router() {
+ const controller = new AuthCtrl(client);
+ AuthRouter.post('/', (req, res) => controller.login(req, res));
+ AuthRouter.get('/refreshToken', (req, res) => controller.refresh_session(req, res));
+ AuthRouter.post('/logout/all', authMid, (req, res) => controller.logout_all(req, res));
+ AuthRouter.post('/logout', authMid, (req, res) => controller.logout(req, res));
+ return AuthRouter;
+ },
+ };
+};
diff --git a/backend-old/routes/v1/backup.ts b/backend-old/routes/v1/backup.ts
new file mode 100644
index 00000000..12a1ef8a
--- /dev/null
+++ b/backend-old/routes/v1/backup.ts
@@ -0,0 +1,17 @@
+import { Router } from 'express';
+import BackupsCtrl from '../../controllers/backups.controller';
+import authMid from '../../middlewares/auth';
+
+const BackupsRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ const controller = new BackupsCtrl(client);
+ return {
+ route: 'backups',
+ version: 1,
+ router() {
+ BackupsRouter.post('', authMid, (req, res) => controller.add(req, res));
+ return BackupsRouter;
+ },
+ };
+};
diff --git a/backend-old/routes/v1/categories.ts b/backend-old/routes/v1/categories.ts
new file mode 100644
index 00000000..774a0f70
--- /dev/null
+++ b/backend-old/routes/v1/categories.ts
@@ -0,0 +1,20 @@
+import { Router } from 'express';
+import CategoriesCtrl from '../../controllers/categories.controller';
+import authMid from '../../middlewares/auth';
+
+const CategoriesRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ const controller = new CategoriesCtrl(client);
+ return {
+ route: 'categories',
+ version: 1,
+ router() {
+ CategoriesRouter.get('/', authMid, (req, res) => controller.getAll(req, res));
+ CategoriesRouter.post('', authMid, (req, res) => controller.add(req, res));
+ CategoriesRouter.patch('/:id', authMid, (req, res) => controller.update(req, res));
+ CategoriesRouter.delete('/:id', authMid, (req, res) => controller.delete(req, res));
+ return CategoriesRouter;
+ },
+ };
+};
diff --git a/backend-old/routes/v1/cdn.ts b/backend-old/routes/v1/cdn.ts
new file mode 100644
index 00000000..d82e3ba4
--- /dev/null
+++ b/backend-old/routes/v1/cdn.ts
@@ -0,0 +1,35 @@
+import { Router, type Request, type Response, NextFunction } from 'express';
+import RessourcesController from '../../controllers/cdn.controller';
+import auth from '../../middlewares/auth';
+import multerCdn from '../../middlewares/multer.cdn';
+import multer from 'multer';
+import { error } from '../../utils/functions';
+
+const CDNRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ const controller = new RessourcesController(client);
+ return {
+ route: 'ressources',
+ version: 1,
+ router() {
+ CDNRouter.get('/', auth, (req: Request, res: Response) => controller.get(req, res));
+ CDNRouter.post('/avatar', auth, multerCdn, (req: Request, res: Response) => controller.addAvatar(req, res), multerErrors);
+ CDNRouter.post('/', auth, multerCdn, (req: Request, res: Response) => controller.add(req, res), multerErrors);
+ CDNRouter.delete('/:id', auth, (req: Request, res: Response) => controller.delete(req, res));
+ return CDNRouter;
+ },
+ };
+};
+
+function multerErrors(err: any, _: Request, res: Response, next: NextFunction) {
+ if (err instanceof multer.MulterError) {
+ if (err.code === 'LIMIT_FILE_SIZE') return res.status(413).json(error('File size is too large.'));
+ else res.status(400).json(error(err.message));
+ }
+ if (err) {
+ if (err.message === 'BAD_MIMETYPE') return res.status(415).json(error('Invalid file format.'));
+ return res.status(400).json(error(err.message));
+ }
+ return next();
+}
diff --git a/backend-old/routes/v1/documents.ts b/backend-old/routes/v1/documents.ts
new file mode 100644
index 00000000..1221eac0
--- /dev/null
+++ b/backend-old/routes/v1/documents.ts
@@ -0,0 +1,21 @@
+import { Router } from 'express';
+import DocumentsCtrl from '../../controllers/documents.controller';
+import authMid from '../../middlewares/auth';
+
+const DocumentsRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ const controller = new DocumentsCtrl(client);
+ return {
+ route: 'documents',
+ version: 1,
+ router() {
+ DocumentsRouter.get('/', authMid, (req, res) => controller.getAllDocuments(req, res));
+ DocumentsRouter.get('/:id', authMid, (req, res) => controller.getDocument(req, res));
+ DocumentsRouter.post('/', authMid, (req, res) => controller.add(req, res));
+ DocumentsRouter.patch('/:id', authMid, (req, res) => controller.updateDocument(req, res));
+ DocumentsRouter.delete('/:id', authMid, (req, res) => controller.deleteDocument(req, res));
+ return DocumentsRouter;
+ },
+ };
+};
diff --git a/backend-old/routes/v1/stats.ts b/backend-old/routes/v1/stats.ts
new file mode 100644
index 00000000..597f8f81
--- /dev/null
+++ b/backend-old/routes/v1/stats.ts
@@ -0,0 +1,18 @@
+import { Router } from 'express';
+//import statsCtrl from '../../controllers/stats.controller';
+//import authMid from '../../middlewares/auth';
+//import isAdmin from '../../middlewares/is_admin';
+
+const UsersRouter: Router = Router();
+
+export default (_: App): Iroute => {
+ //const controller = new statsCtrl(client);
+ return {
+ route: 'stats',
+ version: 1,
+ router() {
+ // UsersRouter.get('/', authMid, isAdmin, (req, res) => {});
+ return UsersRouter;
+ },
+ };
+};
diff --git a/backend-old/routes/v1/users.ts b/backend-old/routes/v1/users.ts
new file mode 100644
index 00000000..90ba00f6
--- /dev/null
+++ b/backend-old/routes/v1/users.ts
@@ -0,0 +1,29 @@
+import { Router } from 'express';
+import UsersCtrl from '../../controllers/users.controller';
+import authMid from '../../middlewares/auth';
+import isAdmin from '../../middlewares/is_admin';
+
+const UsersRouter: Router = Router();
+
+export default (client: App): Iroute => {
+ const controller = new UsersCtrl(client);
+ return {
+ route: 'users',
+ version: 1,
+ router() {
+ UsersRouter.get('/@me', authMid, (req, res) => controller.getMe(req, res));
+ UsersRouter.patch('/:id/password', authMid, (req, res) => controller.updatePassword(req, res));
+ UsersRouter.post('/', (req, res) => controller.post(req, res));
+ UsersRouter.patch('/:id', authMid, (req, res) => controller.update(req, res));
+
+ // Protected routes
+ UsersRouter.get('/:id', authMid, isAdmin, (req, res) => controller.getById(req, res));
+ UsersRouter.get('/', authMid, isAdmin, (req, res) => controller.getAll(req, res));
+ //UsersRouter.get('/:id', authMid, (req, res) => controller.getDocument(req, res));
+ //UsersRouter.post('/', (req, res) => controller.add(req, res));
+ //UsersRouter.patch('/:id', authMid, (req, res) => controller.updateDocument(req, res));
+ //UsersRouter.delete('/:id', authMid, (req, res) => controller.deleteDocument(req, res));
+ return UsersRouter;
+ },
+ };
+};
diff --git a/backend-old/tsconfig.json b/backend-old/tsconfig.json
new file mode 100644
index 00000000..98b204e3
--- /dev/null
+++ b/backend-old/tsconfig.json
@@ -0,0 +1,43 @@
+{
+ // Mapped from https://www.typescriptlang.org/tsconfig
+ "compilerOptions": {
+ // Type Checking
+ "allowUnreachableCode": false,
+ "allowUnusedLabels": false,
+ "exactOptionalPropertyTypes": false,
+ "noFallthroughCasesInSwitch": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "strict": true,
+ "useUnknownInCatchVariables": true,
+ "noUncheckedIndexedAccess": true,
+ // Modules
+ "module": "CommonJS",
+ "moduleResolution": "node",
+ "resolveJsonModule": true,
+ // Emit
+ "importHelpers": true,
+ "inlineSources": true,
+ "newLine": "lf",
+ "noEmitHelpers": true,
+ "outDir": "dist",
+ "preserveConstEnums": true,
+ "removeComments": false,
+ "sourceMap": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "skipLibCheck": true,
+ // Language and Environment
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "lib": ["ESNext"],
+ "target": "ES2021",
+ "useDefineForClassFields": true,
+ // Paths
+ "baseUrl": "./src"
+ },
+ "include": ["**/*", "custom.d.ts", "global.d.ts"],
+ "exclude": ["node_modules", "test", "typings"]
+}
diff --git a/backend-old/types/Structures.d.ts b/backend-old/types/Structures.d.ts
new file mode 100644
index 00000000..a0ac55fb
--- /dev/null
+++ b/backend-old/types/Structures.d.ts
@@ -0,0 +1,117 @@
+import type { RowDataPacket } from 'mysql2';
+
+export interface Document {
+ id: string;
+ name: string;
+ description?: string;
+ tags?: string;
+ category?: string;
+ parent_id?: string;
+ accessibility: number; // 0: No; 1: Yes;
+ content_markdown?: string;
+ content_html?: string;
+ author_id: string;
+ created_timestamp: string;
+ updated_timestamp: string;
+}
+
+export interface Category {
+ id: string;
+ name: string;
+ icon?: string;
+ order?: number;
+ role: number; // 1 Category; 2 Workspace;
+ workspace_id?: string;
+ parent_id?: string;
+ author_id: string;
+}
+
+export interface User {
+ id: string;
+ username: string;
+ firstname?: string;
+ lastname?: string;
+ role: number; // 0: User; 1: Admin;
+ avatar?: string;
+ email: string;
+ password: string;
+ created_timestamp: string;
+ updated_timestamp: string;
+}
+
+export interface Ressource {
+ id: string;
+ filename: string;
+ file_size: number;
+ file_type: string;
+ original_path: string;
+ transformed_path: string;
+ author_id: string;
+ created_timestamp: string;
+}
+
+export interface ConnectionLog {
+ id: string;
+ user_id: string;
+ ip_adress?: string;
+ user_agent?: string;
+ location?: string;
+ type: string;
+ timestamp: string; // BIGINT converted to string
+}
+
+export interface Session {
+ id: string;
+ user_id: string;
+ refresh_token: string;
+ expire_token: string;
+ last_refresh_timestamp: string;
+ active: number; // 0: No; 1: Yes;
+ login_timestamp: string;
+ logout_timestamp: string;
+}
+
+export type DocumentDB = RowDataPacket & Document;
+export type CategoryDB = RowDataPacket & Category;
+export type UserDB = RowDataPacket & User;
+export type RessourceDB = RowDataPacket & Ressource;
+export type ConnectionLogDB = RowDataPacket & ConnectionLog;
+export type SessionDB = RowDataPacket & Session;
+
+// SQL create the documents table (relation between author_id and users.id; relation between category and categories.id)
+/* CREATE TABLE documents (
+ id VARCHAR(50) PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ description VARCHAR(255),
+ tags VARCHAR(255),
+ category VARCHAR(50),
+ accessibility TINYINT(1) NOT NULL,
+ content_markdown LONGTEXT,
+ content_html LONGTEXT,
+ author_id VARCHAR(50) NOT NULL,
+ created_timestamp VARCHAR(50) NOT NULL,
+ updated_timestamp VARCHAR(50) NOT NULL,
+ FOREIGN KEY (author_id) REFERENCES users(id),
+ FOREIGN KEY (category) REFERENCES categories(id)
+); */
+
+// SQL create the categories table (relation between parent_id and categories.id)
+/* CREATE TABLE categories (
+ id VARCHAR(50) PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ icon VARCHAR(255),
+ order INT,
+ parent_id VARCHAR(50),
+ FOREIGN KEY (parent_id) REFERENCES categories(id)
+); */
+// SQL create the users table
+/* CREATE TABLE users (
+ id VARCHAR(50) PRIMARY KEY,
+ username VARCHAR(255) NOT NULL,
+ firstname VARCHAR(255),
+ lastname VARCHAR(255),
+ avatar VARCHAR(255),
+ email VARCHAR(255) NOT NULL,
+ password VARCHAR(255) NOT NULL,
+ created_timestamp VARCHAR(50) NOT NULL
+); */
diff --git a/backend-old/types/index.d.ts b/backend-old/types/index.d.ts
new file mode 100644
index 00000000..eb306e74
--- /dev/null
+++ b/backend-old/types/index.d.ts
@@ -0,0 +1,22 @@
+import type { Router } from 'express';
+
+//Router
+export interface Iroute {
+ route: string;
+ version: number;
+ router: () => Router;
+}
+
+//Response
+export interface IResponse {
+ status: string;
+ timestamp: number;
+ result?: any;
+ message?: string;
+}
+//Object
+export interface IObject {
+ [index: string]: any;
+}
+
+export type * from './Structures';
diff --git a/backend-old/utils/Logger.ts b/backend-old/utils/Logger.ts
new file mode 100644
index 00000000..553f0134
--- /dev/null
+++ b/backend-old/utils/Logger.ts
@@ -0,0 +1,31 @@
+export default class Logger {
+ // Info, Warning, Error, Debug, Success
+ private static colors = {
+ info: '\x1b[36m%s\x1b[0m',
+ warn: '\x1b[33m%s\x1b[0m',
+ error: '\x1b[31m%s\x1b[0m',
+ debug: '\x1b[34m%s\x1b[0m',
+ success: '\x1b[32m%s\x1b[0m',
+ reset: '\x1b[0m',
+ };
+
+ public static info(message: string, details?: string): void {
+ console.log(Logger.colors.info, message, Logger.colors.reset, details ? details : '');
+ }
+
+ public static warn(message: string, details?: string): void {
+ console.log(Logger.colors.warn, message, Logger.colors.reset, details ? details : '');
+ }
+
+ public static error(message: string, details?: string): void {
+ console.log(Logger.colors.error, message, Logger.colors.reset, details ? details : '');
+ }
+
+ public static debug(message: string, details?: string): void {
+ console.log(Logger.colors.debug, message, Logger.colors.reset, details ? details : '');
+ }
+
+ public static success(message: string, details?: string): void {
+ console.log(Logger.colors.success, message, Logger.colors.reset, details ? details : '');
+ }
+}
diff --git a/backend-old/utils/Snowflake.ts b/backend-old/utils/Snowflake.ts
new file mode 100644
index 00000000..99a85733
--- /dev/null
+++ b/backend-old/utils/Snowflake.ts
@@ -0,0 +1,179 @@
+const ProcessId = 1n;
+const WorkerId = 0n;
+
+/**
+ * A class for generating and deconstructing Twitter snowflakes.
+ *
+ * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}
+ * is a 64-bit unsigned integer with 4 result that have a fixed epoch value.
+ *
+ * If we have a snowflake `266241948824764416` we can represent it as binary:
+ * ```
+ * 64 22 17 12 0
+ * 000000111011000111100001101001000101000000 00001 00000 000000000000
+ * number of ms since epoch worker pid increment
+ * ```
+ */
+export class Snowflake {
+ /**
+ * Internal incrementor for generating snowflakes
+ * @internal
+ */
+ #increment = 0n;
+
+ /**
+ * Internal reference of the epoch passed in the constructor
+ * @internal
+ */
+ #epoch: bigint;
+
+ /**
+ * Alias for {@link deconstruct}
+ */
+ // eslint-disable-next-line @typescript-eslint/unbound-method, @typescript-eslint/no-invalid-this
+ public decode = this.deconstruct;
+
+ /**
+ * @param epoch the epoch to use
+ */
+ public constructor(epoch: number | bigint | Date) {
+ this.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);
+ }
+
+ /**
+ * The epoch for this snowflake.
+ */
+ public get epoch(): bigint {
+ return this.#epoch;
+ }
+
+ /**
+ * Generates a snowflake given an epoch and optionally a timestamp
+ * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}
+ *
+ * **note** when `increment` is not provided it defaults to the private `increment` of the instance
+ * @example
+ * ```typescript
+ * const epoch = new Date('2000-01-01T00:00:00.000Z');
+ * const snowflake = new Snowflake(epoch).generate();
+ * ```
+ * @returns A unique snowflake
+ */
+ public generate({
+ increment,
+ timestamp = Date.now(),
+ workerId = WorkerId,
+ processId = ProcessId,
+ }: SnowflakeGenerateOptions = {}) {
+ if (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());
+ else if (typeof timestamp === 'number') timestamp = BigInt(timestamp);
+ else if (typeof timestamp !== 'bigint') {
+ throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`);
+ }
+
+ if (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;
+ else {
+ increment = this.#increment++;
+ if (this.#increment >= 4095n) this.#increment = 0n;
+ }
+
+ // timestamp, workerId, processId, increment
+ return ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;
+ }
+
+ /**
+ * Deconstructs a snowflake given a snowflake ID
+ * @param id the snowflake to deconstruct
+ * @returns a deconstructed snowflake
+ * @example
+ * ```typescript
+ * const epoch = new Date('2000-01-01T00:00:00.000Z');
+ * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');
+ * ```
+ */
+ public deconstruct(id: string | bigint): DeconstructedSnowflake {
+ const bigIntId = BigInt(id);
+ return {
+ id: bigIntId,
+ timestamp: (bigIntId >> 22n) + this.#epoch,
+ workerId: (bigIntId >> 17n) & 0b11111n,
+ processId: (bigIntId >> 12n) & 0b11111n,
+ increment: bigIntId & 0b111111111111n,
+ epoch: this.#epoch,
+ };
+ }
+
+ /**
+ * Retrieves the timestamp field's value from a snowflake.
+ * @param id The snowflake to get the timestamp value from.
+ * @returns The UNIX timestamp that is stored in `id`.
+ */
+ public timestampFrom(id: string | bigint): number {
+ return Number((BigInt(id) >> 22n) + this.#epoch);
+ }
+}
+
+/**
+ * Options for Snowflake#generate
+ */
+export interface SnowflakeGenerateOptions {
+ /**
+ * Timestamp or date of the snowflake to generate
+ * @default Date.now()
+ */
+ timestamp?: number | bigint | Date;
+
+ /**
+ * The increment to use
+ * @default 0n
+ * @remark keep in mind that this bigint is auto-incremented between generate calls
+ */
+ increment?: bigint;
+
+ /**
+ * The worker ID to use, will be truncated to 5 bits (0-31)
+ * @default 0n
+ */
+ workerId?: bigint;
+
+ /**
+ * The process ID to use, will be truncated to 5 bits (0-31)
+ * @default 1n
+ */
+ processId?: bigint;
+}
+
+/**
+ * Object returned by Snowflake#deconstruct
+ */
+export interface DeconstructedSnowflake {
+ /**
+ * The id in BigInt form
+ */
+ id: bigint;
+
+ /**
+ * The timestamp stored in the snowflake
+ */
+ timestamp: bigint;
+
+ /**
+ * The worker id stored in the snowflake
+ */
+ workerId: bigint;
+
+ /**
+ * The process id stored in the snowflake
+ */
+ processId: bigint;
+
+ /**
+ * The increment stored in the snowflake
+ */
+ increment: bigint;
+
+ /**
+ * The epoch to use in the snowflake
+ */
+ epoch: bigint;
+}
diff --git a/backend-old/utils/constants.ts b/backend-old/utils/constants.ts
new file mode 100644
index 00000000..e7d69bfe
--- /dev/null
+++ b/backend-old/utils/constants.ts
@@ -0,0 +1,63 @@
+import type { CookieOptions } from 'express';
+import type { Document } from '../types';
+
+/*const COOKIE_CONFIG: CookieOptions = {
+ httpOnly: true,
+ domain: process.env.FRONT_DOMAIN,
+ secure: process.env.NODE_ENV == 'production' ? true : false,
+ sameSite: 'lax',
+};*/
+const COOKIE_CONFIG: CookieOptions = {
+ httpOnly: true,
+ domain: process.env.NODE_ENV == 'production' ? process.env.FRONT_DOMAIN : undefined,
+ secure: process.env.NODE_ENV == 'production' ? true : false,
+ sameSite: 'lax',
+};
+
+const MIME_TYPES_IMAGE = {
+ 'image/jpg': 'jpg',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/svg+xml': 'svg',
+};
+const OTHER_MIME_TYPES = {
+ 'application/pdf': 'pdf',
+ // doc, docx, xls, xlsx, ppt, pptx
+ 'application/msword': 'doc',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
+ 'application/vnd.ms-excel': 'xls',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
+ 'application/vnd.ms-powerpoint': 'ppt',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
+ // txt
+ 'text/plain': 'txt',
+ // zip, tar, rar
+ 'application/zip': 'zip',
+ 'application/x-tar': 'tar',
+ 'application/x-rar-compressed': 'rar',
+};
+const ACCEPTED_MIME_TYPES = {
+ ...MIME_TYPES_IMAGE,
+ ...OTHER_MIME_TYPES,
+};
+enum Roles {
+ USER = 1,
+ ADMIN = 2,
+}
+
+const DEFAULT_DOCUMENT: Omit<Document, 'id' | 'author_id' | 'created_timestamp' | 'updated_timestamp'> = {
+ name: 'Welcome to Alexandrie!',
+ description: 'This is your first document, you can edit it or delete it.',
+ tags: 'welcome, first',
+ category: undefined,
+ parent_id: undefined,
+ accessibility: 1,
+ content_markdown:
+ '# Welcome to Alexandrie ! πŸš€\n\n## Formatting options\n\nLorem **ipsum dolor** *sit amet*, consectetur _adipiscing elit_. ==But not sad.== \n\n### Different content blocks\n\n:::blue Blue\nA blue block\n:::\n:::red Red\nA red block\n:::\n:::green Green\nA green block\n:::\n:::grey Grey\nA grey block\n:::\n:::yellow Yellow\nA yellow block\n:::\n:::turquoise Turquoise\nA turquoise block\n:::\n:::details Details\nA details block\n:::\n\n\n:::no-print\nThis content will not be printed\n:::\n\n:::center\nThis content is centered\n:::\n\n:::definition Red Info\nBlock of content (ex: definition)\n:::\n\n:::property Blue Info\nBlock of content (ex: property)\n:::\n\n:::theorem Turquoise Info\nBlock of content (ex: theorem)\n:::\n\n:::info-u Info without background\nBlock of content (ex: info, tip, note)\n:::\n\n:::warning Warning Info\nBlock of content (ex: warning)\n:::\n\n### Bullet and Numbered Lists:\n\n- Bullet 1\n- Bullet 2\n - Sub-bullet 2-1\n\n1. Item 1\n1. Item 2\n\n### Markdown Tables\n\n| Column 1 | Column 2 | Column 3 |\n|:----------|:----------|:---------|\n|Item 1 | Item 2 | Item 3 |\n\n### Other formats\n\n$\text{This is a math block: } f(x) = ax^2+bx+c$\n\n```javascript\nconst hello = "Hello world";\n```\n\n> Note: This content is a quote\n>> Nested quote\n\n## Shortcuts\n\n- **Ctrl + S**: Save\n- **Ctrl + P**: Toggle preview\n- **Ctrl + Q**: Switch to document\n- **Ctrl + B**: Bold formatting\n- **Ctrl + I**: Italic formatting\n- **Ctrl + U**: Underline formatting\n- **Ctrl + K**: Insert link\n- **Ctrl + M**: Insert image\n\n## Snippets\n\n- **!m**: Insert a math block (LaTeX)\n- **!def**: Insert a definition block\n- **!thm**: Insert a theorem block\n- **!center**: Center the content\n- **!red**: Insert a red block\n- **!green**: Insert a green block\n- **!blue**: Insert a blue block\n- **!yellow**: Insert a yellow block\n- **!details**: Insert a details block\n',
+ content_html:
+ '<h1 id="welcome-to-alexandrie-!-%F0%9F%9A%80" tabindex="-1"><a class="header-anchor" href="#welcome-to-alexandrie-!-%F0%9F%9A%80" aria-hidden="true">#</a> Welcome to Alexandrie ! πŸš€</h1>\n<h2 id="formatting-options" tabindex="-1"><a class="header-anchor" href="#formatting-options" aria-hidden="true">#</a> Formatting options</h2>\n<p>Lorem <strong>ipsum dolor</strong> <em>sit amet</em>, consectetur <u>adipiscing elit</u>. <mark>But not sad.</mark></p>\n<h3 id="different-content-blocks" tabindex="-1"><a class="header-anchor" href="#different-content-blocks" aria-hidden="true">#</a> Different content blocks</h3>\n<div class="blue custom-block"><p class="custom-block-title">Blue</p>\n<p>A blue block</p>\n</div>\n<div class="red custom-block"><p class="custom-block-title">Red</p>\n<p>A red block</p>\n</div>\n<div class="green custom-block"><p class="custom-block-title">Green</p>\n<p>A green block</p>\n</div>\n<div class="grey custom-block"><p class="custom-block-title">Grey</p>\n<p>A grey block</p>\n</div>\n<div class="yellow custom-block"><p class="custom-block-title">Yellow</p>\n<p>A yellow block</p>\n</div>\n<div class="turquoise custom-block"><p class="custom-block-title">Turquoise</p>\n<p>A turquoise block</p>\n</div>\n<details class="details custom-block no-print"><summary>Details</summary>\n<p>A details block</p>\n</details>\n<div class="no-print">\n<p>This content will not be printed</p>\n</div>\n<div class="center">\n<p>This content is centered</p>\n</div>\n<div class="markdown-container">\n <strong style="display: inline-flex; align-items: baseline;" class="red title">\n <svg style="align-self: center;" class="svg-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm6.5-.25A.75.75 0 017.25 7h1a.75.75 0 01.75.75v2.75h.25a.75.75 0 010 1.5h-2a.75.75 0 010-1.5h.25v-2h-.25a.75.75 0 01-.75-.75zM8 6a1 1 0 100-2 1 1 0 000 2z"></path></svg>Red Info</strong><p>Block of content (ex: definition)</p>\n</div>\n<div class="markdown-container">\n <strong style="display: inline-flex; align-items: baseline;" class="blue title">\n <svg style="align-self: center;" class="svg-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm6.5-.25A.75.75 0 017.25 7h1a.75.75 0 01.75.75v2.75h.25a.75.75 0 010 1.5h-2a.75.75 0 010-1.5h.25v-2h-.25a.75.75 0 01-.75-.75zM8 6a1 1 0 100-2 1 1 0 000 2z"></path></svg>Blue Info</strong><p>Block of content (ex: property)</p>\n</div>\n<div class="markdown-container">\n <strong style="display: inline-flex; align-items: baseline;" class="turquoise title">\n <svg style="align-self: center;" class="svg-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm6.5-.25A.75.75 0 017.25 7h1a.75.75 0 01.75.75v2.75h.25a.75.75 0 010 1.5h-2a.75.75 0 010-1.5h.25v-2h-.25a.75.75 0 01-.75-.75zM8 6a1 1 0 100-2 1 1 0 000 2z"></path></svg>Turquoise Info</strong><p>Block of content (ex: theorem)</p>\n</div>\n<div class="markdown-container">\n <strong style="display: inline-flex; align-items: baseline;" class="u title">\n <svg style="align-self: center;" class="svg-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zM0 8a8 8 0 1116 0A8 8 0 010 8zm6.5-.25A.75.75 0 017.25 7h1a.75.75 0 01.75.75v2.75h.25a.75.75 0 010 1.5h-2a.75.75 0 010-1.5h.25v-2h-.25a.75.75 0 01-.75-.75zM8 6a1 1 0 100-2 1 1 0 000 2z"></path></svg>Info without background</strong><p>Block of content (ex: info, tip, note)</p>\n</div>\n<div class="markdown-container">\n <strong style="display: inline-flex; align-items: baseline;" class="yellow title">\n <svg style="align-self: center;" class="svg-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"> </path> </svg>Warning Info</strong><p>Block of content (ex: warning)</p>\n</div>\n<h3 id="bullet-and-numbered-lists%3A" tabindex="-1"><a class="header-anchor" href="#bullet-and-numbered-lists%3A" aria-hidden="true">#</a> Bullet and Numbered Lists:</h3>\n<ul>\n<li>Bullet 1</li>\n<li>Bullet 2\n<ul>\n<li>Sub-bullet 2-1</li>\n</ul>\n</li>\n</ul>\n<ol>\n<li>Item 1</li>\n<li>Item 2</li>\n</ol>\n<h3 id="markdown-tables" tabindex="-1"><a class="header-anchor" href="#markdown-tables" aria-hidden="true">#</a> Markdown Tables</h3>\n<table>\n<thead>\n<tr>\n<th style="text-align:left">Column 1</th>\n<th style="text-align:left">Column 2</th>\n<th style="text-align:left">Column 3</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style="text-align:left">Item 1</td>\n<td style="text-align:left">Item 2</td>\n<td style="text-align:left">Item 3</td>\n</tr>\n</tbody>\n</table>\n<h3 id="other-formats" tabindex="-1"><a class="header-anchor" href="#other-formats" aria-hidden="true">#</a> Other formats</h3>\n<p><span class="katex-container"><i><span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>This&nbsp;is&nbsp;a&nbsp;math&nbsp;block:&nbsp;</mtext><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi></mrow><annotation encoding="application/x-tex">\text{This is a math block: } f(x) = ax^2+bx+c</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord text"><span class="mord">This&nbsp;is&nbsp;a&nbsp;math&nbsp;block:&nbsp;</span></span><span class="mord mathnormal" style="margin-right:0.10764em;">f</span><span class="mopen">(</span><span class="mord mathnormal">x</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.9474em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal">x</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.8641em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight">2</span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">b</span><span class="mord mathnormal">x</span><span class="mspace" style="margin-right:0.2222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">c</span></span></span></span></span></i></span></p>\n<pre><code class="hljs language-javascript"><span class="hljs-keyword">const</span> hello = <span class="hljs-string">"Hello world"</span>;\n</code></pre>\n<blockquote>\n<p>Note: This content is a quote</p>\n<blockquote>\n<p>Nested quote</p>\n</blockquote>\n</blockquote>\n<h2 id="shortcuts" tabindex="-1"><a class="header-anchor" href="#shortcuts" aria-hidden="true">#</a> Shortcuts</h2>\n<ul>\n<li><strong>Ctrl + S</strong>: Save</li>\n<li><strong>Ctrl + P</strong>: Toggle preview</li>\n<li><strong>Ctrl + Q</strong>: Switch to document</li>\n<li><strong>Ctrl + B</strong>: Bold formatting</li>\n<li><strong>Ctrl + I</strong>: Italic formatting</li>\n<li><strong>Ctrl + U</strong>: Underline formatting</li>\n<li><strong>Ctrl + K</strong>: Insert link</li>\n<li><strong>Ctrl + M</strong>: Insert image</li>\n</ul>\n<h2 id="snippets" tabindex="-1"><a class="header-anchor" href="#snippets" aria-hidden="true">#</a> Snippets</h2>\n<ul>\n<li><strong>!m</strong>: Insert a math block (LaTeX)</li>\n<li><strong>!def</strong>: Insert a definition block</li>\n<li><strong>!thm</strong>: Insert a theorem block</li>\n<li><strong>!center</strong>: Center the content</li>\n<li><strong>!red</strong>: Insert a red block</li>\n<li><strong>!green</strong>: Insert a green block</li>\n<li><strong>!blue</strong>: Insert a blue block</li>\n<li><strong>!yellow</strong>: Insert a yellow block</li>\n<li><strong>!details</strong>: Insert a details block</li>\n</ul>',
+};
+
+export { MIME_TYPES_IMAGE, OTHER_MIME_TYPES, ACCEPTED_MIME_TYPES, COOKIE_CONFIG, DEFAULT_DOCUMENT, Roles };
diff --git a/backend-old/utils/functions.ts b/backend-old/utils/functions.ts
new file mode 100644
index 00000000..68ac9a98
--- /dev/null
+++ b/backend-old/utils/functions.ts
@@ -0,0 +1,39 @@
+import type { IResponse } from '../types';
+
+export function success(result: any): IResponse {
+ const Response: IResponse = {
+ status: 'success',
+ timestamp: Date.now(),
+ result: result,
+ };
+ return Response;
+}
+
+export function error(message: any): IResponse {
+ const Response: IResponse = {
+ status: 'error',
+ timestamp: Date.now(),
+ message: String(message),
+ };
+ return Response;
+}
+
+export function isErr(param: any): boolean {
+ return param instanceof Error;
+}
+
+export function checkAndChange(obj: any) {
+ if (isErr(obj)) return error(obj.message || obj);
+ else return success(obj);
+}
+
+type Cookies = {
+ [key: string]: any;
+};
+export function parseCookies(cookies: string = '') {
+ return cookies.split(';').reduce((obj: Cookies, c: string) => {
+ const n = c.trim().split('=');
+ if (n[0]) obj[n[0]] = n[1]?.trim();
+ return obj;
+ }, {});
+}
diff --git a/backend-old/utils/index.ts b/backend-old/utils/index.ts
new file mode 100644
index 00000000..5764e349
--- /dev/null
+++ b/backend-old/utils/index.ts
@@ -0,0 +1,3 @@
+export * from './constants';
+export * from './functions';
+export * as Logger from './Logger';
diff --git a/backend-old/utils/responses.go b/backend-old/utils/responses.go
new file mode 100644
index 00000000..a6fe71bc
--- /dev/null
+++ b/backend-old/utils/responses.go
@@ -0,0 +1,35 @@
+package utils
+
+import (
+ "time"
+)
+
+
+type internal_success struct {
+ status string
+ result any
+ timestamp int64
+}
+type internal_error struct {
+ status string
+ message string
+ timestamp int64
+}
+
+
+
+func Success(data any) internal_success {
+ return internal_success{
+ status: "success",
+ result: data,
+ timestamp: time.Now().UnixMilli(),
+ }
+}
+
+func Error(message string) internal_error {
+ return internal_error{
+ status: "error",
+ message: message,
+ timestamp: time.Now().UnixMilli(),
+ }
+}
\ No newline at end of file