📚 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
V5: New auth system, WYSIWYG, toolbar, shortcuts, new editor, classes, configs, css fixes, new sidebar ui, new composables
Smaug6739e86d552ab79d
diff --git a/.idea/.gitignore b/.idea/.gitignorenew file mode 100644index 00000000..b58b603f--- /dev/null+++ b/.idea/.gitignore@@ -0,0 +1,5 @@+# Default ignored files+/shelf/+/workspace.xml+# Editor-based HTTP Client requests+/httpRequests/diff --git a/.idea/Alexandrie.iml b/.idea/Alexandrie.imlnew file mode 100644index 00000000..24643cc3--- /dev/null+++ b/.idea/Alexandrie.iml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="UTF-8"?>+<module type="WEB_MODULE" version="4">+ <component name="NewModuleRootManager">+ <content url="file://$MODULE_DIR$">+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />+ <excludeFolder url="file://$MODULE_DIR$/temp" />+ <excludeFolder url="file://$MODULE_DIR$/tmp" />+ </content>+ <orderEntry type="inheritedJdk" />+ <orderEntry type="sourceFolder" forTests="false" />+ </component>+</module>\ No newline at end of filediff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xmlnew file mode 100644index 00000000..df7825df--- /dev/null+++ b/.idea/inspectionProfiles/Project_Default.xml@@ -0,0 +1,6 @@+<component name="InspectionProjectProfileManager">+ <profile version="1.0">+ <option name="myName" value="Project Default" />+ <inspection_tool class="TsLint" enabled="true" level="WARNING" enabled_by_default="true" />+ </profile>+</component>\ No newline at end of filediff --git a/.idea/modules.xml b/.idea/modules.xmlnew file mode 100644index 00000000..c615bda9--- /dev/null+++ b/.idea/modules.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<project version="4">+ <component name="ProjectModuleManager">+ <modules>+ <module fileurl="file://$PROJECT_DIR$/.idea/Alexandrie.iml" filepath="$PROJECT_DIR$/.idea/Alexandrie.iml" />+ </modules>+ </component>+</project>\ No newline at end of filediff --git a/.idea/vcs.xml b/.idea/vcs.xmlnew file mode 100644index 00000000..35eb1ddf--- /dev/null+++ b/.idea/vcs.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="UTF-8"?>+<project version="4">+ <component name="VcsDirectoryMappings">+ <mapping directory="" vcs="Git" />+ </component>+</project>\ No newline at end of filediff --git a/backend/app.ts b/backend/App.tssimilarity index 93%rename from backend/app.tsrename to backend/App.tsindex 1ffe2cff..be825b90 100644--- a/backend/app.ts+++ b/backend/App.ts@@ -16,9 +16,11 @@ export class App {public snowflake: Snowflake;public db: Pool;public config: typeof config;+ public logger: typeof Logger;constructor(c: typeof config) {Logger.debug(`Starting in ${process.env.NODE_ENV} mode...`);+ this.logger = Logger;this.config = c;this.app = express();this.port = process.env.PORT || '3000';@@ -38,8 +40,9 @@ export class App {}}private handleMiddlewares(): void {- this.app.use(express.urlencoded({ extended: true, limit: '5mb' }));- this.app.use(express.json({ limit: '5mb' }));+ this.app.use(express.urlencoded({ extended: true, limit: `20mb` }));+ this.app.use(express.json({ limit: `20mb` }));+ this.app.set('trust proxy', true);this.app.use(function (req: Request, res: Response, next: Function) {const origin = req.headers.origin;if (!origin || ![process.env.DOMAIN_CLIENT, process.env.DOMAIN_DASHBOARD].includes(origin)) return next();diff --git a/backend/classes/Base.ts b/backend/classes/Base.tsindex af1fc7a7..781f419b 100644--- a/backend/classes/Base.ts+++ b/backend/classes/Base.ts@@ -1,4 +1,4 @@-import { App } from '../app';+import { App } from '../App';export default abstract class Base<T> {// Define the app main classdiff --git a/backend/classes/ConnectionsLogsManager.ts b/backend/classes/ConnectionsLogsManager.tsindex 790aa27b..f31f2c28 100644--- a/backend/classes/ConnectionsLogsManager.ts+++ b/backend/classes/ConnectionsLogsManager.ts@@ -7,16 +7,20 @@ export class ConnectionsLogsManager extends Base<ConnectionLog> {}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);- });+ this.app.db.query<ConnectionLogDB[]>(+ 'SELECT * FROM connections_logs WHERE user_id = ?',+ [user_id],+ async (err, results) => {+ if (err) return reject('Internal database error.');+ resolve(results);+ },+ );});}- public createConnexion(connection: ConnectionLog) {+ public createConnection(connection: ConnectionLog) {return new Promise((resolve, reject) => {this.app.db.query<ConnectionLogDB[]>(- 'INSERT INTO connections (id, user_id, ip_adress, user_agent, location, type, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)',+ 'INSERT INTO connections_logs (id, user_id, ip_adress, user_agent, location, type, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)',[connection.id,connection.user_id,@@ -37,11 +41,74 @@ export class ConnectionsLogsManager extends Base<ConnectionLog> {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.ip_adress && data.ip_adress.length > 50) return 'connection log ip adress invalid';if (data.user_agent && data.user_agent.length > 200) return 'connection log user agent invalid';if (data.location && data.location.length > 200) return 'connection log location invalid';if (!data.type || data.type.length > 10) return 'connection log type invalid';if (!data.timestamp || data.timestamp.length > 50) return 'connection log timestamp invalid';return false;}+ async getLocationFromIp(ip: string): Promise<string> {+ const ipType = this.ipType(ip);+ const location_id = ipType === 'ipv4' ? await this.getLocationIdFromIpV4(ip) : await this.getLocationIdFromIpV6(ip);+ if (!location_id) return 'Unknown';+ return new Promise((resolve, reject) => {+ this.app.db.query<ConnectionLogDB[]>(+ 'SELECT * FROM City_Locations_fr WHERE geoname_id = ?',+ [location_id],+ async (err, results) => {+ if (err) return reject(err);+ const result = results?.[0];+ if (!result) return resolve('Unknown');+ resolve(+ `${result.city_name ? result.city_name + ', ' : ''}${+ result.subdivision_1_name ? result.subdivision_1_name + ', ' : ''+ }${result.country_name ? result.country_name : ''}`,+ );+ },+ );+ });+ }+ private ipType(ip: string): string {+ if (ip.includes(':')) return 'ipv6';+ return 'ipv4';+ }+ private getLocationIdFromIpV4(ip: string): Promise<string | undefined> {+ const ip_int = ip+ .split('.')+ .map(Number)+ .reduce((acc, cur, i) => acc + cur * 256 ** (3 - i), 0)+ .toString();+ return new Promise((resolve, reject) => {+ this.app.db.query<ConnectionLogDB[]>(+ 'SELECT * FROM City_IPv4_complete WHERE ? BETWEEN network_start_integer AND network_last_integer',+ [ip_int],+ async (err, results) => {+ if (err) return reject('Internal database error.');+ resolve(results?.[0]?.geoname_id);+ },+ );+ });+ }+ private getLocationIdFromIpV6(ip: string): Promise<string | undefined> {+ const ip_int = ip+ .split(':')+ .map(str => BigInt(parseInt(str, 16)))+ .reduce(function (int, value) {+ return BigInt(int) * BigInt(65536) + BigInt(value);+ });++ console.log(ip_int);++ return new Promise((resolve, reject) => {+ this.app.db.query<ConnectionLogDB[]>(+ 'SELECT * FROM City_IPv6_complete WHERE ? BETWEEN network_start_integer AND network_last_integer',+ [ip_int],+ async (err, results) => {+ if (err) return reject('Internal database error.');+ resolve(results?.[0]?.geoname_id);+ },+ );+ });+ }}diff --git a/backend/classes/ConnectionsManager.ts b/backend/classes/ConnectionsManager.tsdeleted file mode 100644index dc184e82..00000000--- a/backend/classes/ConnectionsManager.ts+++ /dev/null@@ -1,48 +0,0 @@-import Base from './Base';-import type { Connection, ConnectionDB } from '../types';--export class ConnectionsManager extends Base<Connection> {- 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 => {- 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);- },- );- });- }- 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/SessionsManager.ts b/backend/classes/SessionsManager.tsnew file mode 100644index 00000000..406c4df2--- /dev/null+++ b/backend/classes/SessionsManager.ts@@ -0,0 +1,90 @@+import Base from './Base';+import type { Session, SessionDB } from '../types';++export class SessionsManager extends Base<Session> {+ constructor(app: App) {+ super(app);+ setInterval(() => this.deleteOldSessions(), 1000 * 60 * 60); // 1 hour+ }+ public getSession(token: string): Promise<Session | undefined> {+ return new Promise((resolve, reject) => {+ this.app.db.query<SessionDB[]>('SELECT * FROM sessions WHERE refresh_token = ?', [token], async (err, results) => {+ if (err) return reject('Internal database error.');+ resolve(results[0]);+ });+ });+ }+ public createConnection(session: Session) {+ return new Promise((resolve, reject) => {+ this.app.db.query<SessionDB[]>(+ 'INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, login_timestamp, logout_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',+ [+ session.id,+ session.user_id,+ session.refresh_token,+ session.expire_token,+ session.last_refresh_timestamp,+ session.active,+ session.login_timestamp,+ session.logout_timestamp,+ ],+ async err => {+ if (err) return reject('Internal database error.');+ resolve(session);+ },+ );+ });+ }+ public updateConnection(session: Session): Promise<Session> {+ return new Promise((resolve, reject) => {+ this.app.db.query<SessionDB[]>(+ 'UPDATE sessions SET refresh_token = ?, expire_token = ?, last_refresh_timestamp = ?, active = ?, login_timestamp = ?, logout_timestamp = ? WHERE id = ?',+ [+ session.refresh_token,+ session.expire_token,+ session.last_refresh_timestamp,+ session.active,+ session.login_timestamp,+ session.logout_timestamp,+ session.id,+ ],+ async err => {+ if (err) return reject('Internal database error.');+ resolve(session);+ },+ );+ });+ }+ deleteSession(refresh_token: string): Promise<boolean> {+ return new Promise((resolve, reject) => {+ this.app.db.query<SessionDB[]>('DELETE FROM sessions WHERE refresh_token = ?', [refresh_token], async err => {+ if (err) return reject('Internal database error.');+ resolve(true);+ });+ });+ }+ deleteOldSessions(): Promise<boolean> {+ return new Promise((resolve, reject) => {+ this.app.logger.info('[SESSIONS] Deleting old sessions...');+ this.app.db.query<SessionDB[]>(+ 'DELETE FROM sessions WHERE expire_token < ? OR active = 0',+ [Date.now().toString()],+ async err => {+ if (err) return reject('Internal database error.');+ resolve(true);+ },+ );+ });+ }+ public validate(data: Session): string | false {+ if (!data.id || data.id.length > 50) return 'session user id invalid';+ if (!data.user_id || data.user_id.length > 50) return 'session user id invalid';+ if (data.refresh_token && data.refresh_token.length > 200) return 'session refresh token invalid';+ if (!data.expire_token) return 'session expire token invalid';+ if (!data.last_refresh_timestamp) return 'session last refresh invalid';+ if (data.active != 0 && data.active != 1) return 'session active invalid';+ if (!data.login_timestamp) return 'session last login invalid';+ if (!data.logout_timestamp) return 'session last logout invalid';+ return false;+ }+}diff --git a/backend/classes/index.ts b/backend/classes/index.tsindex a6112a3d..61a82fae 100644--- a/backend/classes/index.ts+++ b/backend/classes/index.ts@@ -1,6 +1,6 @@export * from './CategoriesManager';export * from './ConnectionsLogsManager';-export * from './ConnectionsManager';+export * from './SessionsManager';export * from './DocumentsManager';export * from './RessourcesManager';export * from './UsersManager';diff --git a/backend/config.ts b/backend/config.tsindex bbd025aa..2fbbf1cc 100644--- a/backend/config.ts+++ b/backend/config.ts@@ -3,6 +3,7 @@ import { resolve } from 'path';export const config = {max_file_size: 20 * 1024 * 1024, // 20MBupload_path: resolve(__dirname, '../uploads'),- access_token_expiration: '5s',- refresh_token_expiration: 10 * 1000, // 1 days+ access_token_expiration: '1800s',+ access_token_expiration_ms: 1800 * 1000,+ refresh_token_expiration: 7 * 24 * 60 * 60 * 1000,};diff --git a/backend/controllers/auth.controller.ts b/backend/controllers/auth.controller.tsindex 0e333e8d..2de1663c 100644--- a/backend/controllers/auth.controller.ts+++ b/backend/controllers/auth.controller.ts@@ -3,85 +3,133 @@ import { sign } from 'jsonwebtoken';import { compare } from 'bcrypt';import BaseController from './BaseController';-import { UsersManager, ConnectionsManager } from '../classes';-import type { Connection, User } from '../types';+import { UsersManager, SessionsManager, ConnectionsLogsManager } from '../classes';++import type { Session, User, ConnectionLog } from '../types';import type { Request, Response } from 'express';export default class Authentification extends BaseController<UsersManager, User> {- connectionsManager: ConnectionsManager;+ sessions: SessionsManager;+ logs: ConnectionsLogsController;constructor(app: App) {super(new UsersManager(app));- this.connectionsManager = new ConnectionsManager(app);+ this.sessions = new SessionsManager(app);+ this.logs = new ConnectionsLogsController(app);}- async authentification(_: App, req: Request, res: Response) {+ public async login(req: Request, res: Response) {try {- console.log('\x1b[44m[AUTH]\x1b[0m Initial connection');+ this.app.logger.info(`[AUTH] User ${req.body.username} is trying to connect...`);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);+ const session: Session = {+ id: this.app.snowflake.generate().toString(),+ user_id: user.id,+ refresh_token: this.generate_refresh_token(),+ expire_token: (Date.now() + this.app.config.refresh_token_expiration).toString(),+ last_refresh_timestamp: '0',+ active: 1,+ login_timestamp: Date.now().toString(),+ logout_timestamp: '0',+ };- if (!connection.refresh_token || BigInt(connection.expire_token) < Date.now()) {- connection.refresh_token = randomBytes(64).toString('hex');- 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().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: this.app.config.access_token_expiration,- });+ await this.sessions.createConnection(session);+ const accessToken = this.sign_access_token(user);console.log(`[AUTH] User ${user.id} connected. Signing new token...`);- 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 });+ this.set_cookies(res, accessToken, session.refresh_token);res.status(200).json(this.utils.success({ auth: true }));- console.log('\x1b[42m[AUTH]\x1b[0m Connection successful');+ this.app.logger.success(`[AUTH] User ${user.username} connected.`);+ this.logs.add(req, 'login', user.id);} catch (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 {+ public logout(_: 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(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) {- console.log('\x1b[44m[AUTH]\x1b[0m Refreshing access token');++ public async refresh_session(req: Request, res: Response) {+ this.app.logger.info(`[AUTH] Refreshing access token...`);req.cookies = this.utils.parseCookies(req.headers.cookie);- const userId = req.params.user_id;const refreshToken = req.cookies.user_refresh_token;try {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 || BigInt(connection.expire_token) < Date.now())- throw 'Invalid refresh token';+ const session = await this.sessions.getSession(refreshToken);+ if (!session) throw 'Session not found';+ if (BigInt(session.expire_token) < Date.now()) throw 'Refresh_token expired';// Check if user still exists- const user = await this.manager.getById(userId);+ const user = await this.manager.getById(session?.user_id);if (!user) throw 'User not found'; // if user deleted account- 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 });++ const new_session: Session = await this.sessions.updateConnection({+ ...session,+ refresh_token: this.generate_refresh_token(),+ expire_token: (Date.now() + this.app.config.refresh_token_expiration).toString(),+ last_refresh_timestamp: Date.now().toString(),+ });+ const accessToken = this.sign_access_token(user);+ this.set_cookies(res, accessToken, new_session.refresh_token);res.status(200).json(this.utils.success({ auth: true }));- console.log('\x1b[42m[AUTH]\x1b[0m Access token refreshed');+ this.app.logger.success(`[AUTH] User ${user.username} refreshed token.`);} catch (e) {- console.log('\x1b[41m[AUTH]\x1b[0m Error during refresh access token');- console.error(e);- res.clearCookie('user_auth');+ this.app.logger.error(`[AUTH] Error while refreshing token: ${e}`);+ this.sessions.deleteSession(refreshToken);res.status(401).json(this.utils.error(e));}}+ private async check_password(user: User, password: string): Promise<boolean> {+ const valid = await compare(password, user.password);+ return valid;+ }+ private sign_access_token(user: User): string {+ return sign({ userId: user.id }, process.env.JWT_SECRET || '', {+ expiresIn: this.app.config.access_token_expiration,+ });+ }+ private generate_refresh_token(): string {+ return randomBytes(40).toString('hex');+ }+ private set_cookies(res: Response, accessToken: string, refreshToken: string): void {+ res.cookie('user_token', `${accessToken}`, {+ ...this.utils.COOKIE_CONFIG,+ maxAge: this.app.config.access_token_expiration_ms,+ });+ res.cookie('user_refresh_token', `${refreshToken}`, {+ ...this.utils.COOKIE_CONFIG,+ maxAge: this.app.config.refresh_token_expiration,+ });+ }+}++class ConnectionsLogsController extends BaseController<ConnectionsLogsManager, ConnectionLog> {+ constructor(app: App) {+ super(new ConnectionsLogsManager(app));+ }++ async add(req: Request, type: string, user_id: string) {+ this.app.logger.info(`[CONNECTIONS LOGS] Adding connection log...`);+ try {+ const ip = req.ip || req.headers['x-forwarded-for']?.toString() || req.socket.remoteAddress || '';+ const location = await this.manager.getLocationFromIp(ip);+ const connectionLog: ConnectionLog = {+ id: this.app.snowflake.generate().toString(),+ user_id,+ ip_adress: ip,+ user_agent: req.get('user-agent'),+ location,+ type,+ timestamp: Date.now().toString(),+ };+ const err = this.manager.validate(connectionLog);+ if (!err) this.manager.createConnection(connectionLog);+ } catch (e) {+ this.app.logger.error(`[CONNECTIONS LOGS] Error while adding connection log: ${e}`);+ }+ }}diff --git a/backend/controllers/backups.controller.ts b/backend/controllers/backups.controller.tsindex b6687648..a2417cd6 100644--- a/backend/controllers/backups.controller.ts+++ b/backend/controllers/backups.controller.ts@@ -3,7 +3,7 @@ import { spawn } from 'child_process';import { error, success } from '../utils/functions';import type { Request, Response } from 'express';-export default class CategoriesController {+export default class BackupController {app: App;constructor(app: App) {this.app = app;diff --git a/backend/controllers/categories.controller.ts b/backend/controllers/categories.controller.tsindex 2bae2c61..a1a561ca 100644--- a/backend/controllers/categories.controller.ts+++ b/backend/controllers/categories.controller.ts@@ -1,7 +1,7 @@import BaseController from './BaseController';import { CategoriesManager } from '../classes';import type { Request, Response } from 'express';-import { Category } from '../types';+import type { Category } from '../types';export default class CategoriesController extends BaseController<CategoriesManager, Category> {constructor(app: App) {diff --git a/backend/global.d.ts b/backend/global.d.tsindex 5b70ea44..a5624352 100644--- a/backend/global.d.ts+++ b/backend/global.d.ts@@ -1,5 +1,5 @@declare global {- type App = import('./app').App;+ type App = import('./App').App;type Iroute = import('./types').Iroute;}diff --git a/backend/main.ts b/backend/main.tsindex 0870c22b..6f8743a5 100644--- a/backend/main.ts+++ b/backend/main.ts@@ -1,6 +1,6 @@import { resolve } from 'path';import { config as constants } from './config';-import { App } from './app';+import { App } from './App';import { config } from 'dotenv';config({diff --git a/backend/middlewares/auth.ts b/backend/middlewares/auth.tsindex be9b90ba..617cdae0 100644--- a/backend/middlewares/auth.ts+++ b/backend/middlewares/auth.ts@@ -1,6 +1,5 @@import { verify } from 'jsonwebtoken';-import { error } from '../utils/functions';-import { parseCookies } from '../utils/functions';+import { parseCookies, error } from '../utils';import type { Request, Response } from 'express';if (!process.env.JWT_SECRET) throw 'Missing JWT_SECRET';@@ -9,19 +8,15 @@ export default (req: Request, res: Response, next: Function) => {try {req.cookies = parseCookies(req.headers.cookie);if (!req.cookies) throw 'Missing cookies';- if (!req.cookies.user_token && req.cookies.user_refresh_token) throw 'Missing token cookies.';+ if (!req.cookies.user_token) throw 'Missing token cookies.';verify(req.cookies.user_token, process.env.JWT_SECRET!, async (err: any, decoded: any) => {if (err) {- 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/routes/v1/auth.ts b/backend/routes/v1/auth.tsindex 9a025205..1128b849 100644--- a/backend/routes/v1/auth.ts+++ b/backend/routes/v1/auth.ts@@ -8,9 +8,9 @@ export default (client: App): Iroute => {version: 1,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));+ AuthRouter.post('/', (req, res) => controller.login(req, res));+ AuthRouter.get('/refreshToken/:user_id', (req, res) => controller.refresh_session(req, res));+ AuthRouter.get('/disconnection', (req, res) => controller.logout(req, res));return AuthRouter;},};diff --git a/backend/types/Structures.d.ts b/backend/types/Structures.d.tsindex e16425e9..c35d6984 100644--- a/backend/types/Structures.d.ts+++ b/backend/types/Structures.d.ts@@ -48,19 +48,22 @@ export interface Ressource {export interface ConnectionLog {id: string;user_id: string;- ip_adress: string;- user_agent: string;- location: string;+ ip_adress?: string;+ user_agent?: string;+ location?: string;type: string;timestamp: string; // BIGINT converted to string}-export interface Connection {+export interface Session {+ id: string;user_id: string;refresh_token: string;expire_token: string;- last_login: string;- last_logout: string;+ last_refresh_timestamp: string;+ active: number; // 0: No; 1: Yes;+ login_timestamp: string;+ logout_timestamp: string;}export type DocumentDB = RowDataPacket & Document;@@ -68,7 +71,7 @@ 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;+export type SessionDB = RowDataPacket & Session;// SQL create the documents table (relation between author_id and users.id; relation between category and categories.id)/* CREATE TABLE documents (diff --git a/backend/utils/constants.ts b/backend/utils/constants.tsindex c62f9122..9251150b 100644--- a/backend/utils/constants.ts+++ b/backend/utils/constants.ts@@ -1,7 +1,6 @@import type { CookieOptions } from 'express';const COOKIE_CONFIG: CookieOptions = {- maxAge: 3600000 * 3,httpOnly: true,domain: process.env.FRONT_DOMAIN,secure: process.env.NODE_ENV == 'production' ? true : false,diff --git a/backend/utils/index.ts b/backend/utils/index.tsindex f203a170..5764e349 100644--- a/backend/utils/index.ts+++ b/backend/utils/index.ts@@ -1,2 +1,3 @@export * from './constants';export * from './functions';+export * as Logger from './Logger';diff --git a/frontend/components/MarkdownEditor/Editor.ts b/frontend/components/MarkdownEditor/Editor.tsnew file mode 100644index 00000000..d1bf78a0--- /dev/null+++ b/frontend/components/MarkdownEditor/Editor.ts@@ -0,0 +1,148 @@+import { ref } from 'vue';+import type { Ref } from 'vue';++import MarkdownUtil from '~/components/MarkdownEditor/Utils';++export class Editor extends EventTarget {+ public area: Ref<HTMLDivElement | undefined>; // The editor area+ public util: MarkdownUtil; // The markdown utility formatter+ public showPreview: Ref<boolean> = ref(false); // Whether to show the preview or not++ public inlineToolbar: Ref<{ element: HTMLElement } | undefined>;++ constructor(area: Ref<HTMLDivElement | undefined>, inlineToolbar: Ref<{ element: HTMLElement } | undefined>) {+ super();+ this.area = area;+ this.inlineToolbar = inlineToolbar as Ref<{ element: HTMLElement }>;+ this.util = new MarkdownUtil(area);+ }++ public format(action: string) {+ switch (action) {+ case 'blue':+ this.util.inlineFormat('<blue>', '</blue>');+ break;+ case 'green':+ this.util.inlineFormat('<green>', '</green>');+ break;+ case 'red':+ this.util.inlineFormat('<red>', '</red>');+ break;+ case 'yellow':+ this.util.inlineFormat('<yellow>', '</yellow>');+ break;+ case 'pink':+ this.util.inlineFormat('<pink>', '</pink>');+ break;+ case 'bold':+ this.util.inlineFormat('<b>', '</b>');+ break;+ case 'italic':+ this.util.inlineFormat('<em>', '</em>');+ break;+ case 'underline':+ this.util.inlineFormat('__', '__');+ break;+ case 'strike':+ this.util.inlineFormat('~~', '~~');+ break;+ case 'link':+ this.util.inlineFormat('[](', ')');+ break;+ case 'image':+ this.util.inlineFormat('');+ break;+ case 'code':+ this.util.inlineFormat('`', '`');+ break;+ case 'quote':+ this.util.inlineFormat('> ', '');+ break;+ case 'list':+ this.util.inlineFormat('* ', '');+ break;+ case 'orderedList':+ this.util.inlineFormat('1. ', '');+ break;+ case 'clear':+ this.util.clear();+ break;+ case 'block':+ this.util.inlineFormat('<div class="green custom-block"><p class="custom-block-title">Block name</p>', '</div>');+ break;+ }+ }+ public handleKeydown(event: KeyboardEvent) {+ if (event.key === 'Enter') {+ event.preventDefault();+ const selection = window.getSelection();+ if (!selection) return;+ const range = selection.getRangeAt(0);++ // IF the cursor is at the end of the line, insert two new lines instead of one else insert one new line+ const textNode =+ range.startContainer.textContent?.length == range.startOffset ? document.createTextNode('\n\n') : document.createTextNode('\n');++ range.insertNode(textNode);++ range.setStartAfter(textNode);+ range.setEndAfter(textNode);+ selection.removeAllRanges();+ selection.addRange(range);+ }+ if (event.key === 'Tab') {+ event.preventDefault();+ this.util.addContent(' ');+ }+ // Ctrl + B for bold+ if (event.ctrlKey && event.key === 'b') {+ event.preventDefault();+ this.format('bold');+ }+ // Ctrl + I for italic+ if (event.ctrlKey && event.key === 'i') {+ event.preventDefault();+ this.format('italic');+ }+ // Ctrl + U for underline+ if (event.ctrlKey && event.key === 'u') {+ event.preventDefault();+ this.format('underline');+ }+ // Ctrl + K for link+ if (event.ctrlKey && event.key === 'k') {+ event.preventDefault();+ this.format('link');+ }+ // Ctrl + S for saving+ if (event.ctrlKey && event.key === 's') {+ event.preventDefault();+ this.dispatchEvent(new Event('save'));+ }+ // Ctrl + P for preview+ if (event.ctrlKey && event.key === 'p') {+ event.preventDefault();+ this.showPreview.value = !this.showPreview.value;+ }+ }++ public updateContextMenu() {+ console.log('selectionchange');++ if (!this.inlineToolbar?.value?.element) return;+ const toolbarElement = this.inlineToolbar.value.element;+ toolbarElement.style.display = 'none';+ if (!this.area?.value) return;+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0 || selection.toString().length == 0) return;+ const range = selection.getRangeAt(0);+ if (!this.area.value.contains(range.startContainer) || !this.area.value.contains(range.endContainer)) return;+ const containerRect = this.area.value?.getBoundingClientRect(); //const selectionRect = range.getBoundingClientRect();+ const rects = range.getClientRects();+ if (!containerRect) return;+ const last_rect = rects[rects.length - 1];+ toolbarElement.style.top = `${last_rect.top - containerRect.top + 25}px`;+ toolbarElement.style.left = `${last_rect.left - containerRect.left}px`;+ toolbarElement.style.display = 'flex';+ }+}diff --git a/frontend/components/MarkdownEditor/InlineToolbar.vue b/frontend/components/MarkdownEditor/InlineToolbar.vueindex 48ed2e57..a45dfbf2 100644--- a/frontend/components/MarkdownEditor/InlineToolbar.vue+++ b/frontend/components/MarkdownEditor/InlineToolbar.vue@@ -1,34 +1,38 @@<template>- <div class="i_toolbar" ref="toolbar">+ <div class="i_toolbar" ref="element"><div class="i_toolbar_swatches">- <button class="swatch blue" @click="exec('blue')"></button>- <button class="swatch green" @click="exec('green')"></button>- <button class="swatch red" @click="exec('red')"></button>- <button class="swatch yellow" @click="exec('yellow')"></button>- <button class="swatch pink" @click="exec('pink')"></button>+ <button class="swatch blue" @click="emitAction('blue')"></button>+ <button class="swatch green" @click="emitAction('green')"></button>+ <button class="swatch red" @click="emitAction('red')"></button>+ <button class="swatch yellow" @click="emitAction('yellow')"></button>+ <button class="swatch pink" @click="emitAction('pink')"></button></div><div class="i_toolbar_buttons">- <button @click="exec('bold')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M9 12L9 7.1C9 7.04477 9.04477 7 9.1 7H10.4C11.5 7 14 7.1 14 9.5C14 9.5 14 12 11 12M9 12V16.8C9 16.9105 9.08954 17 9.2 17H12.5C14 17 15 16 15 14.5C15 11.7046 11 12 11 12M9 12H11"></path></svg>+ <button @click="emitAction('bold')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M9 12L9 7.1C9 7.04477 9.04477 7 9.1 7H10.4C11.5 7 14 7.1 14 9.5C14 9.5 14 12 11 12M9 12V16.8C9 16.9105 9.08954 17 9.2 17H12.5C14 17 15 16 15 14.5C15 11.7046 11 12 11 12M9 12H11"></path></svg></button>- <button @click="exec('italic')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M13.34 10C12.4223 12.7337 11 17 11 17"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M14.21 7H14.2"></path></svg>+ <button @click="emitAction('italic')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M13.34 10C12.4223 12.7337 11 17 11 17"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M14.21 7H14.2"></path></svg></button>- <button @click="exec('strike')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.5 8.50001C13.5 7 10.935 6.66476 9.75315 7.79706C9.27092 8.25909 9 8.88574 9 9.53915C9 10.1926 9.27092 10.8192 9.75315 11.2812C10.9835 12.46 13.0165 11.5457 14.2468 12.7244C14.7291 13.1865 15 13.8131 15 14.4665C15 15.1199 14.7291 15.7466 14.2468 16.2086C12.8659 17.5317 10 17.5 9 16"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 12H18"/></svg>+ <button @click="emitAction('strike')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.5 8.50001C13.5 7 10.935 6.66476 9.75315 7.79706C9.27092 8.25909 9 8.88574 9 9.53915C9 10.1926 9.27092 10.8192 9.75315 11.2812C10.9835 12.46 13.0165 11.5457 14.2468 12.7244C14.7291 13.1865 15 13.8131 15 14.4665C15 15.1199 14.7291 15.7466 14.2468 16.2086C12.8659 17.5317 10 17.5 9 16"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 12H18"/></svg></button>- <button @click="exec('underline')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7.5V11.5C9 12.2956 9.31607 13.0587 9.87868 13.6213C10.4413 14.1839 11.2044 14.5 12 14.5C12.7956 14.5 13.5587 14.1839 14.1213 13.6213C14.6839 13.0587 15 12.2956 15 11.5V7.5"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7.71429 18H16.2857"/></svg>+ <button @click="emitAction('underline')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7.5V11.5C9 12.2956 9.31607 13.0587 9.87868 13.6213C10.4413 14.1839 11.2044 14.5 12 14.5C12.7956 14.5 13.5587 14.1839 14.1213 13.6213C14.6839 13.0587 15 12.2956 15 11.5V7.5"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7.71429 18H16.2857"/></svg></button>- <button @click="exec('link')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M7.69998 12.6L7.67896 12.62C6.53993 13.7048 6.52012 15.5155 7.63516 16.625V16.625C8.72293 17.7073 10.4799 17.7102 11.5712 16.6314L13.0263 15.193C14.0703 14.1609 14.2141 12.525 13.3662 11.3266L13.22 11.12"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M16.22 11.12L16.3564 10.9805C17.2895 10.0265 17.3478 8.5207 16.4914 7.49733V7.49733C15.5691 6.39509 13.9269 6.25143 12.8271 7.17675L11.3901 8.38588C10.0935 9.47674 9.95706 11.4241 11.0888 12.6852L11.12 12.72"></path></svg>+ <button @click="emitAction('link')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M7.69998 12.6L7.67896 12.62C6.53993 13.7048 6.52012 15.5155 7.63516 16.625V16.625C8.72293 17.7073 10.4799 17.7102 11.5712 16.6314L13.0263 15.193C14.0703 14.1609 14.2141 12.525 13.3662 11.3266L13.22 11.12"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M16.22 11.12L16.3564 10.9805C17.2895 10.0265 17.3478 8.5207 16.4914 7.49733V7.49733C15.5691 6.39509 13.9269 6.25143 12.8271 7.17675L11.3901 8.38588C10.0935 9.47674 9.95706 11.4241 11.0888 12.6852L11.12 12.72"></path></svg></button>- <button @click="exec('quote')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M9.5 8L6.11524 11.8683C6.04926 11.9437 6.04926 12.0563 6.11524 12.1317L9.5 16"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M15 8L18.3848 11.8683C18.4507 11.9437 18.4507 12.0563 18.3848 12.1317L15 16"></path></svg>+ <button @click="emitAction('quote')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M9.5 8L6.11524 11.8683C6.04926 11.9437 6.04926 12.0563 6.11524 12.1317L9.5 16"></path><path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M15 8L18.3848 11.8683C18.4507 11.9437 18.4507 12.0563 18.3848 12.1317L15 16"></path></svg></button>- <button @click="exec('code')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17C7 17 7 15.2536 7 13.5L5.5 12L7 10.5C7 8.74644 7 7 9 7"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17C17 17 17 15.2536 17 13.5L18.5 12L17 10.5C17 8.74644 17 7 15 7"/></svg>+ <button @click="emitAction('code')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17C7 17 7 15.2536 7 13.5L5.5 12L7 10.5C7 8.74644 7 7 9 7"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17C17 17 17 15.2536 17 13.5L18.5 12L17 10.5C17 8.74644 17 7 15 7"/></svg></button>- <button @click="exec('clear')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-width="2" d="M11.3536 9.31802L12.7678 7.90381C13.5488 7.12276 14.8151 7.12276 15.5962 7.90381C16.3772 8.68486 16.3772 9.95119 15.5962 10.7322L14.182 12.1464M11.3536 9.31802L7.96729 12.7043C7.40889 13.2627 7.02827 13.9739 6.8734 14.7482L6.69798 15.6253C6.55804 16.325 7.17496 16.942 7.87468 16.802L8.75176 16.6266C9.52612 16.4717 10.2373 16.0911 10.7957 15.5327L14.182 12.1464M11.3536 9.31802L14.182 12.1464"></path><line x1="15" x2="19" y1="17" y2="17" stroke="currentColor" stroke-linecap="round" stroke-width="2"></line></svg>+ <button @click="emitAction('clear')"><svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-width="2" d="M11.3536 9.31802L12.7678 7.90381C13.5488 7.12276 14.8151 7.12276 15.5962 7.90381C16.3772 8.68486 16.3772 9.95119 15.5962 10.7322L14.182 12.1464M11.3536 9.31802L7.96729 12.7043C7.40889 13.2627 7.02827 13.9739 6.8734 14.7482L6.69798 15.6253C6.55804 16.325 7.17496 16.942 7.87468 16.802L8.75176 16.6266C9.52612 16.4717 10.2373 16.0911 10.7957 15.5327L14.182 12.1464M11.3536 9.31802L14.182 12.1464"></path><line x1="15" x2="19" y1="17" y2="17" stroke="currentColor" stroke-linecap="round" stroke-width="2"></line></svg></button></div></div></template><script setup lang="ts">+const element = ref<HTMLElement>();+const emit = defineEmits(['execute-action']);+const emitAction = (action: string) => emit('execute-action', action);+defineExpose({ element })</script>diff --git a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vueindex 3dd75832..ed388c91 100644--- a/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue+++ b/frontend/components/MarkdownEditor/LazyMarkdownEditor.vue@@ -3,129 +3,69 @@<Toolbar style="height: fit-content;" :document="document" @execute-action="(a: string) => exec(a)" /><input placeholder="Titre" class="title" v-model="document.name" /><input placeholder="Description" class="description" v-model="document.description" />- <div class="markdown" ref="container">- <InlineToolbar />- <div contenteditable="true" ref="textarea" class="textarea content markdown-input" placeholder="Écrivez votre contenu ici..."- @scroll="syncScroll" @mouseup="updateContextMenu" @input="update" @blur="update" v-html="document.content_markdown">- </div>- <div v-if="showPreview" class="markdown-preview document-theme" ref="markdownPreview" v-html="document.content_html">- </div>+ <div class="markdown">+ <InlineToolbar ref="toolbar" @execute-action="(a: string) => exec(a)" />+ <div contenteditable="true" ref="textarea" class="textarea content markdown-input" @scroll="syncScroll"+ @input="update" @blur="update" @keydown="editor.handleKeydown" v-html="document.content_markdown"></div>+ <div v-if="editor.showPreview.value" class="markdown-preview document-theme" ref="markdownPreview"+ v-html="document.content_html"></div></div></div></template>-<script setup lang="ts">-import type { Document } from "~/store";-import Toolbar from "./LazyToolbar.vue";-import MarkdownUtil from "./Utils";-import compile from "~/helpers/markdown";-import InlineToolbar from "~/components/MarkdownEditor/InlineToolbar.vue";+import { Editor } from './Editor';+import Toolbar from './LazyToolbar.vue';+import compile from '~/helpers/markdown';+import InlineToolbar from '~/components/MarkdownEditor/InlineToolbar.vue';+import type { Document } from '~/store';const props = defineProps<{ doc?: Document }>();const document = ref<Document | Partial<Document>>({ ...props.doc });+const toolbar = ref<{ element: HTMLDivElement }>();const textarea = ref<HTMLDivElement>();-const container = ref<HTMLDivElement>();-const toolbar = ref<HTMLDivElement>();-const showPreview = ref(false);++const editor = new Editor(textarea, toolbar);const emit = defineEmits(['save']);-const update = () => document.value.content_html = compile(textarea.value?.innerHTML || '', true);-onMounted(() => window.addEventListener('mouseup', updateContextMenu));-onBeforeUnmount(() => window.removeEventListener('mouseup', updateContextMenu));--function updateContextMenu(){- if (!textarea.value || !toolbar.value) return;- const selection = window.getSelection();- toolbar.value.style.display = 'none';- if (!selection || selection.rangeCount === 0 || selection.toString().length == 0) return;- const range = selection.getRangeAt(0);- if (!textarea.value.contains(range.startContainer) || !textarea.value.contains(range.endContainer)) return;- const containerRect = container.value?.getBoundingClientRect(); //const selectionRect = range.getBoundingClientRect();- const rects = range.getClientRects();- if (!containerRect) return;- const last_rect = rects[rects.length -1];- toolbar.value.style.top = `${last_rect.top - containerRect.top + 25}px`;- toolbar.value.style.left = `${last_rect.left - containerRect.left /*+ last_rect.width*/}px`;- toolbar.value.style.display = "flex";-}+const update = () => {+ document.value.content_html = compile(textarea.value?.innerHTML || '');+};+const handleClick = () => editor.updateContextMenu();+++const markdownPreview = ref<HTMLDivElement>();+editor.addEventListener('save', saveDocument);++onMounted(() => window.addEventListener('mouseup', handleClick));+onBeforeUnmount(() => window.removeEventListener('mouseup', handleClick));function exec(action: string) {- const util = new MarkdownUtil(textarea.value);- if (!textarea.value) return;+ editor.format(action);switch (action) {- case 'blue':- util.inlineFormat('<blue>', '</blue>');- break;- case 'green':- util.inlineFormat('<green>', '</green>');- break;- case 'red':- util.inlineFormat('<red>', '</red>');- break;- case 'yellow':- util.inlineFormat('<yellow>', '</yellow>');- break;- case 'pink':- util.inlineFormat('<pink>', '</pink>');- break;- case 'bold':- util.inlineFormat('<b>', '</b>');- break;- case 'italic':- util.inlineFormat('<em>', '</em>');- break;- case 'underline':- util.inlineFormat('__', '__');- break;- case 'strike':- util.inlineFormat('~~', '~~');- break;- case 'link':- util.inlineFormat('[](', ')');- break;- case 'image':- util.inlineFormat('');- break;- case 'code':- util.inlineFormat('`', '`');- break;- case 'quote':- util.inlineFormat('> ', '');- break;- case 'list':- util.inlineFormat('* ', '');- break;- case 'orderedList':- util.inlineFormat('1. ', '');- break;- case 'clear':- util.clear();- break;case 'exit':- useRouter().push(document.value.id ? `/dashboard/doc/${document.value.id}` : '/dashboard')+ useRouter().push(document.value.id ? `/dashboard/doc/${document.value.id}` : '/dashboard');break;case 'preview':- showPreview.value = !showPreview.value;+ editor.showPreview.value = !editor.showPreview.value;break;case 'save':- if (!document) return;- document.value.content_markdown = textarea.value.innerHTML;- document.value.content_html = compile(document.value.content_markdown, true);- emit('save', document.value);- break;+ saveDocument();}- update();+ update();}-const markdownPreview = ref<HTMLDivElement>();-function syncScroll() {- updateContextMenu() // Update the position of the context menuif (!textarea.value || !markdownPreview.value) return;const scrollPercentage = textarea.value.scrollTop / (textarea.value.scrollHeight - textarea.value.clientHeight);markdownPreview.value.scrollTop = scrollPercentage * (markdownPreview.value.scrollHeight - markdownPreview.value.clientHeight);}+function saveDocument() {+ document.value.content_markdown = textarea.value?.innerHTML;+ document.value.content_html = compile(document.value.content_markdown, true);+ emit('save', document.value);+}+</script><style scoped lang="scss">@@ -135,30 +75,33 @@ function syncScroll() {}.markdown {- position: relative;+ position: relative;height: 80%;display: flex;}.markdown-input,.markdown-preview {+ padding: 5px;flex: 1;overflow: auto;}.markdown-preview {+ border-left: 1px solid var(--border-color);position: relative;}input,.textarea {- border: none;- outline: none;- background-color: var(--bg-color);- padding-left: 0;+ border: none;+ outline: none;+ background-color: var(--bg-color);+ padding-left: 0;}+.textarea {- white-space: break-spaces;+ white-space: break-spaces;}.title {@@ -172,4 +115,4 @@ input,font-weight: bold;margin-bottom: 10px;}-</style>\ No newline at end of file+</style>diff --git a/frontend/components/MarkdownEditor/Utils.ts b/frontend/components/MarkdownEditor/Utils.tsindex 7f54f103..2c33cf47 100644--- a/frontend/components/MarkdownEditor/Utils.ts+++ b/frontend/components/MarkdownEditor/Utils.ts@@ -1,55 +1,67 @@+let lastSelection: any = null;+class MarkdownUtil {- private editor: HTMLDivElement;+ private editor: Ref<HTMLDivElement | undefined>;- constructor(editor: HTMLDivElement) {- this.editor = editor;+ constructor(editor: Ref<HTMLDivElement | undefined>) {+ this.editor = editor;+ }+ private getEditorRange() {+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return;+ const range = selection.getRangeAt(0);+ if (!this.editor.value) return;+ // Check if the selection is within the textarea or its descendants+ if (!this.editor.value.contains(range.startContainer) || !this.editor.value.contains(range.endContainer)) return;+ return range;+ }+ // Function to create a temporary container for the selected content+ private createTempDiv(content: DocumentFragment) {+ const tempDiv = document.createElement('div');+ tempDiv.appendChild(content);+ return tempDiv;+ }+ public inlineFormat(tag1: string, tag2: string) {+ const range = this.getEditorRange();+ if (!range) return;+ const tempDiv = this.createTempDiv(range.cloneContents());+ const fragment = document.createDocumentFragment();+ tempDiv.innerHTML = tag1 + tempDiv.innerHTML.trim().replaceAll('\n', '') + tag2;+ while (tempDiv.firstChild) {+ fragment.appendChild(tempDiv.firstChild);}- public formatText() {- const selection = window.getSelection();- if (!selection || selection.isCollapsed) return;- const range = selection.getRangeAt(0);+ range.deleteContents();+ range.insertNode(fragment);+ }- // Check if the selection is within the textarea or its descendants- if (!this.editor.contains(range.startContainer) || !this.editor.contains(range.endContainer)) return;- return range;- }- // Function to create a temporary container for the selected content- private createTempDiv(content: DocumentFragment) {- const tempDiv = document.createElement('div');- tempDiv.appendChild(content);- return tempDiv;- }- private inlineFormat(tag1: string, tag2: string) {- const range = this.formatText()- if(!range) return;- const tempDiv = this.createTempDiv(range.cloneContents());- const fragment = document.createDocumentFragment();- tempDiv.innerHTML = tag1 + tempDiv.innerHTML + tag2;- while (tempDiv.firstChild) {- fragment.appendChild(tempDiv.firstChild);- }- range.deleteContents();- range.insertNode(fragment);- }-- public clear(){- const range = this.formatText()- if(!range) return;- const tempDiv = this.createTempDiv(range.cloneContents());- const parentElement: Element | null = range.commonAncestorContainer.nodeType === 3 ? range.commonAncestorContainer.parentElement as Element : range.commonAncestorContainer as Element;- if (parentElement != this.editor) {- const text = parentElement.textContent || '';- const textNode = document.createTextNode(text);- parentElement.replaceWith(textNode);- } else if(tempDiv.innerHTML != '') {- const text = tempDiv.textContent || '';- const textNode = document.createTextNode(text);- range.deleteContents();- range.insertNode(textNode);- }+ public clear() {+ const range = this.getEditorRange();+ if (!range) return;+ const tempDiv = this.createTempDiv(range.cloneContents());+ const parentElement: Element | null =+ range.commonAncestorContainer.nodeType === 3+ ? (range.commonAncestorContainer.parentElement as Element)+ : (range.commonAncestorContainer as Element);+ if (parentElement != this.editor.value) {+ const text = parentElement.textContent || '';+ const textNode = document.createTextNode(text);+ parentElement.replaceWith(textNode);+ } else if (tempDiv.innerHTML != '') {+ const text = tempDiv.textContent || '';+ const textNode = document.createTextNode(text);+ range.deleteContents();+ range.insertNode(textNode);}+ }+ public addContent(content: string) {+ const selection = window.getSelection();+ if (!selection) return;+ const range = selection.getRangeAt(0);+ const textNode = document.createTextNode(content);+ range.insertNode(textNode);+ // Move the cursor to the end of the inserted text+ range.setStartAfter(textNode);+ }}-export default MarkdownUtil;-diff --git a/frontend/components/MarkdownEditor/editor.ts b/frontend/components/MarkdownEditor/editor.tsdeleted file mode 100644index e69de29b..00000000diff --git a/frontend/composables/utils.ts b/frontend/composables/utils.tsindex 5053834f..1ef4656f 100644--- a/frontend/composables/utils.ts+++ b/frontend/composables/utils.ts@@ -45,6 +45,7 @@ export async function makeRequest(return await makeRequest(route, method, body, true);} else {console.log('\x1b[41m[AUTH]\x1b[0m Refresh token invalid. Please login again.');+ logOut();navigateTo('/login');return { status: 'error', message: 'Please login again.' };}@@ -54,3 +55,12 @@ export async function makeRequest(console.log('[SUCCESS] Response data:', decoded);return decoded;}++export function logIn() {+ if (!import.meta.client) return;+ localStorage.setItem('isLoggedIn', 'true');+}+export function logOut() {+ if (!import.meta.client) return;+ localStorage.removeItem('isLoggedIn');+}diff --git a/frontend/middleware/authentification.global.ts b/frontend/middleware/authentification.global.tsindex 3b8a1fb0..34f78813 100644--- a/frontend/middleware/authentification.global.ts+++ b/frontend/middleware/authentification.global.ts@@ -1,6 +1,9 @@export default defineNuxtRouteMiddleware((to, from) => {- const user_auth = useCookie('user_auth');- if (to.fullPath.startsWith('/dashboard') && !user_auth?.value) {+ if (!import.meta.client) return;+ const user_auth = localStorage.getItem('isLoggedIn');+ console.log(user_auth);++ if (to.fullPath.startsWith('/dashboard') && !user_auth) {return navigateTo({path: '/login',query: { redirect: to.fullPath },diff --git a/frontend/pages/login.vue b/frontend/pages/login.vueindex d8ad4216..c23b7dce 100644--- a/frontend/pages/login.vue+++ b/frontend/pages/login.vue@@ -69,7 +69,10 @@ async function connect(username: string, password: string) {});const result = await responce.json();- if (result.status == "success" && result.result.auth) router.push("/dashboard");+ if (result.status == "success" && result.result.auth) {+ logIn();+ router.push("/dashboard");+ }else errors.value.general = result.message;}diff --git a/frontend/styles/_variables.scss b/frontend/styles/_variables.scssindex 7b2b5752..6f7ba418 100644--- a/frontend/styles/_variables.scss+++ b/frontend/styles/_variables.scss@@ -14,7 +14,6 @@ $primary-400: #007bff;$primary-300: lighten($primary-400, 10%);$primary-500: darken($primary-400, 10%);-$selection-color: #e1f2ff;@import "./font.scss";@@ -29,9 +28,7 @@ $transition-duration: 0.3s;--bg-color: #fff;--bg-contrast: #F1F6FD;--bg-contrast-2: #ECF2FF;- //--bg-color: #ECF2FF;- // --bg-contrast: #e7ecf7;- // --bg-contrast-2: #cdd5dd;+ --selection-color: #e1f2ff;--font-color: #111;--border-color: rgba(0, 0, 0, 0.1);// COLORS \\@@ -62,7 +59,8 @@ $transition-duration: 0.3s;.dark-mode {--bg-color: #202025;--bg-contrast: #2e3034;- --bg-contrast-2: #2e3034;+ --bg-contrast-2: #2b2d31;+ --selection-color: #4a90e2;--font-color: #ddd;--border-color: rgba(255, 255, 255, 0.1);// COLORS \\diff --git a/frontend/styles/main.scss b/frontend/styles/main.scssindex d3931560..37fb05df 100644--- a/frontend/styles/main.scss+++ b/frontend/styles/main.scss@@ -28,11 +28,11 @@}::-moz-selection {- background-color: $selection-color;+ background-color: var(--selection-color);}::selection {- background-color: $selection-color;+ background-color: var(--selection-color);}