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.

New CDN system & auth V2

Smaug67393b61979b01d8
diff --git a/.gitignore b/.gitignore
index ed2187bf..554aeef6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,8 @@
uploads/images/*
uploads/webp/*
uploads/backups/*
+uploads/other/*
!uploads/images/.gitkeep
!uploads/webp/.gitkeep
!uploads/backups/.gitkeep
+!uploads/other/.gitkeep
\ No newline at end of file
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 00000000..55cfd19a
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,5 @@
+- Get cookie utility function
+- Verify data in controllers not in managers
+- Unification of error handling
+- Unification of types
+- Unification of classes / params
diff --git a/backend/app.ts b/backend/app.ts
index 066acbf6..5e671e32 100644
--- a/backend/app.ts
+++ b/backend/app.ts
@@ -4,11 +4,10 @@ import express from 'express';
import { Pool } from 'mysql2';
import type { Request, Response } from 'express';
-import type { Iroute } from './types';
-
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';
export class App {
@@ -71,7 +70,7 @@ export class App {
res.set('x-timestamp', Date.now().toString());
},
};
- this.app.use('/static', express.static(join(__dirname, '../../uploads'), staticOptions));
+ this.app.use('/static', express.static(UPLOADS_PATH, staticOptions));
this.app.listen(this.port, () => {
Logger.success(`Started on port ${this.port}`);
diff --git a/backend/classes/Categories.ts b/backend/classes/Categories.ts
index 2e35dcf3..569c1f77 100644
--- a/backend/classes/Categories.ts
+++ b/backend/classes/Categories.ts
@@ -1,5 +1,4 @@
import Base from './Base';
-import type { App } from '../app';
import type { Category, CategoryDB } from '../types';
export default class CategoriesDB extends Base {
diff --git a/backend/classes/ConnectionsLogsManager.ts b/backend/classes/ConnectionsLogsManager.ts
new file mode 100644
index 00000000..eeb33a24
--- /dev/null
+++ b/backend/classes/ConnectionsLogsManager.ts
@@ -0,0 +1,30 @@
+import Base from './Base';
+import type { ConnectionLog, ConnectionLogDB } from '../types';
+
+export default class ConnectionsLogsManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+ public getConnections(user_id: string): Promise<ConnectionLogDB[]> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>('SELECT * FROM connections WHERE user_id = ?', [user_id], async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results);
+ });
+ });
+ }
+ public createConnexion(connection: Omit<ConnectionLog, 'id' | 'timestamp'>) {
+ 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],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id, ...connection, created_timestamp: time });
+ },
+ );
+ });
+ }
+}
diff --git a/backend/classes/ConnectionsManager.ts b/backend/classes/ConnectionsManager.ts
new file mode 100644
index 00000000..bd447718
--- /dev/null
+++ b/backend/classes/ConnectionsManager.ts
@@ -0,0 +1,42 @@
+import Base from './Base';
+import type { Connection, ConnectionDB } from '../types';
+
+export default class ConnectionsLogsManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+ public getConnection(user_id: string): Promise<Connection> {
+ 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 });
+ });
+ });
+ }
+ public createConnection(connection: Connection) {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionDB[]>(
+ '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 });
+ },
+ );
+ });
+ }
+ public updateConnection(connection: Connection) {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionDB[]>(
+ 'UPDATE users_auth SET refresh_token = ?, expire_token = ?, last_login = ?, last_logout = ? WHERE user_id = ?',
+ [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 });
+ },
+ );
+ });
+ }
+}
diff --git a/backend/classes/DocumentsManager.ts b/backend/classes/DocumentsManager.ts
index d41efb3b..3bad57d5 100644
--- a/backend/classes/DocumentsManager.ts
+++ b/backend/classes/DocumentsManager.ts
@@ -1,5 +1,4 @@
import Base from './Base';
-import type { App } from '../app';
import type { Document, DocumentDB } from '../types';
export default class DocumentsManager extends Base {
diff --git a/backend/classes/RessourcesManager.ts b/backend/classes/RessourcesManager.ts
new file mode 100644
index 00000000..ea60983b
--- /dev/null
+++ b/backend/classes/RessourcesManager.ts
@@ -0,0 +1,40 @@
+import Base from './Base';
+import type { IObject, Ressource, RessourceDB } from '../types';
+import type { PartialRessource } from '../controllers/cdn.controller';
+
+export default class RessourcesManager extends Base {
+ constructor(app: App) {
+ super(app);
+ }
+ 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 createRessource(ressource: PartialRessource): 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.filename,
+ ressource.file_size,
+ ressource.file_type,
+ ressource.original_path,
+ ressource.transformed_path,
+ ressource.author_id,
+ time,
+ ],
+ async err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id, ...ressource, created_timestamp: time });
+ },
+ );
+ });
+ }
+}
diff --git a/backend/classes/Users.ts b/backend/classes/Users.ts
index 1667eb38..624340de 100644
--- a/backend/classes/Users.ts
+++ b/backend/classes/Users.ts
@@ -1,21 +1,24 @@
import Base from './Base';
-import { compare } from 'bcrypt';
-import type { IObject, UserDB } from '../types';
-import type { App } from '../app';
+import type { UserDB } from '../types';
export default class MemberClass extends Base {
constructor(app: App) {
super(app);
}
- public auth(username: string, password: string): Promise<IObject> {
+ public get(username: string): Promise<UserDB> {
return new Promise((resolve, reject) => {
- if (!username || (username && username.trim() === '')) return reject('Username must be provided.');
- if (!password || (password && password.trim() === '')) return reject('Password must be provided.');
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/password.');
- const valid = await compare(password, results[0].password);
- if (!valid) return reject('Bad username/password.');
+ 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/controllers/auth.controller.ts b/backend/controllers/auth.controller.ts
index dd1809b6..82cdefca 100644
--- a/backend/controllers/auth.controller.ts
+++ b/backend/controllers/auth.controller.ts
@@ -1,11 +1,16 @@
import UsersManager from '../classes/Users';
+import ConnectionsManager from '../classes/ConnectionsManager';
import { success, error } from '../utils/functions';
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 type { App } from '../app';
const COOKIE_CONFIG: CookieOptions = {
- maxAge: 3600000 * 3,
httpOnly: true,
domain: process.env.FRONT_DOMAIN,
secure: process.env.NODE_ENV == 'production' ? true : false,
@@ -13,20 +18,37 @@ const COOKIE_CONFIG: CookieOptions = {
};
export default class Authentification {
- Users: UsersManager;
+ usersManager: UsersManager;
+ connectionsManager: ConnectionsManager;
constructor(app: App) {
- this.Users = new UsersManager(app);
+ this.usersManager = new UsersManager(app);
+ this.connectionsManager = new ConnectionsManager(app);
}
- authentification(_: App, req: Request, res: Response): void {
- this.Users.auth(req.body.username, req.body.password)
- .then(result => {
- const token = sign({ expiresIn: '6h', userId: result.id }, process.env.JWT_SECRET || '');
- res.cookie('user_token', `${token}`, COOKIE_CONFIG); //process.env.NODE_ENV == 'production' ? 'None' : 'lax'
- res.cookie('user_id', `${result.id}`, COOKIE_CONFIG); //process.env.NODE_ENV == 'production' ? 'None' : 'lax'
- res.cookie('user_auth', `true`, { ...COOKIE_CONFIG, httpOnly: false }); //process.env.NODE_ENV == 'production' ? 'None' : 'lax'
- res.status(200).json(success({ auth: true }));
- })
- .catch(e => res.json(error(e)));
+ async authentification(_: App, req: Request, res: Response) {
+ try {
+ const user = await this.usersManager.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()) {
+ connection.refresh_token = randomBytes(64).toString('hex');
+ connection.expire_token = Date.now() + 3600000 * 24 * 1; // 1 day
+ }
+ const in_database = connection.last_login != 0;
+ connection.last_login = Date.now();
+ 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' });
+ 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 }));
+ } catch (e) {
+ if (e instanceof Error) res.status(401).json(error(e.message));
+ else res.status(500).json(error(String(e)));
+ }
}
disconnection(_: App, __: Request, res: Response): void {
res.clearCookie('user_auth', { domain: process.env.FRONT_DOMAIN });
@@ -34,4 +56,31 @@ export default class Authentification {
res.clearCookie('user_token', { domain: process.env.FRONT_DOMAIN });
res.status(200).json(success('success'));
}
+ 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);
+ 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 valid
+ const connection = await this.connectionsManager.getConnection(userId);
+ if (connection.refresh_token !== refreshToken || connection.expire_token < Date.now()) throw 'Invalid refresh token';
+
+ // Check if user still exists
+ const user = await this.usersManager.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 }));
+ } catch (e) {
+ res.status(401).json(error(e));
+ }
+ }
}
diff --git a/backend/controllers/backups.controller.ts b/backend/controllers/backups.controller.ts
index 45532783..c549ebc9 100644
--- a/backend/controllers/backups.controller.ts
+++ b/backend/controllers/backups.controller.ts
@@ -1,8 +1,6 @@
import { createWriteStream, unlinkSync, readdirSync } from 'fs';
import { spawn } from 'child_process';
-
import type { Request, Response } from 'express';
-import type { App } from '../app';
import { error, success } from '../utils/functions';
export default class CategoriesController {
diff --git a/backend/controllers/categories.controller.ts b/backend/controllers/categories.controller.ts
index a2c04b15..e9c8d460 100644
--- a/backend/controllers/categories.controller.ts
+++ b/backend/controllers/categories.controller.ts
@@ -1,31 +1,30 @@
import CategoriesManager from '../classes/Categories';
import { error, success } from '../utils/functions';
import type { Request, Response } from 'express';
-import type { App } from '../app';
export default class CategoriesController {
app: App;
- db_c: CategoriesManager;
+ manager: CategoriesManager;
constructor(app: App) {
this.app = app;
- this.db_c = new CategoriesManager(app);
+ this.manager = new CategoriesManager(app);
}
getAll(_: Request, res: Response) {
- this.db_c
+ this.manager
.getAll()
.then((result: any) => res.status(200).json(success(result)))
.catch((err: Error) => res.status(500).json(error(err.message)));
}
add(req: Request, res: Response) {
- this.db_c
+ 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)));
}
update(req: Request, res: Response) {
- this.db_c
+ this.manager
.update({
id: req.params.id!,
name: req.body.name,
@@ -38,7 +37,7 @@ export default class CategoriesController {
}
delete(req: Request, res: Response) {
- this.db_c
+ this.manager
.delete(req.params.id!)
.then(r => res.status(200).json(success(r)))
.catch(err => res.status(500).json(error(err.message)));
diff --git a/backend/controllers/cdn.controller.ts b/backend/controllers/cdn.controller.ts
index 43172102..0bc6c963 100644
--- a/backend/controllers/cdn.controller.ts
+++ b/backend/controllers/cdn.controller.ts
@@ -1,29 +1,70 @@
-import { join } from 'path';
-import { existsSync } from 'fs';
+import { access, constants } from 'fs';
import sharp from 'sharp';
-import { error, success } from '../utils/functions';
+import { MIME_TYPES_IMAGE, UPLOADS_PATH } from '../utils/constants';
import type { Request, Response } from 'express';
-import type { App } from '../app';
+import { Ressource } from '../types';
+import { error, success } from '../utils/functions';
+import RessourcesManager from '../classes/RessourcesManager';
-export function convertImageToWebp(_: App, req: Request, res: Response) {
- if (typeof req.files != 'object' || !('file' in req.files) || !req.files.file[0]) {
- res.status(400).json(error('No file provided.'));
- return;
- }
+export type PartialRessource = Omit<Ressource, 'id' | 'created_timestamp'>;
- const filename = req.files['file'][0].filename;
+export function convertImageToWebp(filename: string): Promise<string[]> {
+ return new Promise((resolve, reject) => {
+ const path = `${UPLOADS_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`)
+ .then(() => resolve([`/images/${filename}`, `/webp/${filename.split('.')[0]}.webp`]))
+ .catch(() => reject(new Error('Error converting image.')));
+ });
+ });
+}
+export default class RessourcesController {
+ app: App;
+ manager: RessourcesManager;
+ constructor(app: App) {
+ this.app = app;
+ this.manager = new RessourcesManager(app);
+ }
- if (!filename) {
- res.status(400).json(error('No file provided.'));
- return;
+ 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)));
}
- const path = join(__dirname, `../../../uploads/images/${filename}`);
+ 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: PartialRessource = {
+ filename: file.originalname,
+ file_size: file.size,
+ file_type: file.mimetype,
+ original_path: '',
+ transformed_path: '',
+ author_id: req.user_id!,
+ };
+ if (Object.keys(MIME_TYPES_IMAGE).includes(file.mimetype)) {
+ const converted = await convertImageToWebp(filename);
+ ressource.original_path = String(converted[0]);
+ ressource.transformed_path = String(converted[1]);
+ } else ressource.original_path = `/other/${filename}`;
- if (existsSync(path)) {
- sharp(path)
- .toFile(join(__dirname, `../../../uploads/webp/${filename.split('.')[0]}.webp`))
- .then(() => res.status(200).json(success(`/webp/${filename.split('.')[0]}.webp`)))
- .catch(_ => res.status(500).json(error('Error while converting image to webp.')));
- } else res.status(404).json(error('File not found.'));
+ this.manager
+ .createRessource(ressource)
+ .then(r => res.status(201).json(success(r)))
+ .catch(err => res.status(500).json(error(err.message)));
+ } catch (err) {
+ if (err instanceof Error) res.status(500).json(error(err.message));
+ res.status(500).json(error('Internal server error.'));
+ }
+ }
}
diff --git a/backend/controllers/documents.controller.ts b/backend/controllers/documents.controller.ts
index 0da6c613..806afc8c 100644
--- a/backend/controllers/documents.controller.ts
+++ b/backend/controllers/documents.controller.ts
@@ -1,31 +1,30 @@
import DocumentsManager from '../classes/DocumentsManager';
import { error, success } from '../utils/functions';
import type { Response, Request } from 'express';
-import type { App } from '../app';
import type { Document } from '../types';
export default class DocumentsController {
app: App;
- db_a: DocumentsManager;
+ manager: DocumentsManager;
constructor(app: App) {
this.app = app;
- this.db_a = new DocumentsManager(app);
+ this.manager = new DocumentsManager(app);
}
getAllDocuments(req: Request, res: Response) {
- this.db_a
+ 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)));
}
getDocument(req: Request, res: Response) {
- this.db_a
+ this.manager
.get(req.params.id as string)
.then(r => res.status(200).json(success(r)))
.catch(e => res.status(500).json(error(e)));
}
add(req: Request, res: Response): void {
- this.db_a
+ this.manager
.add({
name: req.body.name,
description: req.body.description,
@@ -35,13 +34,13 @@ export default class DocumentsController {
accessibility: req.body.accessibility,
content_markdown: req.body.content_markdown,
content_html: req.body.content_html,
- author_id: req.cookies.user_id,
+ author_id: req.user_id!,
})
.then(r => res.status(201).json(success(r)))
.catch(err => res.status(500).json(error(err.message)));
}
updateDocument(req: Request, res: Response) {
- this.db_a
+ this.manager
.put(req.params.id as string, {
name: req.body.name,
description: req.body.description,
@@ -51,13 +50,13 @@ export default class DocumentsController {
accessibility: req.body.accessibility,
content_markdown: req.body.content_markdown,
content_html: req.body.content_html,
- author_id: req.cookies.user_id,
+ author_id: req.user_id!,
})
.then(r => res.status(201).json(success(r)))
.catch(err => res.status(500).json(error(err.message)));
}
deleteDocument(req: Request, res: Response) {
- this.db_a
+ 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)));
diff --git a/backend/controllers/index.ts b/backend/controllers/index.ts
index bc03e824..4d82bc13 100644
--- a/backend/controllers/index.ts
+++ b/backend/controllers/index.ts
@@ -2,3 +2,4 @@ export * from './documents.controller';
export * from './auth.controller';
export * from './categories.controller';
export * from './cdn.controller';
+export * from './backups.controller';
diff --git a/backend/custom.d.ts b/backend/custom.d.ts
new file mode 100644
index 00000000..8d126502
--- /dev/null
+++ b/backend/custom.d.ts
@@ -0,0 +1,5 @@
+declare namespace Express {
+ export interface Request {
+ user_id?: string;
+ }
+}
diff --git a/backend/global.d.ts b/backend/global.d.ts
new file mode 100644
index 00000000..5b70ea44
--- /dev/null
+++ b/backend/global.d.ts
@@ -0,0 +1,6 @@
+declare global {
+ type App = import('./app').App;
+ type Iroute = import('./types').Iroute;
+}
+
+export {};
diff --git a/backend/main.ts b/backend/main.ts
index 3ae9254b..e1b3bf96 100644
--- a/backend/main.ts
+++ b/backend/main.ts
@@ -9,3 +9,5 @@ config({
const server: App = new App();
server.start();
+
+export default server;
diff --git a/backend/middlewares/auth.ts b/backend/middlewares/auth.ts
index ecc4e72a..b56ea42a 100644
--- a/backend/middlewares/auth.ts
+++ b/backend/middlewares/auth.ts
@@ -1,25 +1,22 @@
import { verify } from 'jsonwebtoken';
import { error } from '../utils/functions';
+import { parseCookies } from '../utils/functions';
import type { Request, Response } from 'express';
+if (!process.env.JWT_SECRET) throw 'Missing JWT_SECRET';
+
export default (req: Request, res: Response, next: Function) => {
try {
- const cookies = req.headers.cookie;
- if (cookies) {
- req.cookies = cookies.split(';').reduce((obj: any, c: string) => {
- var n: any = c.trim().split('=');
- obj[n[0]] = n[1].trim();
- return obj;
- }, {});
- }
+ req.cookies = parseCookies(req.headers.cookie);
if (!req.cookies) throw 'Missing cookies';
- if (!req.cookies.user_token) throw 'Missing token cookie.';
- if (!req.cookies.user_id) throw 'Missing token cookie.';
- if (!process.env.JWT_SECRET) throw 'Missing JWT_SECRET';
- const decoded: any = verify(req.cookies.user_token, process.env.JWT_SECRET);
- if (req.cookies.user_id != decoded.userId) throw 'Bad user';
- return next();
+ 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'));
+ req.user_id = decoded.userId;
+ return next();
+ });
} catch (err) {
- return res.status(401).json(error('Requete non authentifiée'));
+ 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.ts
index 5c059060..e08186c9 100644
--- a/backend/middlewares/multer.cdn.ts
+++ b/backend/middlewares/multer.cdn.ts
@@ -1,26 +1,16 @@
-import { join } from 'path';
import multer from 'multer';
+import { MIME_TYPES_IMAGE, ACCEPTED_MIME_TYPES, maxSize, UPLOADS_PATH } from '../utils/constants';
import type { IObject } from '../types';
-const tailleMax = 20 * 1024 * 1024; // 20MB
-
-enum MIME_TYPES_IMAGE {
- 'image/jpg' = 'jpg',
- 'image/jpeg' = 'jpg',
- 'image/png' = 'png',
- 'image/gif' = 'gif',
- 'image/webp' = 'webp',
- 'image/svg+xml' = 'svg',
-}
-
const storage = multer.diskStorage({
- destination: (_, __: Express.Multer.File, callback: Function) => {
- callback(null, `${join(__dirname, `../../../uploads/images`)}`);
+ 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`);
},
filename: (_, file: IObject, callback: Function) => {
- const mimetype = file.mimetype as unknown as keyof typeof MIME_TYPES_IMAGE;
- const extension = MIME_TYPES_IMAGE[mimetype];
- const fullName = Date.now().toString() + '.' + extension;
+ 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);
},
});
@@ -28,12 +18,12 @@ const storage = multer.diskStorage({
export default multer({
storage: storage,
limits: {
- fileSize: tailleMax,
+ fileSize: maxSize,
},
fileFilter: (_, file: IObject, cb: Function) => {
- const mimetype = file.mimetype as unknown as keyof typeof MIME_TYPES_IMAGE;
- if (MIME_TYPES_IMAGE[mimetype]) cb(null, true);
- else cb(new Error('[BAD_MIMETYPE]'));
+ const mimetype = file.mimetype as unknown as keyof typeof ACCEPTED_MIME_TYPES;
+ if (ACCEPTED_MIME_TYPES[mimetype]) cb(null, true);
+ else cb(new Error('BAD_MIMETYPE'));
},
}).fields([
{
diff --git a/backend/routes/v1/auth.ts b/backend/routes/v1/auth.ts
index 89dd08d9..9a025205 100644
--- a/backend/routes/v1/auth.ts
+++ b/backend/routes/v1/auth.ts
@@ -1,7 +1,5 @@
import { Router } from 'express';
import AuthCtrl from '../../controllers/auth.controller';
-import type { Iroute } from '../../types';
-import type { App } from '../../app';
const AuthRouter: Router = Router();
export default (client: App): Iroute => {
@@ -11,6 +9,7 @@ export default (client: App): Iroute => {
router() {
const controller = new AuthCtrl(client);
AuthRouter.post('/', (req, res) => controller.authentification(client, req, res));
+ AuthRouter.get('/refreshToken/:user_id', (req, res) => controller.refresh_access_token(req, res));
AuthRouter.get('/disconnection', (req, res) => controller.disconnection(client, req, res));
return AuthRouter;
},
diff --git a/backend/routes/v1/backup.ts b/backend/routes/v1/backup.ts
index 6b77f251..12a1ef8a 100644
--- a/backend/routes/v1/backup.ts
+++ b/backend/routes/v1/backup.ts
@@ -1,8 +1,6 @@
import { Router } from 'express';
import BackupsCtrl from '../../controllers/backups.controller';
import authMid from '../../middlewares/auth';
-import type { App } from '../../app';
-import type { Iroute } from '../../types';
const BackupsRouter: Router = Router();
diff --git a/backend/routes/v1/categories.ts b/backend/routes/v1/categories.ts
index f4e976bc..0b8d5525 100644
--- a/backend/routes/v1/categories.ts
+++ b/backend/routes/v1/categories.ts
@@ -1,8 +1,6 @@
import { Router } from 'express';
import CategoriesCtrl from '../../controllers/categories.controller';
import authMid from '../../middlewares/auth';
-import type { App } from '../../app';
-import type { Iroute } from '../../types';
const CategoriesRouter: Router = Router();
diff --git a/backend/routes/v1/cdn.ts b/backend/routes/v1/cdn.ts
index ea576e65..5783b10b 100644
--- a/backend/routes/v1/cdn.ts
+++ b/backend/routes/v1/cdn.ts
@@ -1,25 +1,20 @@
import { Router, type Request, type Response, NextFunction } from 'express';
-import * as CDNCtrl from '../../controllers/cdn.controller';
+import RessourcesController from '../../controllers/cdn.controller';
import auth from '../../middlewares/auth';
import multerCdn from '../../middlewares/multer.cdn';
-import type { Iroute } from '../../types';
-import type { App } from '../../app';
import multer from 'multer';
import { error } from '../../utils/functions';
+
const CDNRouter: Router = Router();
-export default (app: App): Iroute => {
+export default (client: App): Iroute => {
+ const controller = new RessourcesController(client);
return {
- route: 'cdn',
+ route: 'ressources',
version: 1,
router() {
- CDNRouter.post(
- '/image',
- auth,
- multerCdn,
- (req: Request, res: Response) => CDNCtrl.convertImageToWebp(app, req, res),
- multerErrors,
- );
+ CDNRouter.get('/:user_id', auth, (req: Request, res: Response) => controller.get(req, res));
+ CDNRouter.post('/', auth, multerCdn, (req: Request, res: Response) => controller.add(req, res), multerErrors);
return CDNRouter;
},
};
@@ -27,11 +22,11 @@ export default (app: App): Iroute => {
function multerErrors(err: any, _: Request, res: Response, next: NextFunction) {
if (err instanceof multer.MulterError) {
- if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json(error('File size is too large.'));
+ 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(400).json(error('Only images and vectors are alowed.'));
+ 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/routes/v1/documents.ts b/backend/routes/v1/documents.ts
index 6f707f0e..f8ab79b2 100644
--- a/backend/routes/v1/documents.ts
+++ b/backend/routes/v1/documents.ts
@@ -1,8 +1,6 @@
import { Router } from 'express';
import DocumentsCtrl from '../../controllers/documents.controller';
import authMid from '../../middlewares/auth';
-import type { App } from '../../app';
-import type { Iroute } from '../../types';
const DocumentsRouter: Router = Router();
@@ -13,7 +11,7 @@ export default (client: App): Iroute => {
version: 1,
router() {
DocumentsRouter.get('/', (req, res) => controller.getAllDocuments(req, res));
- DocumentsRouter.get('/:id', (req, res) => controller.getDocument(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));
diff --git a/backend/tsconfig.json b/backend/tsconfig.json
index 5b312e5c..98b204e3 100644
--- a/backend/tsconfig.json
+++ b/backend/tsconfig.json
@@ -38,6 +38,6 @@
// Paths
"baseUrl": "./src"
},
- "include": ["**/*"],
+ "include": ["**/*", "custom.d.ts", "global.d.ts"],
"exclude": ["node_modules", "test", "typings"]
}
diff --git a/backend/types/Structures.d.ts b/backend/types/Structures.d.ts
index 6bf4aa66..dce8248e 100644
--- a/backend/types/Structures.d.ts
+++ b/backend/types/Structures.d.ts
@@ -34,9 +34,41 @@ export interface User {
created_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;
+}
+
+export interface Connection {
+ user_id: string;
+ refresh_token: string;
+ expire_token: number;
+ last_login: number;
+ last_logout: number;
+}
+
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 ConnectionDB = RowDataPacket & Connection;
// SQL create the documents table (relation between author_id and users.id; relation between category and categories.id)
/* CREATE TABLE documents (
diff --git a/backend/utils/constants.ts b/backend/utils/constants.ts
new file mode 100644
index 00000000..329fd9f3
--- /dev/null
+++ b/backend/utils/constants.ts
@@ -0,0 +1,55 @@
+import { resolve } from 'path';
+
+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,
+ httpOnly: true,
+ secure: true,
+ sameSite: 'none',
+};
+
+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,
+};
+
+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,
+};
diff --git a/backend/utils/functions.ts b/backend/utils/functions.ts
index b8f3c730..7d6ccb01 100644
--- a/backend/utils/functions.ts
+++ b/backend/utils/functions.ts
@@ -9,11 +9,11 @@ export function success(result: any): IResponse {
return Response;
}
-export function error(message: string): IResponse {
+export function error(message: any): IResponse {
const Response: IResponse = {
status: 'error',
timestamp: Date.now(),
- message: message,
+ message: String(message),
};
return Response;
}
@@ -26,3 +26,11 @@ export function checkAndChange(obj: any) {
if (isErr(obj)) return error(obj.message || obj);
else return success(obj);
}
+
+export function parseCookies(cookies: string = ''): any {
+ return cookies.split(';').reduce((obj: any, c: string) => {
+ const n: any = c.trim().split('=');
+ obj[n[0]] = n[1].trim();
+ return obj;
+ }, {});
+}
diff --git a/frontend/.env.development b/frontend/.env.development
index 6c049a37..3f3c70c6 100644
--- a/frontend/.env.development
+++ b/frontend/.env.development
@@ -1 +1 @@
-VITE_BASE_API="http://localhost:3000"
\ No newline at end of file
+VITE_BASE_API="http://192.168.0.25:3001"
\ No newline at end of file
diff --git a/frontend/bun.lockb b/frontend/bun.lockb
index 60cd2135..c3053608 100755
Binary files a/frontend/bun.lockb and b/frontend/bun.lockb differ
diff --git a/frontend/components/DataTable.vue b/frontend/components/DataTable.vue
index 433f314d..c1fcb096 100644
--- a/frontend/components/DataTable.vue
+++ b/frontend/components/DataTable.vue
@@ -18,7 +18,7 @@
<td v-for=" (field, index) in row.fields" :key="index" :class="{ noMobile: index > 1 }">
<span v-if="!field.action" v-text="field.content"></span>
<span v-else>
- <NuxtLink :to="field.action" class="small-btn" type="button" v-text="field.content">
+ <NuxtLink :to="field.action" type="button" v-text="field.content">
</NuxtLink>
</span>
</td>
@@ -27,8 +27,8 @@
<td colspan="100%">
<div class="actions-bar">
<div class="left">
- <button type="button" class="small-btn" @click="page--">&lt;Previous</button>
- <button type="button" class="small-btn" @click="page++">Next&gt;</button>
+ <button type="button" @click="page--">&lt;Previous</button>
+ <button type="button" @click="page++">Next&gt;</button>
</div>
<div class="right">
<span>Items per page</span>
@@ -84,11 +84,12 @@ table {
width: 100%;
}
-button {
- margin-right: 20px;
+th {
+ text-align: left;
}
-.small-btn {
+button {
+ margin-right: 20px;
padding: 0.1rem 0.25rem;
font-size: 1rem;
}
diff --git a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue
index d28c1969..da80a866 100644
--- a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue
+++ b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue
@@ -1,15 +1,12 @@
<template>
<div class="editor-container">
<Toolbar style="height: fit-content;" :document="document" @execute-action="(a: string) => exec(a)" />
- <div class="editor-input">
- <input placeholder="Titre" class="title input" v-model="document.name" />
- <input placeholder="Description" class="description input" v-model="document.description" />
- <div class="markdown">
- <textarea ref="textarea" class="content markdown-input input" placeholder="Écrivez votre contenu ici..."
- v-model="document.content_markdown" @scroll="syncScroll"></textarea>
- <div v-if="showPreview" class="markdown-preview document-theme" ref="markdownPreview">
- <div v-html="html_content"></div>
- </div>
+ <input placeholder="Titre" class="title" v-model="document.name" />
+ <input placeholder="Description" class="description" v-model="document.description" />
+ <div class="markdown">
+ <textarea ref="textarea" class="content markdown-input" placeholder="Écrivez votre contenu ici..."
+ v-model="document.content_markdown" @scroll="syncScroll"></textarea>
+ <div v-if="showPreview" class="markdown-preview document-theme" ref="markdownPreview" v-html="html_content">
</div>
</div>
</div>
@@ -81,6 +78,7 @@ function exec(action: string) {
emit('save', document.value);
break;
}
+ document.value.content_html = compile(document.value.content_markdown, true);
}
const markdownPreview = ref<HTMLDivElement>();
@@ -98,13 +96,8 @@ function syncScroll() {
width: 100%;
}
-.editor-input,
-.markdown {
- height: 100%;
- width: 100%;
-}
-
.markdown {
+ height: 80%;
display: flex;
}
@@ -112,26 +105,29 @@ function syncScroll() {
.markdown-preview {
flex: 1;
overflow: auto;
- min-height: 75vh;
}
-.input {
+.markdown-preview {
+ position: relative;
+}
+
+input,
+textarea {
border: none;
outline: none;
background-color: var(--bg-color);
padding-left: 0;
+}
- &.title {
- font-size: 24px;
- font-weight: bold;
- margin-bottom: 10px;
- }
-
- &.description {
- font-size: 18px;
- font-weight: bold;
- margin-bottom: 10px;
- }
+.title {
+ font-size: 24px;
+ font-weight: bold;
+ margin-bottom: 10px;
+}
+.description {
+ font-size: 18px;
+ font-weight: bold;
+ margin-bottom: 10px;
}
</style>
\ No newline at end of file
diff --git a/frontend/components/MarkdownEditor/LazyToolbar.vue b/frontend/components/MarkdownEditor/LazyToolbar.vue
index 7d6cec17..254567a2 100644
--- a/frontend/components/MarkdownEditor/LazyToolbar.vue
+++ b/frontend/components/MarkdownEditor/LazyToolbar.vue
@@ -1,8 +1,7 @@
<template>
<div class="toolbar">
- <span v-for="item in toolbar" :key="item.name" v-html="item.icon" class="btn"
- @click="emitAction(item.action)"></span>
- <!--<input placeholder="#tags" class="tags input" v-model="copy.tags" style="margin-right:5px;" />-->
+ <button v-for="item in toolbar" :key="item.name" v-html="item.icon" class="btn"
+ @click="emitAction(item.action)"></button>
<select v-model="copy.accessibility" style="margin-right:5px;">
<option value="1">Visible</option>
<option value="2">Draf</option>
@@ -15,20 +14,14 @@
</option>
</optgroup>
</select>
- <select v-model="copy.parent_id">
- <option selected :value="null"> No parent </option>
- <option v-for="doc in documentsStore.getByCategories(copy.category || '')" :value="doc.id" :key="doc.id"
- v-text="doc.name">
- </option>
- </select>
+
</div>
</template>
<script setup lang="ts">
-import { useCategoriesStore, useDocumentsStore, type Document } from "~/store";
+import { useCategoriesStore, type Document } from "~/store";
const categoriesStore = useCategoriesStore();
-const documentsStore = useDocumentsStore();
const props = defineProps<{ document: Partial<Document> }>();
const copy = ref(props.document);
const emit = defineEmits(['execute-action']);
@@ -105,22 +98,17 @@ const toolbar = [
<style scoped lang="scss">
button {
- padding: 5px 0;
+ padding: 3px 5px 3px 0;
margin: 0;
+ transform: none;
}
.toolbar {
- margin-bottom: 10px;
user-select: none;
display: flex;
align-items: center;
}
-.btn {
- margin-right: 5px;
- cursor: pointer;
-}
-
svg,
.toolbar:deep(svg) {
fill: var(--font-color);
diff --git a/frontend/components/MediumView.vue b/frontend/components/MediumView.vue
index f7377b33..153c8029 100644
--- a/frontend/components/MediumView.vue
+++ b/frontend/components/MediumView.vue
@@ -16,7 +16,7 @@ const transition = computed(() => isResizing.value ? 'none' : 'margin-left 0.3s'
.medium-view {
padding: 0 2rem;
width: 100%;
- height: 60px;
+ height: 100%;
}
@media print {
diff --git a/frontend/helpers/markdown/index.ts b/frontend/helpers/markdown/index.ts
index 821b3e88..62adcd0a 100644
--- a/frontend/helpers/markdown/index.ts
+++ b/frontend/helpers/markdown/index.ts
@@ -4,6 +4,7 @@ import { anchorPlugin } from './anchor';
import { containerSvg } from './containers-svg';
// @ts-ignore
import underline from 'markdown-it-underline';
+import highlight from 'markdown-it-highlightjs';
// @ts-ignore
import mark from 'markdown-it-mark';
import katex from 'katex';
@@ -15,6 +16,7 @@ md.use(containerSvg);
md.use(underline);
md.use(mark);
md.use(markdownItKatexPlugin);
+md.use(highlight);
function markdownItKatexPlugin(md: any) {
// Nous ajoutons une règle en ligne (inline) après la règle 'escape' (qui échappe les caractères spéciaux)
diff --git a/frontend/pages/dashboard/cdn.vue b/frontend/pages/dashboard/cdn.vue
index 4e1aa6c2..bbbafcd2 100644
--- a/frontend/pages/dashboard/cdn.vue
+++ b/frontend/pages/dashboard/cdn.vue
@@ -13,23 +13,40 @@
sélectionner</span>.
</div>
</div>
- <button @click="submitFile" :disabled="!selectedFile">Uploader on server</button>
+ <button @click="submitFile" :disabled="!selectedFile">Uploader sur le serveur</button>
<div v-if="isLoading" class="loading-spinner"></div>
<div v-if="fileLink" class="link-section">
<input type="text" v-model="fileLink" readonly />
<button @click="copyLink">Copy link</button>
</div>
+ <h2>Ressources existantes</h2>
+ <div v-if="ressources.length" class="ressources-list">
+ <div v-for="ressource in ressources" :key="ressource.id" class="ressource-item">
+ <div class="ressource-info">
+ <span class="ressource-name">{{ ressource.filename }}</span>
+ <span class="ressource-size">{{ readableFileSize(ressource.file_size) }}</span>
+ <span class="ressource-type">{{ ressource.file_type }}</span>
+ <span class="ressource-date">{{ formatDate(ressource.created_timestamp) }}</span>
+ </div>
+ <a :href="`/static${ressource.transformed_path || ressource.original_path}`" target="_blank">View</a>
+ </div>
+ </div>
+ <div v-else>
+ Aucune ressource disponible.
+ </div>
</div>
</template>
<script setup lang="ts">
-import { useNotifications } from '~/store';
+import { useNotifications, useRessourcesStore } from '~/store';
+const ressourcesStore = useRessourcesStore();
+await ressourcesStore.fetch();
const selectedFile: Ref<File | null> = ref(null);
const isDragOver = ref(false);
const fileLink = ref('');
const fileInput: Ref<HTMLInputElement | null> = ref(null);
const isLoading = ref(false);
-
+const ressources = ressourcesStore.ressources;
const triggerFileSelect = () => fileInput.value!.click();
const handleFileSelect = (event: Event) => selectedFile.value = (event.target as HTMLInputElement | null)?.files?.[0] || null;
@@ -50,8 +67,9 @@ const submitFile = async () => {
const body = new FormData();
body.append("file", selectedFile.value);
+ clearForm();
- const response = await fetch(`${import.meta.env.VITE_BASE_API}/api/v1/cdn/image`, {
+ const response = await fetch(`${import.meta.env.VITE_BASE_API}/api/v1/ressources`, {
method: "POST",
credentials: "include",
body: body,
@@ -59,16 +77,20 @@ const submitFile = async () => {
const result = await response.json();
isLoading.value = false;
- clearForm();
- if (result.status === "success") fileLink.value = `${import.meta.env.VITE_BASE_API}/static${result.result}`;
+ if (result.status === "success") fileLink.value = `${import.meta.env.VITE_BASE_API}/static${result.result.transformed_path || result.result.original_path}`;
else useNotifications().add({ type: "error", title: "Error", message: result.message, timeout: 5000 })
}
const readableFileSize = (size: number): string => {
- let i = Math.floor(Math.log(size) / Math.log(1024));
+ const i = Math.floor(Math.log(size) / Math.log(1024));
return `${(size / Math.pow(1024, i)).toFixed(2)} ${["B", "kB", "MB", "GB", "TB"][i]}`
}
+const formatDate = (timestamp: string): string => {
+ const date = new Date(parseInt(timestamp));
+ return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
+}
+
const clearForm = () => selectedFile.value = null;
</script>
@@ -80,8 +102,6 @@ const clearForm = () => selectedFile.value = null;
gap: 1.5rem;
padding: 2rem;
border-radius: 8px;
- width: 100%;
- margin: 0 auto;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
.dropzone {
@@ -154,6 +174,67 @@ const clearForm = () => selectedFile.value = null;
transform: rotate(360deg);
}
}
+
+ .ressources-list {
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+
+ .ressource-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 1rem;
+ border: 1px solid #ddd;
+ /* Lighter border for a subtler effect */
+ border-radius: 8px;
+ background-color: #fafafa;
+ /* Light gray background for list items */
+ transition: background-color 0.2s ease, box-shadow 0.2s ease;
+
+ &:hover {
+ background-color: #e3e3e3;
+ /* Slightly darker on hover */
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+ /* Subtle shadow on hover */
+ }
+
+ .ressource-info {
+ display: flex;
+ justify-content: space-around;
+ width: 100%;
+
+ .ressource-name {
+ font-weight: bold;
+ color: #333;
+ /* Darker text for better contrast */
+ }
+
+ .ressource-size,
+ .ressource-type,
+ .ressource-date {
+ font-size: 0.9rem;
+ color: #757575;
+ }
+ }
+
+ a {
+ color: #2196f3;
+ text-decoration: none;
+ font-weight: bold;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+ }
+ }
}
.dropzone.drag-over {
@@ -165,4 +246,4 @@ const clearForm = () => selectedFile.value = null;
.file-info {
color: #2196F3;
}
-</style>
\ No newline at end of file
+</style>
diff --git a/frontend/pages/dashboard/doc/edit/[id].vue b/frontend/pages/dashboard/doc/edit/[id].vue
index bb10044e..d4037ea4 100644
--- a/frontend/pages/dashboard/doc/edit/[id].vue
+++ b/frontend/pages/dashboard/doc/edit/[id].vue
@@ -1,7 +1,5 @@
<template>
- <div v-if="document" class="edit-component">
- <MarkdownEditor ref="editor" :doc="document" @save="(data) => save(data)" />
- </div>
+ <MarkdownEditor v-if="document" ref="editor" :doc="document" @save="(data) => save(data)" />
</template>
<script lang="ts" setup>
import { useNotifications, useDocumentsStore, type Document } from '@/store';
@@ -32,9 +30,3 @@ function save(doc: Document) {
}
</script>
-<style lang="scss" scoped>
-.edit-component {
- width: 100%;
- height: 100%;
-}
-</style>
\ No newline at end of file
diff --git a/frontend/pages/dashboard/new.vue b/frontend/pages/dashboard/new.vue
index f96fa38d..3f7004e8 100644
--- a/frontend/pages/dashboard/new.vue
+++ b/frontend/pages/dashboard/new.vue
@@ -1,7 +1,5 @@
<template>
- <div class="new-component">
- <MarkdownEditor ref="editor" :doc="document" @save="(data) => save(data)" />
- </div>
+ <MarkdownEditor ref="editor" :doc="document" @save="(data) => save(data)" />
</template>
<script lang="ts" setup>
import { useNotifications, useDocumentsStore, type Document } from '@/store';
@@ -19,11 +17,4 @@ function save(doc: Document) {
.then(() => notifications.add({ title: "Success:", message: "Document posted", type: "success", timeout: 5000 }))
.catch((e) => notifications.add({ title: "Error:", message: e, type: "error", timeout: 5000 }))
}
-
-</script>
-<style lang="scss" scoped>
-.new-component {
- width: 100%;
- padding: 12px;
-}
-</style>
\ No newline at end of file
+</script>
\ No newline at end of file
diff --git a/frontend/pages/dashboard/search.vue b/frontend/pages/dashboard/search.vue
index cb28e1d6..230d5c6b 100644
--- a/frontend/pages/dashboard/search.vue
+++ b/frontend/pages/dashboard/search.vue
@@ -26,5 +26,4 @@ const rows = computed(() => documents.value.map((doc) => {
],
};
}));
-
-</script>
\ No newline at end of file
+</script>
diff --git a/frontend/store/db_strustures.d.ts b/frontend/store/db_strustures.d.ts
index 56e74cec..0ddc53c5 100644
--- a/frontend/store/db_strustures.d.ts
+++ b/frontend/store/db_strustures.d.ts
@@ -37,3 +37,13 @@ export interface User {
password: string;
created_timestamp: string;
}
+export interface DB_Ressource {
+ id: string;
+ filename: string;
+ file_size: number;
+ file_type: string;
+ original_path: string;
+ transformed_path: string;
+ author_id: string;
+ created_timestamp: string;
+}
diff --git a/frontend/store/index.ts b/frontend/store/index.ts
index cd043801..f297a1d8 100644
--- a/frontend/store/index.ts
+++ b/frontend/store/index.ts
@@ -1,5 +1,6 @@
export * from './documents.store';
export * from './categories.store';
export * from './notifications.store';
+export * from './ressources.store';
export type * from './utils';
export type * from './db_strustures';
diff --git a/frontend/store/ressources.store.ts b/frontend/store/ressources.store.ts
new file mode 100644
index 00000000..02c89e70
--- /dev/null
+++ b/frontend/store/ressources.store.ts
@@ -0,0 +1,36 @@
+import { defineStore } from 'pinia';
+import { makeRequest } from './utils';
+import type { DB_Ressource } from './db_strustures';
+export const useRessourcesStore = defineStore('ressources', {
+ state: () => ({
+ ressources: [] as DB_Ressource[],
+ }),
+ getters: {
+ getAll: state => state.ressources,
+ },
+ actions: {
+ fetch: async function () {
+ return new Promise(async (resolve, reject) => {
+ const request = await makeRequest(`ressources`, 'GET', {});
+ if (request.status == 'success') {
+ this.ressources = request.result as DB_Ressource[];
+ resolve(this.ressources);
+ } else reject(request.message);
+ });
+ },
+ post(ressource: DB_Ressource) {
+ return new Promise(async (resolve, reject) => {
+ const request = await makeRequest(`ressources`, 'POST', ressource);
+ if (request.status == 'success') resolve(this.ressources.push(request.result as DB_Ressource));
+ else reject(request.message);
+ });
+ },
+ delete(id: string) {
+ return new Promise(async (resolve, reject) => {
+ const request = await makeRequest(`ressources/${id}`, 'DELETE', {});
+ if (request.status == 'success') resolve((this.ressources = this.ressources.filter(c => c.id != id)));
+ else reject(request.message);
+ });
+ },
+ },
+});
diff --git a/frontend/store/utils.ts b/frontend/store/utils.ts
index 4c3f3e21..b61b46b2 100644
--- a/frontend/store/utils.ts
+++ b/frontend/store/utils.ts
@@ -1,4 +1,4 @@
-import type { DB_Category, DB_Document } from './db_strustures';
+import type { DB_Category, DB_Document, DB_Ressource } from './db_strustures';
export interface APIResult<Data> {
status: 'success' | 'error';
@@ -15,15 +15,22 @@ export async function makeRequest(
route: string,
method: string,
body: Object,
-): Promise<APIResult<DB_Document | DB_Category | DB_Document[] | DB_Category[]>> {
+ retry = false,
+): Promise<APIResult<DB_Document | DB_Category | DB_Ressource | DB_Document[] | DB_Category[] | DB_Ressource[]>> {
try {
- const responce = await fetch(`${baseUrl}/api/v1/${route}`, {
+ 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',
});
- const decoded = await responce.json();
+ 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 };
diff --git a/frontend/styles/code.scss b/frontend/styles/code.scss
new file mode 100644
index 00000000..8604d72d
--- /dev/null
+++ b/frontend/styles/code.scss
@@ -0,0 +1,119 @@
+@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap');
+
+pre code.hljs {
+ display: block;
+ overflow-x: auto;
+ font-family: 'JetBrains Mono', monospace;
+}
+
+pre {
+ border-radius: 8px;
+ margin: 16px 2px;
+ background: #2c333a;
+}
+
+code.hljs {
+ padding: 1em;
+ text-wrap: wrap;
+}
+
+.hljs {
+ color: #aabbcf;
+}
+
+.hljs-comment,
+.hljs-punctuation,
+.hljs-tag {
+ color: #7a7e85
+}
+
+
+
+.hljs-attribute,
+.hljs-doctag,
+.hljs-keyword,
+.hljs-meta .hljs-keyword,
+.hljs-name,
+.hljs-selector-tag {
+ color: #398ee7;
+}
+
+.hljs-deletion,
+.hljs-quote,
+.hljs-selector-class,
+.hljs-selector-id,
+.hljs-template-tag,
+.hljs-type {
+ color: #79d984
+}
+
+.hljs-number {
+ color: yellow
+}
+
+.hljs-string {
+ color: #b492ec
+}
+
+.hljs-section,
+.hljs-title {
+ color: #79d984;
+ font-weight: 700
+}
+
+.hljs-title.function_ {
+ color: #f84
+}
+
+.hljs-attr,
+.hljs-params {
+ color: #ffa500
+}
+
+.hljs-variable {
+ color: cyan;
+}
+
+.hljs-title.class_ {
+ color: #6a7be6
+}
+
+.hljs-link,
+.hljs-operator,
+.hljs-regexp,
+.hljs-selector-attr,
+.hljs-selector-pseudo,
+.hljs-symbol {
+ color: #ffa500
+}
+
+.hljs-property {
+ color: #f84
+}
+
+.hljs-addition,
+.hljs-bullet,
+.hljs-code {
+ color: #5da873
+}
+
+.hljs-built_in,
+.hljs-literal {
+ color: #79d984;
+}
+
+.hljs-meta {
+ color: #1f7199
+}
+
+.hljs-meta .hljs-string {
+ color: #38a
+}
+
+.hljs-emphasis {
+ font-style: italic
+}
+
+.hljs-strong {
+ font-weight: 700
+}
\ No newline at end of file
diff --git a/frontend/styles/main.scss b/frontend/styles/main.scss
index 91178ff9..7902e863 100644
--- a/frontend/styles/main.scss
+++ b/frontend/styles/main.scss
@@ -2,6 +2,7 @@
@import "./katex.scss";
@import "./markdown.scss";
@import "./document-theme.scss";
+@import "./code.scss";
/* only needed once */
* {
diff --git a/frontend/styles/theme.scss b/frontend/styles/theme.scss
index 4cfa2669..a138e742 100644
--- a/frontend/styles/theme.scss
+++ b/frontend/styles/theme.scss
@@ -43,20 +43,6 @@ button {
}
}
-code {
- background-color: var(--bg-contrast-2);
- border: 1px solid var(--border-color);
- border-radius: 12px;
- padding: 4px 8px;
-}
-
-/* Style pour les éléments <pre> contenant du code */
-pre code {
- display: block;
- padding: 10px;
- overflow-x: auto;
- white-space: pre-wrap;
-}
fieldset {
margin: auto;
@@ -174,13 +160,6 @@ p {
margin: 12px 0;
}
-pre {
- background: var(--bg-contrast);
- border-radius: 15px;
- overflow: auto;
- padding: 1px;
-}
-
select {
font-family: $external-font;
border: 1px solid var(--border-color);
@@ -226,21 +205,4 @@ textarea {
ul,
ol {
padding-left: 22px;
-}
-
-code {
- font-family: $external-font;
- font-size: 14px;
- padding: 2px 4px;
- color: var(--font-color);
-}
-
-/* Style pour les balises pre contenant du code */
-pre {
- position: relative;
- z-index: 1;
- margin: 0;
- padding: 16px 0;
- background: transparent;
- overflow-x: auto;
}
\ No newline at end of file
diff --git a/uploads/other/.gitkeep b/uploads/other/.gitkeep
new file mode 100644
index 00000000..e69de29b