📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
Fix new auth system
Smaug67398a71ef8d9421
diff --git a/TODO.md b/TODO.mdindex 55cfd19a..28b5a4da 100644--- a/TODO.md+++ b/TODO.md@@ -3,3 +3,5 @@- Unification of error handling- Unification of types- Unification of classes / params++- Badges frontend (interfaces and markdown)diff --git a/backend/app.ts b/backend/app.tsindex 5e671e32..1ffe2cff 100644--- a/backend/app.ts+++ b/backend/app.ts@@ -7,22 +7,23 @@ import type { Request, Response } from 'express';import db from './models/db';import Logger from './utils/Logger';import { checkAndChange } from './utils/functions';-import { UPLOADS_PATH } from './utils/constants';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 uploads_dir: string;- constructor() {+ public config: typeof config;++ constructor(c: typeof config) {Logger.debug(`Starting in ${process.env.NODE_ENV} mode...`);+ 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');- this.uploads_dir = join(__dirname, '../../uploads');}private async handleRoutes() {const directories = readdirSync(join(__dirname, 'routes'));@@ -70,7 +71,7 @@ export class App {res.set('x-timestamp', Date.now().toString());},};- this.app.use('/static', express.static(UPLOADS_PATH, staticOptions));+ this.app.use('/static', express.static(this.config.upload_path, staticOptions));this.app.listen(this.port, () => {Logger.success(`Started on port ${this.port}`);diff --git a/backend/classes/Base.ts b/backend/classes/Base.tsindex b9e52cd4..af1fc7a7 100644--- a/backend/classes/Base.ts+++ b/backend/classes/Base.ts@@ -1,11 +1,13 @@-import { App } from "../app";+import { App } from '../app';-export default class Base {+export default abstract class Base<T> {// Define the app main classreadonly app: App;constructor(app: App) {- if (!app) throw new Error("App is not defined");+ if (!app) throw new Error('App is not defined');this.app = app;}++ public abstract validate(data: T): string | false;}diff --git a/backend/classes/Categories.ts b/backend/classes/CategoriesManager.tssimilarity index 74%rename from backend/classes/Categories.tsrename to backend/classes/CategoriesManager.tsindex 569c1f77..b39f5e7b 100644--- a/backend/classes/Categories.ts+++ b/backend/classes/CategoriesManager.ts@@ -1,7 +1,7 @@import Base from './Base';import type { Category, CategoryDB } from '../types';-export default class CategoriesDB extends Base {+export class CategoriesManager extends Base<Category> {constructor(app: App) {super(app);}@@ -15,16 +15,15 @@ export default class CategoriesDB extends Base {});}- public add(data: Omit<Category, 'id'>): Promise<Category> {+ public add(data: Category): Promise<Category> {return new Promise((resolve, reject) => {- const id = this.app.snowflake.generate().toString();if (!data.name) return reject(new Error('name must be provided'));this.app.db.query('INSERT INTO categories (`id`, `name`,`icon`, `order`, `parent_id`) VALUES (?, ?, ?, ?, ?)',- [id, data.name, data.icon, data.order, data.parent_id],+ [data.id, data.name, data.icon, data.order, data.parent_id],err => {if (err) return reject('Internal database error.');- else resolve({ id, ...data });+ else resolve(data);},);});@@ -55,4 +54,12 @@ export default class CategoriesDB extends Base {});});}++ public validate(data: Category): string | false {+ if (!data.id || data.id.length > 50) return 'category id invalid';+ if (!data.name || data.name.length > 50) return 'category name invalid';+ if (data.order && isNaN(data.order)) return 'category order invalid';+ if (data.parent_id && data.parent_id.length > 50) return 'category id invalid';+ return false;+ }}diff --git a/backend/classes/ConnectionsLogsManager.ts b/backend/classes/ConnectionsLogsManager.tsindex eeb33a24..790aa27b 100644--- a/backend/classes/ConnectionsLogsManager.ts+++ b/backend/classes/ConnectionsLogsManager.ts@@ -1,7 +1,7 @@import Base from './Base';import type { ConnectionLog, ConnectionLogDB } from '../types';-export default class ConnectionsLogsManager extends Base {+export class ConnectionsLogsManager extends Base<ConnectionLog> {constructor(app: App) {super(app);}@@ -13,18 +13,35 @@ export default class ConnectionsLogsManager extends Base {});});}- public createConnexion(connection: Omit<ConnectionLog, 'id' | 'timestamp'>) {+ public createConnexion(connection: ConnectionLog) {return new Promise((resolve, reject) => {- const time = Date.now().toString();- const id = this.app.snowflake.generate().toString();this.app.db.query<ConnectionLogDB[]>('INSERT INTO connections (id, user_id, ip_adress, user_agent, location, type, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)',- [id, connection.user_id, connection.ip_adress, connection.user_agent, connection.location, connection.type, time],+ [+ 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({ id, ...connection, created_timestamp: time });+ 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;+ }}diff --git a/backend/classes/ConnectionsManager.ts b/backend/classes/ConnectionsManager.tsindex bd447718..dc184e82 100644--- a/backend/classes/ConnectionsManager.ts+++ b/backend/classes/ConnectionsManager.ts@@ -1,7 +1,7 @@import Base from './Base';import type { Connection, ConnectionDB } from '../types';-export default class ConnectionsLogsManager extends Base {+export class ConnectionsManager extends Base<Connection> {constructor(app: App) {super(app);}@@ -9,7 +9,7 @@ export default class ConnectionsLogsManager extends Base {return new Promise((resolve, reject) => {this.app.db.query<ConnectionDB[]>('SELECT * FROM users_auth WHERE user_id = ?', [user_id], async (err, results) => {if (err) return reject('Internal database error.');- resolve(results[0] || { user_id, refresh_token: '', expire_token: 0, last_login: 0, last_logout: 0 });+ resolve(results[0] || { user_id, refresh_token: '', expire_token: '0', last_login: '0', last_logout: '0' });});});}@@ -19,10 +19,8 @@ export default class ConnectionsLogsManager extends Base {'INSERT INTO users_auth (user_id, refresh_token, expire_token, last_login, last_logout) VALUES (?, ?, ?, ?, ?)',[connection.user_id, connection.refresh_token, connection.expire_token, connection.last_login, connection.last_logout],async err => {- console.log(err);-if (err) return reject('Internal database error.');- resolve({ ...connection });+ resolve(connection);},);});@@ -34,9 +32,17 @@ export default class ConnectionsLogsManager extends Base {[connection.refresh_token, connection.expire_token, connection.last_login, connection.last_logout, connection.user_id],async err => {if (err) return reject('Internal database error.');- resolve({ ...connection });+ resolve(connection);},);});}+ public validate(data: Connection): string | false {+ if (!data.user_id || data.user_id.length > 50) return 'connection user id invalid';+ if (data.refresh_token && data.refresh_token.length > 200) return 'connection refresh token invalid';+ if (!data.expire_token) return 'connection expire token invalid';+ if (!data.last_login) return 'connection last login invalid';+ if (!data.last_logout) return 'connection last logout invalid';+ return false;+ }}diff --git a/backend/classes/DocumentsManager.ts b/backend/classes/DocumentsManager.tsindex 3bad57d5..e4cb4f63 100644--- a/backend/classes/DocumentsManager.ts+++ b/backend/classes/DocumentsManager.ts@@ -1,7 +1,7 @@import Base from './Base';import type { Document, DocumentDB } from '../types';-export default class DocumentsManager extends Base {+export class DocumentsManager extends Base<Document> {constructor(app: App) {super(app);}@@ -48,18 +48,15 @@ export default class DocumentsManager extends Base {});});}- public add(data: Omit<Document, 'id' | 'created_timestamp' | 'updated_timestamp'>) {+ public add(data: Document) {return new Promise((resolve, reject) => {- const time = Date.now().toString();- const id = this.app.snowflake.generate().toString();if (!data.name) return reject(new Error('name must be provided'));if (!data.accessibility && data.accessibility != 0) return reject(new Error('accessibility must be provided'));if (!data.author_id) return reject(new Error('author_id must be provided'));-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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',[- id,+ data.id,data.name,data.description,data.tags,@@ -69,23 +66,22 @@ export default class DocumentsManager extends Base {data.content_markdown,data.content_html,data.author_id,- time,- time,+ data.created_timestamp,+ data.updated_timestamp,],err => {if (err) return reject('Internal database error.');- resolve({ id, ...data, created_timestamp: time, updated_timestamp: time });+ resolve(data);},);});}- public put(id: string, data: Omit<Document, 'id' | 'created_timestamp' | 'updated_timestamp'>) {+ public put(id: string, data: Omit<Document, 'id' | 'created_timestamp'>) {return new Promise((resolve, reject) => {if (!id) return reject(new Error('id must be provided'));if (!data.name) return reject(new Error('name must be provided'));if (!data.accessibility && data.accessibility != 0) return reject(new Error('accessibility must be provided'));if (!data.author_id) return reject(new Error('author_id must be provided'));- const time = Date.now().toString();this.app.db.query<DocumentDB[]>('UPDATE documents SET name = ?, description = ?, tags = ?, category = ?, parent_id = ?, accessibility = ?, content_markdown = ?, content_html = ?, updated_timestamp = ? WHERE id = ?',[@@ -97,12 +93,12 @@ export default class DocumentsManager extends Base {data.accessibility,data.content_markdown,data.content_html,- time,+ data.updated_timestamp,id,],err => {if (err) return reject('Internal database error.');- resolve({ id, ...data, updated_timestamp: time });+ resolve({ id, ...data });},);});@@ -117,4 +113,20 @@ export default class DocumentsManager extends Base {});});}++ public validate(data: Document): string | false {+ if (!data.id || data.id.length > 50) return 'document id invalid';+ if (!data.name || data.name.length > 50) return 'document name invalid';+ if (data.description && data.description.length > 255) return 'document description invalid';+ if (data.tags && data.tags.length > 200) return 'document tags invalid';+ if (data.category && data.category.length > 50) return 'document category invalid';+ if (data.parent_id && data.parent_id.length > 50) return 'document parent id invalid';+ if (!data.accessibility && data.accessibility > 10) return 'document accessibility invalid';+ if (!data.content_markdown || data.content_markdown.length > 4_294_967_295) return 'document content markdown invalid';+ if (data.content_html && data.content_html.length > 4_294_967_295) return 'document content html invalid';+ if (!data.author_id || data.author_id.length > 50) return 'document author id invalid';+ if (!data.created_timestamp || data.created_timestamp.length > 50) return 'document created timestamp invalid';+ if (!data.updated_timestamp || data.updated_timestamp.length > 50) return 'document updated timestamp invalid';+ return false;+ }}diff --git a/backend/classes/RessourcesManager.ts b/backend/classes/RessourcesManager.tsindex ea60983b..73024591 100644--- a/backend/classes/RessourcesManager.ts+++ b/backend/classes/RessourcesManager.ts@@ -1,8 +1,7 @@import Base from './Base';import type { IObject, Ressource, RessourceDB } from '../types';-import type { PartialRessource } from '../controllers/cdn.controller';-export default class RessourcesManager extends Base {+export class RessourcesManager extends Base<Ressource> {constructor(app: App) {super(app);}@@ -14,27 +13,36 @@ export default class RessourcesManager extends Base {});});}- public createRessource(ressource: PartialRessource): Promise<IObject> {+ public createRessource(ressource: Ressource): Promise<IObject> {return new Promise((resolve, reject) => {- const time = Date.now().toString();- const id = this.app.snowflake.generate().toString();this.app.db.query<RessourceDB[]>('INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path,author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',[- id,+ ressource.id,ressource.filename,ressource.file_size,ressource.file_type,ressource.original_path,ressource.transformed_path,ressource.author_id,- time,+ ressource.created_timestamp,],async err => {if (err) return reject('Internal database error.');- resolve({ id, ...ressource, created_timestamp: time });+ resolve(ressource);},);});}+ 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/classes/Users.ts b/backend/classes/Users.tsdeleted file mode 100644index 624340de..00000000--- a/backend/classes/Users.ts+++ /dev/null@@ -1,26 +0,0 @@-import Base from './Base';-import type { UserDB } from '../types';--export default class MemberClass extends Base {- constructor(app: App) {- super(app);- }- public get(username: string): Promise<UserDB> {- 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.');- if (!results[0]) return reject('Bad username.');- resolve(results[0]);- });- });- }- public getById(id: string): Promise<UserDB> {- return new Promise((resolve, reject) => {- this.app.db.query<UserDB[]>('SELECT * FROM users WHERE id = ? LIMIT 1', [id], async (err, results) => {- if (err) return reject('Internal database error.');- if (!results[0]) return reject('Bad user id.');- resolve(results[0]);- });- });- }-}diff --git a/backend/classes/UsersManager.ts b/backend/classes/UsersManager.tsnew file mode 100644index 00000000..a324720e--- /dev/null+++ b/backend/classes/UsersManager.ts@@ -0,0 +1,38 @@+import Base from './Base';+import type { User, UserDB } from '../types';++export class UsersManager extends Base<User> {+ constructor(app: App) {+ super(app);+ }+ public get(username: string): Promise<UserDB> {+ 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.');+ if (!results[0]) return reject('Bad username.');+ resolve(results[0]);+ });+ });+ }+ public getById(id: string): Promise<UserDB> {+ return new Promise((resolve, reject) => {+ this.app.db.query<UserDB[]>('SELECT * FROM users WHERE id = ? LIMIT 1', [id], async (err, results) => {+ if (err) return reject('Internal database error.');+ if (!results[0]) return reject('Bad user id.');+ resolve(results[0]);+ });+ });+ }++ public validate(data: User): string | false {+ if (!data.id || data.id.length > 50) return 'user id invalid';+ if (!data.username || data.username.length > 25) return 'user username invalid';+ if (!data.firstname || data.firstname.length > 25) return 'user firstname invalid';+ if (!data.lastname || data.lastname.length > 25) return 'user lastname invalid';+ if (!data.avatar || data.avatar.length > 75) return 'user avatar invalid';+ if (!data.email || data.email.length > 50) return 'user email invalid';+ if (!data.password || data.password.length > 255) return 'user password invalid';+ if (!data.created_timestamp || data.created_timestamp.length > 50) return 'user created timestamp invalid';+ return false;+ }+}diff --git a/backend/classes/index.ts b/backend/classes/index.tsnew file mode 100644index 00000000..a6112a3d--- /dev/null+++ b/backend/classes/index.ts@@ -0,0 +1,6 @@+export * from './CategoriesManager';+export * from './ConnectionsLogsManager';+export * from './ConnectionsManager';+export * from './DocumentsManager';+export * from './RessourcesManager';+export * from './UsersManager';diff --git a/backend/config.ts b/backend/config.tsnew file mode 100644index 00000000..bbd025aa--- /dev/null+++ b/backend/config.ts@@ -0,0 +1,8 @@+import { resolve } from 'path';++export const config = {+ max_file_size: 20 * 1024 * 1024, // 20MB+ upload_path: resolve(__dirname, '../uploads'),+ access_token_expiration: '5s',+ refresh_token_expiration: 10 * 1000, // 1 days+};diff --git a/backend/controllers/BaseController.ts b/backend/controllers/BaseController.tsnew file mode 100644index 00000000..d1767dba--- /dev/null+++ b/backend/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<V>, V> {+ public app: App;++ protected manager: T;++ protected utils = utils;++ constructor(manager: T) {+ this.app = manager.app;+ this.manager = manager;+ }+}diff --git a/backend/controllers/auth.controller.ts b/backend/controllers/auth.controller.tsindex 82cdefca..0e333e8d 100644--- a/backend/controllers/auth.controller.ts+++ b/backend/controllers/auth.controller.ts@@ -1,86 +1,87 @@-import UsersManager from '../classes/Users';-import ConnectionsManager from '../classes/ConnectionsManager';-import { success, error } from '../utils/functions';+import { randomBytes } from 'crypto';import { sign } from 'jsonwebtoken';--import { Connection, User } from '../types';import { compare } from 'bcrypt';-import { randomBytes } from 'crypto';-import { parseCookies } from '../utils/functions';-import type { CookieOptions, Request, Response } from 'express';+import BaseController from './BaseController';+import { UsersManager, ConnectionsManager } from '../classes';+import type { Connection, User } from '../types';+import type { Request, Response } from 'express';-const COOKIE_CONFIG: CookieOptions = {- httpOnly: true,- domain: process.env.FRONT_DOMAIN,- secure: process.env.NODE_ENV == 'production' ? true : false,- sameSite: 'lax',-};--export default class Authentification {- usersManager: UsersManager;+export default class Authentification extends BaseController<UsersManager, User> {connectionsManager: ConnectionsManager;constructor(app: App) {- this.usersManager = new UsersManager(app);+ super(new UsersManager(app));this.connectionsManager = new ConnectionsManager(app);}async authentification(_: App, req: Request, res: Response) {try {- const user = await this.usersManager.get(req.body.username);+ console.log('\x1b[44m[AUTH]\x1b[0m Initial connection');+ const user = await this.manager.get(req.body.username);if (!user) throw new Error('Bad username/password.');if (!(await this.check_password(user, req.body.password))) throw new Error('Bad username/password.');const connection: Connection = await this.connectionsManager.getConnection(user.id);- if (!connection.refresh_token || connection.expire_token < Date.now()) {+ if (!connection.refresh_token || BigInt(connection.expire_token) < Date.now()) {connection.refresh_token = randomBytes(64).toString('hex');- connection.expire_token = Date.now() + 3600000 * 24 * 1; // 1 day+ connection.expire_token = (Date.now() + this.app.config.refresh_token_expiration).toString(); // 1 day}- const in_database = connection.last_login != 0;- connection.last_login = Date.now();+ const in_database = connection.last_login != '0';+ connection.last_login = Date.now().toString();if (in_database) await this.connectionsManager.updateConnection(connection);else await this.connectionsManager.createConnection(connection);- const accessToken = sign({ userId: user.id }, process.env.JWT_SECRET || '', { expiresIn: '18s' });+ const accessToken = sign({ userId: user.id }, process.env.JWT_SECRET || '', {+ expiresIn: this.app.config.access_token_expiration,+ });console.log(`[AUTH] User ${user.id} connected. Signing new token...`);- res.cookie('user_token', `${accessToken}`, { ...COOKIE_CONFIG, maxAge: 3600000 * 0.5 });- res.cookie('user_refresh_token', `${connection.refresh_token}`, { ...COOKIE_CONFIG, maxAge: 3600000 * 24 * 1 });- res.cookie('user_auth', `true`, { ...COOKIE_CONFIG, httpOnly: false });- res.status(200).json(success({ auth: true }));+ res.cookie('user_token', `${accessToken}`, { ...this.utils.COOKIE_CONFIG });+ res.cookie('user_refresh_token', `${connection.refresh_token}`, { ...this.utils.COOKIE_CONFIG, maxAge: 3600000 * 24 * 1 });+ res.cookie('user_auth', `true`, { ...this.utils.COOKIE_CONFIG, httpOnly: false });+ res.status(200).json(this.utils.success({ auth: true }));+ console.log('\x1b[42m[AUTH]\x1b[0m Connection successful');} catch (e) {- if (e instanceof Error) res.status(401).json(error(e.message));- else res.status(500).json(error(String(e)));+ console.log('\x1b[41m[AUTH]\x1b[0m Error during initial connection');+ console.error(e);+ res.status(500).json(this.utils.error(e));}}disconnection(_: App, __: Request, res: Response): void {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.status(200).json(success('success'));+ res.status(200).json(this.utils.success({ auth: false }));}async check_password(user: User, password: string): Promise<boolean> {const valid = await compare(password, user.password);return valid;}async refresh_access_token(req: Request, res: Response) {- req.cookies = parseCookies(req.headers.cookie);+ console.log('\x1b[44m[AUTH]\x1b[0m Refreshing access token');+ req.cookies = this.utils.parseCookies(req.headers.cookie);+ const userId = req.params.user_id;+ const refreshToken = req.cookies.user_refresh_token;try {- const userId = req.params.user_id;- const refreshToken = req.cookies.user_refresh_token;if (!refreshToken) throw 'No refresh token provided';if (!userId) throw 'No user id provided';// Check if refresh token is validconst connection = await this.connectionsManager.getConnection(userId);- if (connection.refresh_token !== refreshToken || connection.expire_token < Date.now()) throw 'Invalid refresh token';+ if (connection.refresh_token !== refreshToken || BigInt(connection.expire_token) < Date.now())+ throw 'Invalid refresh token';// Check if user still exists- const user = await this.usersManager.getById(userId);+ const user = await this.manager.getById(userId);if (!user) throw 'User not found'; // if user deleted account-- const accessToken = sign({ userId }, process.env.JWT_SECRET || '', { expiresIn: '18s' });- res.cookie('user_token', `${accessToken}`, { ...COOKIE_CONFIG, maxAge: 3600000 * 0.5 });- res.status(200).json(success({ auth: true }));+ connection.expire_token = (Date.now() + this.app.config.refresh_token_expiration).toString(); // 1 day+ await this.connectionsManager.updateConnection(connection);+ const accessToken = sign({ userId }, process.env.JWT_SECRET || '', { expiresIn: this.app.config.access_token_expiration });+ res.cookie('user_token', `${accessToken}`, { ...this.utils.COOKIE_CONFIG });+ res.status(200).json(this.utils.success({ auth: true }));+ console.log('\x1b[42m[AUTH]\x1b[0m Access token refreshed');} catch (e) {- res.status(401).json(error(e));+ console.log('\x1b[41m[AUTH]\x1b[0m Error during refresh access token');+ console.error(e);+ res.clearCookie('user_auth');+ res.status(401).json(this.utils.error(e));}}}diff --git a/backend/controllers/backups.controller.ts b/backend/controllers/backups.controller.tsindex c549ebc9..b6687648 100644--- a/backend/controllers/backups.controller.ts+++ b/backend/controllers/backups.controller.ts@@ -1,7 +1,7 @@import { createWriteStream, unlinkSync, readdirSync } from 'fs';import { spawn } from 'child_process';-import type { Request, Response } from 'express';import { error, success } from '../utils/functions';+import type { Request, Response } from 'express';export default class CategoriesController {app: App;@@ -11,9 +11,9 @@ export default class CategoriesController {async add(_: Request, res: Response) {// Clean the uploads directory- const files = readdirSync(this.app.uploads_dir + '/backups');+ const files = readdirSync(this.app.config.upload_path + '/backups');for (const file of files) {- if (file.endsWith('.sql')) unlinkSync(`${this.app.uploads_dir}/backups/${file}`);+ if (file.endsWith('.sql')) unlinkSync(`${this.app.config.upload_path}/backups/${file}`);}const name = `backup-${new Date().toISOString().split('T')[0]}-${Date.now()}`;const mysqldump = spawn('mysqldump', [@@ -23,7 +23,7 @@ export default class CategoriesController {'alexandrie',]);- const wstream = createWriteStream(`${this.app.uploads_dir}/backups/${name}.sql`);+ const wstream = createWriteStream(`${this.app.config.upload_path}/backups/${name}.sql`);const backupPromise = new Promise<void | string>((resolve, reject) => {mysqldump.stdout.pipe(wstream)diff --git a/backend/controllers/categories.controller.ts b/backend/controllers/categories.controller.tsindex e9c8d460..2bae2c61 100644--- a/backend/controllers/categories.controller.ts+++ b/backend/controllers/categories.controller.ts@@ -1,26 +1,30 @@-import CategoriesManager from '../classes/Categories';-import { error, success } from '../utils/functions';+import BaseController from './BaseController';+import { CategoriesManager } from '../classes';import type { Request, Response } from 'express';+import { Category } from '../types';-export default class CategoriesController {- app: App;- manager: CategoriesManager;+export default class CategoriesController extends BaseController<CategoriesManager, Category> {constructor(app: App) {- this.app = app;- this.manager = new CategoriesManager(app);+ super(new CategoriesManager(app));}getAll(_: Request, res: Response) {this.manager.getAll()- .then((result: any) => res.status(200).json(success(result)))- .catch((err: Error) => res.status(500).json(error(err.message)));+ .then((result: any) => res.status(200).json(this.utils.success(result)))+ .catch((err: Error) => res.status(500).json(this.utils.error(err.message)));}add(req: Request, res: Response) {this.manager- .add({ name: req.body.name, icon: req.body.icon, order: req.body.order, parent_id: req.body.parent_id })- .then(r => res.status(201).json(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ .add({+ id: this.app.snowflake.generate().toString(),+ name: req.body.name,+ icon: req.body.icon,+ order: req.body.order,+ parent_id: req.body.parent_id,+ })+ .then(r => res.status(201).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));}update(req: Request, res: Response) {@@ -32,14 +36,14 @@ export default class CategoriesController {order: req.body.order,parent_id: req.body.parent_id,})- .then(r => res.status(200).json(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ .then(r => res.status(200).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));}delete(req: Request, res: Response) {this.manager.delete(req.params.id!)- .then(r => res.status(200).json(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ .then(r => res.status(200).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));}}diff --git a/backend/controllers/cdn.controller.ts b/backend/controllers/cdn.controller.tsindex 0bc6c963..5df474e9 100644--- a/backend/controllers/cdn.controller.ts+++ b/backend/controllers/cdn.controller.ts@@ -1,38 +1,32 @@import { access, constants } from 'fs';import sharp from 'sharp';-import { MIME_TYPES_IMAGE, UPLOADS_PATH } from '../utils/constants';+import BaseController from './BaseController';+import { RessourcesManager } from '../classes';+import type { Ressource } from '../types';import type { Request, Response } from 'express';-import { Ressource } from '../types';-import { error, success } from '../utils/functions';-import RessourcesManager from '../classes/RessourcesManager';-export type PartialRessource = Omit<Ressource, 'id' | 'created_timestamp'>;--export function convertImageToWebp(filename: string): Promise<string[]> {+export function convertImageToWebp(upload_path: string, filename: string): Promise<string[]> {return new Promise((resolve, reject) => {- const path = `${UPLOADS_PATH}/images/${filename}`;+ 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(`${UPLOADS_PATH}/webp/${filename.split('.')[0]}.webp`)+ .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 {- app: App;- manager: RessourcesManager;+export default class RessourcesController extends BaseController<RessourcesManager, Ressource> {constructor(app: App) {- this.app = app;- this.manager = new RessourcesManager(app);+ super(new RessourcesManager(app));}async get(req: Request, res: Response) {this.manager.getRessources(req.params.user_id as string)- .then((result: Ressource[]) => res.status(200).json(success(result)))- .catch(e => res.status(500).json(error(e)));+ .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) {@@ -44,27 +38,28 @@ export default class RessourcesController {const filename = file.filename;if (!filename) throw new Error('No file provided.');- const ressource: PartialRessource = {+ 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(MIME_TYPES_IMAGE).includes(file.mimetype)) {- const converted = await convertImageToWebp(filename);+ 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(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ .then(r => res.status(201).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));} catch (err) {- if (err instanceof Error) res.status(500).json(error(err.message));- res.status(500).json(error('Internal server error.'));+ res.status(500).json(this.utils.error(err));}}}diff --git a/backend/controllers/documents.controller.ts b/backend/controllers/documents.controller.tsindex 806afc8c..b9d9ee77 100644--- a/backend/controllers/documents.controller.ts+++ b/backend/controllers/documents.controller.ts@@ -1,46 +1,49 @@-import DocumentsManager from '../classes/DocumentsManager';-import { error, success } from '../utils/functions';+import BaseController from './BaseController';+import { DocumentsManager } from '../classes';import type { Response, Request } from 'express';import type { Document } from '../types';-export default class DocumentsController {- app: App;- manager: DocumentsManager;+export default class DocumentsController extends BaseController<DocumentsManager, Document> {constructor(app: App) {- this.app = app;- this.manager = new DocumentsManager(app);+ super(new DocumentsManager(app));}getAllDocuments(req: Request, res: Response) {this.manager.getAll(req.query.all?.toString())- .then((result: Partial<Document>[]) => res.status(200).json(success(result)))- .catch(e => res.status(500).json(error(e)));+ .then((result: Partial<Document>[]) => res.status(200).json(this.utils.success(result)))+ .catch(e => res.status(500).json(this.utils.error(e)));}getDocument(req: Request, res: Response) {this.manager.get(req.params.id as string)- .then(r => res.status(200).json(success(r)))- .catch(e => res.status(500).json(error(e)));+ .then(r => res.status(200).json(this.utils.success(r)))+ .catch(e => res.status(500).json(this.utils.error(e)));}- add(req: Request, res: Response): void {- this.manager- .add({- 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!,- })- .then(r => res.status(201).json(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ 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(),+ };+ const err = this.manager.validate(document);+ if (err) return res.status(400).json(this.utils.error(err));+ return this.manager+ .add(document)+ .then(r => res.status(201).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));}updateDocument(req: Request, res: Response) {- this.manager+ return this.manager.put(req.params.id as string, {name: req.body.name,description: req.body.description,@@ -51,14 +54,15 @@ export default class DocumentsController {content_markdown: req.body.content_markdown,content_html: req.body.content_html,author_id: req.user_id!,+ updated_timestamp: Date.now().toString(),})- .then(r => res.status(201).json(success(r)))- .catch(err => res.status(500).json(error(err.message)));+ .then(r => res.status(201).json(this.utils.success(r)))+ .catch(err => res.status(500).json(this.utils.error(err.message)));}deleteDocument(req: Request, res: Response) {this.manager.delete(req.params.id as string)- .then(r => res.status(201).json(success(r)))- .catch((err: Error) => res.status(500).json(error(err.message)));+ .then(r => res.status(201).json(this.utils.success(r)))+ .catch((err: Error) => res.status(500).json(this.utils.error(err.message)));}}diff --git a/backend/main.ts b/backend/main.tsindex e1b3bf96..0870c22b 100644--- a/backend/main.ts+++ b/backend/main.ts@@ -1,5 +1,5 @@import { resolve } from 'path';-+import { config as constants } from './config';import { App } from './app';import { config } from 'dotenv';@@ -7,7 +7,7 @@ config({path: resolve(__dirname, '../.env'),});-const server: App = new App();+const server: App = new App(constants);server.start();export default server;diff --git a/backend/middlewares/auth.ts b/backend/middlewares/auth.tsindex b56ea42a..be9b90ba 100644--- a/backend/middlewares/auth.ts+++ b/backend/middlewares/auth.ts@@ -11,11 +11,16 @@ export default (req: Request, res: Response, next: Function) => {if (!req.cookies) throw 'Missing cookies';if (!req.cookies.user_token && req.cookies.user_refresh_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('Requete non authentifiée'));+ if (err) {+ console.log('\x1b[41m[AUTH]\x1b[0m Token invalid. Try to refresh.');+ return res.status(401).json(error('Requete non authentifiée'));+ }req.user_id = decoded.userId;return next();});} catch (err) {+ console.log('\x1b[41m[AUTH]\x1b[0m Invalid authentification error.');+ console.log(err);res.clearCookie('user_auth');res.status(401).json(error('Requete non authentifiée'));}diff --git a/backend/middlewares/multer.cdn.ts b/backend/middlewares/multer.cdn.tsindex e08186c9..2c50cc72 100644--- a/backend/middlewares/multer.cdn.ts+++ b/backend/middlewares/multer.cdn.ts@@ -1,11 +1,12 @@import multer from 'multer';-import { MIME_TYPES_IMAGE, ACCEPTED_MIME_TYPES, maxSize, UPLOADS_PATH } from '../utils/constants';+import { MIME_TYPES_IMAGE, ACCEPTED_MIME_TYPES } from '../utils/constants';+import { config } from '../config';import type { IObject } from '../types';const storage = multer.diskStorage({destination: (_, file: Express.Multer.File, callback: Function) => {- if (Object.keys(MIME_TYPES_IMAGE).includes(file.mimetype)) return callback(null, `${UPLOADS_PATH}/images`);- callback(null, `${UPLOADS_PATH}/other`);+ 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;@@ -18,7 +19,7 @@ const storage = multer.diskStorage({export default multer({storage: storage,limits: {- fileSize: maxSize,+ fileSize: config.max_file_size,},fileFilter: (_, file: IObject, cb: Function) => {const mimetype = file.mimetype as unknown as keyof typeof ACCEPTED_MIME_TYPES;diff --git a/backend/models/database.drawio b/backend/models/database.drawionew file mode 100644index 00000000..3e129d64--- /dev/null+++ b/backend/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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>City_IPv4_complete</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> network_start_integer: bigint<br/> network_last_integer: bigint<br/> geoname_id: int<br/> registered_country_geoname_id: int<br/> represented_country_geoname_id: text<br/> is_anonymous_proxy: int<br/> is_satellite_provider: int<br/> postal_code: text<br/> latitude: double<br/> longitude: double<br/> accuracy_radius: int<br/> is_anycast: text</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>City_IPv6_complete</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> network_start_integer: double<br/> network_last_integer: double<br/> geoname_id: int<br/> registered_country_geoname_id: int<br/> represented_country_geoname_id: text<br/> is_anonymous_proxy: int<br/> is_satellite_provider: int<br/> postal_code: text<br/> latitude: double<br/> longitude: text<br/> accuracy_radius: text<br/> is_anycast: text</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>City_Locations_fr</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> locale_code: text<br/> continent_code: text<br/> continent_name: text<br/> country_iso_code: text<br/> country_name: text<br/> subdivision_1_iso_code: text<br/> subdivision_1_name: text<br/> subdivision_2_iso_code: text<br/> subdivision_2_name: text<br/> city_name: text<br/> metro_code: text<br/> time_zone: text<br/> is_in_european_union: text</p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> geoname_id: int</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>categories</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> name: varchar(50)<br/> icon: text<br/> order: int<br/> parent_id: varchar(50)</p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> id: varchar(50)</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>connections</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> id: varchar(50)<br/> user_id: varchar(50)<br/> ip_adress: varchar(50)<br/> user_agent: varchar(200)<br/> location: varchar(100)<br/> type: varchar(10)<br/> timestamp: bigint</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>documents</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> name: varchar(50)<br/> description: varchar(255)<br/> tags: varchar(200)<br/> category: varchar(50)<br/> parent_id: varchar(50)<br/> accessibility: tinyint(1)<br/> content_markdown: longtext<br/> content_html: longtext<br/> author_id: varchar(50)<br/> created_timestamp: bigint<br/> updated_timestamp: bigint</p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> id: varchar(50)</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>ressources /* For CDN */</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> id: varchar(50)<br/> filename: varchar(50)<br/> file_size: int<br/> file_type: varchar(100)<br/> original_path: varchar(100)<br/> transformed_path: varchar(100)<br/> author_id: varchar(50)<br/> created_timestamp: bigint</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>users</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> username: varchar(25)<br/> firstname: varchar(25)<br/> lastname: varchar(25)<br/> avatar: varchar(75)<br/> email: varchar(50)<br/> password: varchar(255)<br/> created_timestamp: bigint</p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> id: varchar(50)</p>" 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="<p style="margin:0px;margin-top:4px;text-align:center;"><b>users_auth</b></p><hr size="1"/><p style="margin:0 0 0 4px;line-height:1.6;"> user_id: varchar(50)<br/> refresh_token: varchar(255)<br/> expire_token: bigint<br/> last_login: bigint<br/> last_logout: bigint</p>" 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 filediff --git a/backend/models/database.png b/backend/models/database.pngnew file mode 100644index 00000000..d9380b70Binary files /dev/null and b/backend/models/database.png differdiff --git a/backend/types/Structures.d.ts b/backend/types/Structures.d.tsindex dce8248e..e16425e9 100644--- a/backend/types/Structures.d.ts+++ b/backend/types/Structures.d.ts@@ -52,15 +52,15 @@ export interface ConnectionLog {user_agent: string;location: string;type: string;- timestamp: string;+ timestamp: string; // BIGINT converted to string}export interface Connection {user_id: string;refresh_token: string;- expire_token: number;- last_login: number;- last_logout: number;+ expire_token: string;+ last_login: string;+ last_logout: string;}export type DocumentDB = RowDataPacket & Document;diff --git a/backend/utils/constants.ts b/backend/utils/constants.tsindex 329fd9f3..c62f9122 100644--- a/backend/utils/constants.ts+++ b/backend/utils/constants.ts@@ -1,15 +1,11 @@-import { resolve } from 'path';+import type { CookieOptions } from 'express';-const maxSize = 20 * 1024 * 1024; // 20MB--const access_token_expiration = '18s';-const refresh_token_expiration = 3600000 * 24 * 1; // 1 day--const COOKIE_CONFIG = {- domain: process.env.FRONT_DOMAIN,+const COOKIE_CONFIG: CookieOptions = {+ maxAge: 3600000 * 3,httpOnly: true,- secure: true,- sameSite: 'none',+ domain: process.env.FRONT_DOMAIN,+ secure: process.env.NODE_ENV == 'production' ? true : false,+ sameSite: 'lax',};const MIME_TYPES_IMAGE = {@@ -41,15 +37,4 @@ const ACCEPTED_MIME_TYPES = {...OTHER_MIME_TYPES,};-const UPLOADS_PATH = resolve(__dirname, '../../uploads');--export {- maxSize,- MIME_TYPES_IMAGE,- OTHER_MIME_TYPES,- ACCEPTED_MIME_TYPES,- UPLOADS_PATH,- COOKIE_CONFIG,- access_token_expiration,- refresh_token_expiration,-};+export { MIME_TYPES_IMAGE, OTHER_MIME_TYPES, ACCEPTED_MIME_TYPES, COOKIE_CONFIG };diff --git a/backend/utils/functions.ts b/backend/utils/functions.tsindex 7d6ccb01..d1f41d5e 100644--- a/backend/utils/functions.ts+++ b/backend/utils/functions.ts@@ -18,7 +18,7 @@ export function error(message: any): IResponse {return Response;}-export function isErr(param: any): Boolean {+export function isErr(param: any): boolean {return param instanceof Error;}diff --git a/backend/utils/index.ts b/backend/utils/index.tsnew file mode 100644index 00000000..f203a170--- /dev/null+++ b/backend/utils/index.ts@@ -0,0 +1,2 @@+export * from './constants';+export * from './functions';diff --git a/frontend/bun.lockb b/frontend/bun.lockbindex c3053608..67032e0d 100755Binary files a/frontend/bun.lockb and b/frontend/bun.lockb differdiff --git a/frontend/composables/utils.ts b/frontend/composables/utils.tsindex 7b2a43e0..5053834f 100644--- a/frontend/composables/utils.ts+++ b/frontend/composables/utils.ts@@ -10,3 +10,47 @@ export function useColorHash(str: string): string {const index = Math.abs(hash % colors.length);return colors[index];}++export interface APIResult<Data> {+ status: 'success' | 'error';+ message?: string;+ result?: Data;+}++export interface FetchOptions {+ id: string; // id of the ressource+}++export const baseUrl = import.meta.env.VITE_BASE_API?.toString() || '';+import type { DB_Document, DB_Category, DB_Ressource } from '../store/db_strustures';++export async function makeRequest(+ route: string,+ method: string,+ body: Object,+ retry = false,+): Promise<APIResult<DB_Document | DB_Category | DB_Ressource | DB_Document[] | DB_Category[] | DB_Ressource[]>> {+ const response = await fetch(`${baseUrl}/api/v1/${route}`, {+ method: method,+ body: method === 'GET' || method === 'DELETE' ? null : JSON.stringify(body),+ headers: { 'Content-Type': 'application/json; charset=UTF-8' },+ credentials: 'include',+ });++ if (response.status === 401 && !retry) {+ console.log('\x1b[41m[AUTH]\x1b[0m Access token invalid. Getting new access token...');+ const login = await makeRequest(`auth/refreshToken/152981937240150016`, 'GET', {}, true);+ if (login.status === 'success') {+ console.log('\x1b[42m[AUTH]\x1b[0m New access token received.');+ return await makeRequest(route, method, body, true);+ } else {+ console.log('\x1b[41m[AUTH]\x1b[0m Refresh token invalid. Please login again.');+ navigateTo('/login');+ return { status: 'error', message: 'Please login again.' };+ }+ }++ const decoded = await response.json();+ console.log('[SUCCESS] Response data:', decoded);+ return decoded;+}diff --git a/frontend/middleware/authentification.global.ts b/frontend/middleware/authentification.global.tsindex d61c8804..2b8a9377 100644--- a/frontend/middleware/authentification.global.ts+++ b/frontend/middleware/authentification.global.ts@@ -1,16 +1,9 @@-export default defineNuxtRouteMiddleware(to => {+export default defineNuxtRouteMiddleware((to, from) => {const user_auth = useCookie('user_auth');- if (to.fullPath.startsWith('/dashboard')) {- if (!user_auth.value) {- return navigateTo({- path: '/login',- query: { redirect: to.fullPath },- });- }- }- if (to.fullPath.startsWith('/login')) {- if (user_auth.value) {- return navigateTo({ path: '/dashboard' });- }- }+ if (to.fullPath.startsWith('/dashboard') && !user_auth?.value) {+ return navigateTo({+ path: '/login',+ query: { redirect: to.fullPath },+ });+ } else if (to.fullPath.startsWith('/login') && user_auth?.value) return navigateTo({ path: '/dashboard' });});diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex 96787b70..23b0f1a8 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -1,5 +1,6 @@export default defineNuxtConfig({devtools: { enabled: true },+vite: {css: {preprocessorOptions: {@@ -9,16 +10,20 @@ export default defineNuxtConfig({},},},+ssr: false,css: ['~/styles/main.scss', '~/styles/main.scss', '~/styles/katex/katex.min.css'],modules: ['@pinia/nuxt', '@nuxtjs/color-mode'],+colorMode: {preference: 'light', // default value of $colorMode.preferencefallback: 'light', // fallback value if not system preference found},+experimental: {viewTransition: true,},+app: {head: {title: 'Alexandrie',@@ -45,4 +50,6 @@ export default defineNuxtConfig({],},},++ compatibilityDate: '2024-07-03',});diff --git a/frontend/package.json b/frontend/package.jsonindex 7ed25a69..8d9fe70a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -2,24 +2,24 @@"name": "nuxt-app","devDependencies": {"@nuxt/devtools": "latest",- "@nuxtjs/color-mode": "^3.3.3",- "@pinia/nuxt": "^0.5.0",- "@types/katex": "^0.16.5",- "@types/markdown-it": "^13.0.4",- "@types/markdown-it-container": "^2.0.8",- "@types/node": "^20.8.5",- "katex": "^0.16.10",+ "@nuxtjs/color-mode": "^3.4.2",+ "@pinia/nuxt": "^0.5.1",+ "@types/katex": "^0.16.7",+ "@types/markdown-it": "^13.0.8",+ "@types/markdown-it-container": "^2.0.10",+ "@types/node": "^20.14.9",+ "katex": "^0.16.11","markdown-it": "^14.1.0","markdown-it-anchor": "^8.6.7","markdown-it-container": "^4.0.0","markdown-it-mark": "^4.0.0","markdown-it-underline": "^1.0.1",- "nuxt": "^3.8.0",- "pinia": "^2.1.6",- "punycode": "^2.3.0",- "sass": "^1.69.3",- "vue": "^3.3.4",- "vue-router": "^4.2.5"+ "nuxt": "^3.12.3",+ "pinia": "^2.1.7",+ "punycode": "^2.3.1",+ "sass": "^1.77.6",+ "vue": "^3.4.31",+ "vue-router": "^4.4.0"},"private": true,"scripts": {diff --git a/frontend/pages/dashboard/category/[id].vue b/frontend/pages/dashboard/category/[id].vueindex df39543a..928ac858 100644--- a/frontend/pages/dashboard/category/[id].vue+++ b/frontend/pages/dashboard/category/[id].vue@@ -16,11 +16,9 @@<script setup lang="ts">import { useCategoriesStore, useDocumentsStore } from '~/store';-const route = useRoute();const categoriesStore = useCategoriesStore();const documentsStore = useDocumentsStore();-const category = computed(() => categoriesStore.getById(route.params.id as string));const allDocuments = computed(() => {diff --git a/frontend/pages/dashboard/doc/[id].vue b/frontend/pages/dashboard/doc/[id].vueindex 9c217e7c..18569333 100644--- a/frontend/pages/dashboard/doc/[id].vue+++ b/frontend/pages/dashboard/doc/[id].vue@@ -1,43 +1,47 @@<template>- <div v-if="article?.id" style="width:100%;">- <div style="display:flex; justify-content: space-between;">- <div style="width:100%;max-width: 900px;margin: auto;">- <DocumentCardHeader :doc="article" style="margin-bottom: 20px;" />- <article class="document-theme" style="max-width: 100%;" ref="element" v-html="article.content_html">- </article>- <DocumentCardFooter :document="article" :next="next" :previous="previous" />+ <transition name="slide-fade" mode="out-in">++ <div v-if="article?.id" style="width:100%;">+ <div style="display:flex; justify-content: space-between;">+ <div style="width:100%;max-width: 900px;margin: auto;">+ <DocumentCardHeader :doc="article" style="margin-bottom: 20px;" />+ <article class="document-theme" style="max-width: 100%;" ref="element" v-html="article.content_html">+ </article>+ <DocumentCardFooter :document="article" :next="next" :previous="previous" />+ </div>+ <TableOfContent :element="element" :doc_id="article.id" class="toc" /></div>- <TableOfContent :element="element" :doc_id="document_id" class="toc" /></div>- </div>+ </transition></template><script setup lang="ts">+import { useDocumentsStore, type Document } from '@/store';import TableOfContent from "@/components/table-of-content/TableOfContents.vue";const route = useRoute();const documentsStore = useDocumentsStore();const element = ref<HTMLElement>();-const document_id = route.params.id as string;-const article = ref<Document>();+const article = ref<Document | undefined>();watchEffect(async () => {+ const document_id = route.params.id as string;const docFromStore = documentsStore.getById(document_id);+ article.value = undefined;if (docFromStore?.partial) {try {article.value = await documentsStore.fetch({ id: document_id });} catch (error) {- console.error("Error fetching document:", error);}} else article.value = docFromStore;useHead({ title: `Alexandrie ${article.value?.name || ''}` });});+const next = computed(() => documentsStore.getNext(article.value));const previous = computed(() => documentsStore.getPrevious(article.value));-</script><style scoped>@@ -51,4 +55,18 @@ const previous = computed(() => documentsStore.getPrevious(article.value));display: block;}}++.slide-fade-enter-active {+ transition: all .3s ease;+}++.slide-fade-leave-active {+ transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);+}++.slide-fade-enter,+.slide-fade-leave-to {+ transform: translateX(10px);+ opacity: 0;+}</style>\ No newline at end of filediff --git a/frontend/pages/login.vue b/frontend/pages/login.vueindex 5f525d12..d8ad4216 100644--- a/frontend/pages/login.vue+++ b/frontend/pages/login.vue@@ -14,7 +14,7 @@<input :type="showPassword ? 'text' : 'password'" id="password" v-model="password":class="{ 'is-invalid': errors.password }"><button type="button" class="password-toggle" @click="showPassword = !showPassword">{{ showPassword ? 'Hide' :- 'Show' }}</button>+ 'Show' }}</button></div><p v-if="errors.password" class="invalid-feedback">{{ errors.password }}</p></div>@@ -35,6 +35,10 @@ const errors = ref({const showPassword = ref(false)const password = ref('')+definePageMeta({+ viewTransition: false+})+function login() {if (!username.value) errors.value.username = 'Username is required'else errors.value.username = '';diff --git a/frontend/store/categories.store.ts b/frontend/store/categories.store.tsindex 9bb9fb50..008b2a14 100644--- a/frontend/store/categories.store.ts+++ b/frontend/store/categories.store.ts@@ -1,5 +1,4 @@import { defineStore } from 'pinia';-import { makeRequest, type FetchOptions } from './utils';import type { Category, DB_Category } from './db_strustures';diff --git a/frontend/store/documents.store.ts b/frontend/store/documents.store.tsindex 00f8641b..6056dc48 100644--- a/frontend/store/documents.store.ts+++ b/frontend/store/documents.store.ts@@ -1,6 +1,5 @@import { defineStore } from 'pinia';import { ref } from 'vue';-import { makeRequest, type FetchOptions } from './utils';import type { DB_Document, Document } from './db_strustures';export const useDocumentsStore = defineStore('documents', {diff --git a/frontend/store/ressources.store.ts b/frontend/store/ressources.store.tsindex 02c89e70..4e3208e6 100644--- a/frontend/store/ressources.store.ts+++ b/frontend/store/ressources.store.ts@@ -1,5 +1,4 @@import { defineStore } from 'pinia';-import { makeRequest } from './utils';import type { DB_Ressource } from './db_strustures';export const useRessourcesStore = defineStore('ressources', {state: () => ({diff --git a/frontend/store/utils.ts b/frontend/store/utils.tsindex b61b46b2..2c65d18e 100644--- a/frontend/store/utils.ts+++ b/frontend/store/utils.ts@@ -1,5 +1,3 @@-import type { DB_Category, DB_Document, DB_Ressource } from './db_strustures';-export interface APIResult<Data> {status: 'success' | 'error';message?: string;@@ -11,28 +9,3 @@ export interface FetchOptions {}export const baseUrl = import.meta.env.VITE_BASE_API?.toString() || '';-export async function makeRequest(- route: string,- method: string,- body: Object,- retry = false,-): Promise<APIResult<DB_Document | DB_Category | DB_Ressource | DB_Document[] | DB_Category[] | DB_Ressource[]>> {- try {- const response = await fetch(`${baseUrl}/api/v1/${route}`, {- method: method,- body: method == 'GET' || method == 'DELETE' ? null : JSON.stringify(body),- headers: { 'Content-type': 'application/json; charset=UTF-8' },- credentials: 'include',- });- if (response.status == 401 && !retry) {- console.log('[AUTH] Getting new access token...');- const login = await makeRequest(`auth/refreshToken/152981937240150016`, 'GET', {}, true);- if (login.status == 'success') return makeRequest(route, method, body, true);- else throw new Error('Not connected');- }- const decoded = await response.json();- return decoded;- } catch (e) {- return { status: 'error', message: (e as Error).message };- }-}