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 backend validation & multi-user

Smaug673984f5ab23afe8
diff --git a/backend/classes/Base.ts b/backend/classes/Base.ts
index 781f419b..672d88ae 100644
--- a/backend/classes/Base.ts
+++ b/backend/classes/Base.ts
@@ -1,6 +1,7 @@
import { App } from '../App';
+import Validator from './Validator';
-export default abstract class Base<T> {
+export default abstract class Base {
// Define the app main class
readonly app: App;
@@ -9,5 +10,5 @@ export default abstract class Base<T> {
this.app = app;
}
- public abstract validate(data: T): string | false;
+ public abstract validator: Validator;
}
diff --git a/backend/classes/CategoriesManager.ts b/backend/classes/CategoriesManager.ts
index b39f5e7b..f4249eb1 100644
--- a/backend/classes/CategoriesManager.ts
+++ b/backend/classes/CategoriesManager.ts
@@ -1,26 +1,53 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { Category, CategoryDB } from '../types';
-export class CategoriesManager extends Base<Category> {
+export class CategoriesManager extends Base {
constructor(app: App) {
super(app);
}
- public getAll(): Promise<Category[]> {
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'category id invalid' },
+ name: { minLength: 1, maxLength: 50, type: 'string', error: 'category name invalid' },
+ icon: { maxLength: 10_000, type: 'string', error: 'category icon invalid', optional: true },
+ order: { type: 'number', error: 'category order invalid', optional: true },
+ parent_id: { maxLength: 50, type: 'string', error: 'category parent id invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'category author id invalid' },
+ });
+
+ public getAll(author_id: Category['author_id']): Promise<Category[]> {
return new Promise((resolve, reject) => {
- this.app.db.query<CategoryDB[]>('SELECT * FROM `categories` ORDER BY `order`', [], (err, themes) => {
- if (err) return reject('Internal database error.');
- resolve(themes);
- });
+ this.app.db.query<CategoryDB[]>(
+ 'SELECT * FROM `categories` WHERE `author_id` = ? ORDER BY `order`',
+ [author_id],
+ (err, themes) => {
+ if (err) return reject('Internal database error.');
+ resolve(themes);
+ },
+ );
+ });
+ }
+ public get(id: Category['id'], author_id: Category['author_id']): Promise<Category | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<CategoryDB[]>(
+ 'SELECT * FROM `categories` WHERE `id` = ? AND `author_id` = ?',
+ [id, author_id],
+ (err, themes) => {
+ if (err) return reject('Internal database error.');
+ resolve(themes[0]);
+ },
+ );
});
}
public add(data: Category): Promise<Category> {
return new Promise((resolve, reject) => {
- if (!data.name) return reject(new Error('name must be provided'));
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
this.app.db.query(
- 'INSERT INTO categories (`id`, `name`,`icon`, `order`, `parent_id`) VALUES (?, ?, ?, ?, ?)',
- [data.id, data.name, data.icon, data.order, data.parent_id],
+ 'INSERT INTO categories (`id`, `name`,`icon`, `order`, `parent_id`, `author_id`) VALUES (?, ?, ?, ?, ?, ?)',
+ [data.id, data.name, data.icon, data.order, data.parent_id, data.author_id],
err => {
if (err) return reject('Internal database error.');
else resolve(data);
@@ -31,9 +58,8 @@ export class CategoriesManager extends Base<Category> {
update(data: Category): Promise<Category> {
return new Promise((resolve, reject) => {
- if (!data.id) return reject(new Error('id must be provided'));
- if (!data.name) return reject(new Error('name must be provided'));
-
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
this.app.db.query(
'UPDATE categories SET name = ?, icon = ?, `order` = ?, parent_id = ? WHERE id = ?',
[data.name, data.icon, data.order, data.parent_id, data.id],
@@ -54,12 +80,4 @@ export class CategoriesManager extends Base<Category> {
});
});
}
-
- public validate(data: Category): string | false {
- if (!data.id || data.id.length > 50) return 'category id invalid';
- if (!data.name || data.name.length > 50) return 'category name invalid';
- if (data.order && isNaN(data.order)) return 'category order invalid';
- if (data.parent_id && data.parent_id.length > 50) return 'category id invalid';
- return false;
- }
}
diff --git a/backend/classes/ConnectionsLogsManager.ts b/backend/classes/ConnectionsLogsManager.ts
index f31f2c28..9ce1be51 100644
--- a/backend/classes/ConnectionsLogsManager.ts
+++ b/backend/classes/ConnectionsLogsManager.ts
@@ -1,10 +1,22 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { ConnectionLog, ConnectionLogDB } from '../types';
-export class ConnectionsLogsManager extends Base<ConnectionLog> {
+export class ConnectionsLogsManager extends Base {
constructor(app: App) {
super(app);
}
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log id invalid' },
+ user_id: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log user id invalid' },
+ ip_adress: { maxLength: 50, type: 'string', error: 'connection log ip adress invalid', optional: true },
+ user_agent: { maxLength: 200, type: 'string', error: 'connection log user agent invalid', optional: true },
+ location: { maxLength: 200, type: 'string', error: 'connection log location invalid', optional: true },
+ type: { minLength: 1, maxLength: 10, type: 'string', error: 'connection log type invalid' },
+ timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'connection log timestamp invalid' },
+ });
+
public getConnections(user_id: string): Promise<ConnectionLogDB[]> {
return new Promise((resolve, reject) => {
this.app.db.query<ConnectionLogDB[]>(
@@ -17,6 +29,18 @@ export class ConnectionsLogsManager extends Base<ConnectionLog> {
);
});
}
+ public getLastConnection(user_id: string): Promise<ConnectionLogDB | undefined> {
+ return new Promise((resolve, reject) => {
+ this.app.db.query<ConnectionLogDB[]>(
+ 'SELECT * FROM connections_logs WHERE user_id = ? ORDER BY timestamp DESC LIMIT 1',
+ [user_id],
+ async (err, results) => {
+ if (err) return reject('Internal database error.');
+ resolve(results?.[0]);
+ },
+ );
+ });
+ }
public createConnection(connection: ConnectionLog) {
return new Promise((resolve, reject) => {
this.app.db.query<ConnectionLogDB[]>(
@@ -97,9 +121,6 @@ export class ConnectionsLogsManager extends Base<ConnectionLog> {
.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',
diff --git a/backend/classes/DocumentsManager.ts b/backend/classes/DocumentsManager.ts
index 6ec54d36..efef25eb 100644
--- a/backend/classes/DocumentsManager.ts
+++ b/backend/classes/DocumentsManager.ts
@@ -1,24 +1,34 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { Document, DocumentDB } from '../types';
-export class DocumentsManager extends Base<Document> {
+export class DocumentsManager extends Base {
constructor(app: App) {
super(app);
}
- public getAll(all?: string) {
- // If all is true, return all documents, else return only public documents (accessibility = 1)
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'document id invalid' },
+ name: { minLength: 1, maxLength: 50, type: 'string', error: 'document name invalid' },
+ description: { maxLength: 255, type: 'string', error: 'document description invalid', optional: true },
+ tags: { maxLength: 200, type: 'string', error: 'document tags invalid', optional: true },
+ category: { maxLength: 50, type: 'string', error: 'document category invalid', optional: true },
+ parent_id: { maxLength: 50, type: 'string', error: 'document parent id invalid', optional: true },
+ accessibility: { error: 'document accessibility invalid' },
+ content_markdown: { maxLength: 4_294_967_295, type: 'string', error: 'document content markdown invalid', optional: true },
+ content_html: { maxLength: 4_294_967_295, type: 'string', error: 'document content html invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'document author id invalid' },
+ created_timestamp: { maxLength: 50, type: 'string', error: 'document created timestamp invalid' },
+ updated_timestamp: { maxLength: 50, type: 'string', error: 'document updated timestamp invalid' },
+ });
+
+ public getAll(user_id: string) {
return new Promise<Document[]>((resolve, reject) => {
this.app.db.query<DocumentDB[]>(
- `SELECT id, name, description, tags, category, parent_id, accessibility, author_id, created_timestamp, updated_timestamp FROM documents ${
- all == 'true' ? '' : 'WHERE `accessibility` = 1'
- } ORDER BY \`name\``,
+ `SELECT id, name, description, tags, category, parent_id, accessibility, author_id, created_timestamp, updated_timestamp FROM documents WHERE author_id = ? ORDER BY name`,
+ [user_id],
(err, result) => {
- if (err) {
- console.error(err);
- console.error(err.stack);
- return reject('Internal database error.');
- }
+ if (err) return reject('Internal database error.');
resolve(result);
},
);
@@ -38,21 +48,22 @@ export class DocumentsManager extends Base<Document> {
);
});
}
- get(id: string) {
- return new Promise<Document>((resolve, reject) => {
- if (!id) return reject(new Error('id must be provided'));
- this.app.db.query<DocumentDB[]>('SELECT * FROM documents WHERE id = ?', [id], (err, result) => {
- if (err) return reject('Internal database error.');
- if (!result[0]) return reject('Document not found.');
- resolve(result[0]);
- });
+ get(id: string, author_id: string) {
+ return new Promise<Document | undefined>((resolve, reject) => {
+ this.app.db.query<DocumentDB[]>(
+ 'SELECT * FROM documents WHERE id = ? AND author_id = ?',
+ [id, author_id],
+ (err, result) => {
+ if (err) return reject('Internal database error.');
+ resolve(result[0]);
+ },
+ );
});
}
public add(data: Document) {
return new Promise((resolve, reject) => {
- if (!data.name) return reject(new Error('name must be provided'));
- if (!data.accessibility && data.accessibility != 0) return reject(new Error('accessibility must be provided'));
- if (!data.author_id) return reject(new Error('author_id must be provided'));
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
this.app.db.query<DocumentDB[]>(
'INSERT INTO documents (`id`, `name`, `description`, `tags`, `category`, `parent_id`, `accessibility`, `content_markdown`, `content_html`, `author_id`, `created_timestamp`, `updated_timestamp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
@@ -78,10 +89,8 @@ export class DocumentsManager extends Base<Document> {
}
public put(id: string, data: Omit<Document, 'id' | 'created_timestamp'>) {
return new Promise((resolve, reject) => {
- if (!id) return reject(new Error('id must be provided'));
- if (!data.name) return reject(new Error('name must be provided'));
- if (!data.accessibility && data.accessibility != 0) return reject(new Error('accessibility must be provided'));
- if (!data.author_id) return reject(new Error('author_id must be provided'));
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
this.app.db.query<DocumentDB[]>(
'UPDATE documents SET name = ?, description = ?, tags = ?, category = ?, parent_id = ?, accessibility = ?, content_markdown = ?, content_html = ?, updated_timestamp = ? WHERE id = ?',
[
@@ -113,20 +122,4 @@ export class DocumentsManager extends Base<Document> {
});
});
}
-
- public validate(data: Document): string | false {
- if (!data.id || data.id.length > 50) return 'document id invalid';
- if (!data.name || data.name.length > 50) return 'document name invalid';
- if (data.description && data.description.length > 255) return 'document description invalid';
- if (data.tags && data.tags.length > 200) return 'document tags invalid';
- if (data.category && data.category.length > 50) return 'document category invalid';
- if (data.parent_id && data.parent_id.length > 50) return 'document parent id invalid';
- if (!data.accessibility && data.accessibility > 10) return 'document accessibility invalid';
- if (data.content_markdown && data.content_markdown.length > 4_294_967_295) return 'document content markdown invalid';
- if (data.content_html && data.content_html.length > 4_294_967_295) return 'document content html invalid';
- if (!data.author_id || data.author_id.length > 50) return 'document author id invalid';
- if (!data.created_timestamp || data.created_timestamp.length > 50) return 'document created timestamp invalid';
- if (!data.updated_timestamp || data.updated_timestamp.length > 50) return 'document updated timestamp invalid';
- return false;
- }
}
diff --git a/backend/classes/RessourcesManager.ts b/backend/classes/RessourcesManager.ts
index 73024591..2045058b 100644
--- a/backend/classes/RessourcesManager.ts
+++ b/backend/classes/RessourcesManager.ts
@@ -1,10 +1,23 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { IObject, Ressource, RessourceDB } from '../types';
-export class RessourcesManager extends Base<Ressource> {
+export class RessourcesManager extends Base {
constructor(app: App) {
super(app);
}
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource id invalid' },
+ filename: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource filename invalid' },
+ file_size: { type: 'number', error: 'ressource file size invalid' },
+ file_type: { minLength: 1, maxLength: 100, type: 'string', error: 'ressource file type invalid' },
+ original_path: { minLength: 1, maxLength: 100, type: 'string', error: 'ressource original path invalid' },
+ transformed_path: { maxLength: 100, type: 'string', error: 'ressource transformed path invalid', optional: true },
+ author_id: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource author id invalid' },
+ created_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'ressource created timestamp invalid' },
+ });
+
public getRessources(user_id: string): Promise<Ressource[]> {
return new Promise((resolve, reject) => {
this.app.db.query<RessourceDB[]>('SELECT * FROM ressources WHERE author_id = ?', [user_id], async (err, results) => {
diff --git a/backend/classes/SessionsManager.ts b/backend/classes/SessionsManager.ts
index 406c4df2..2ad697ca 100644
--- a/backend/classes/SessionsManager.ts
+++ b/backend/classes/SessionsManager.ts
@@ -1,11 +1,24 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { Session, SessionDB } from '../types';
-export class SessionsManager extends Base<Session> {
+export class SessionsManager extends Base {
constructor(app: App) {
super(app);
setInterval(() => this.deleteOldSessions(), 1000 * 60 * 60); // 1 hour
}
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'session id invalid' },
+ user_id: { minLength: 1, maxLength: 50, type: 'string', error: 'session user id invalid' },
+ refresh_token: { maxLength: 200, type: 'string', error: 'session refresh token invalid', optional: true },
+ expire_token: { minLength: 1, maxLength: 50, type: 'string', error: 'session expire token invalid' },
+ last_refresh_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last refresh invalid' },
+ active: { type: 'number', error: 'session active invalid' },
+ login_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last login invalid' },
+ logout_timestamp: { minLength: 1, maxLength: 50, type: 'string', error: 'session last logout invalid' },
+ });
+
public getSession(token: string): Promise<Session | undefined> {
return new Promise((resolve, reject) => {
this.app.db.query<SessionDB[]>('SELECT * FROM sessions WHERE refresh_token = ?', [token], async (err, results) => {
@@ -76,15 +89,4 @@ export class SessionsManager extends Base<Session> {
);
});
}
- 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/UsersManager.ts b/backend/classes/UsersManager.ts
index 64cff933..557980ef 100644
--- a/backend/classes/UsersManager.ts
+++ b/backend/classes/UsersManager.ts
@@ -1,15 +1,29 @@
import Base from './Base';
+import { Validator } from './Validator';
import type { User, UserDB } from '../types';
-export class UsersManager extends Base<User> {
+export class UsersManager extends Base {
constructor(app: App) {
super(app);
}
+
+ public validator = new Validator({
+ id: { minLength: 1, maxLength: 50, type: 'string', error: 'user id invalid' },
+ username: { minLength: 1, maxLength: 25, type: 'string', error: 'user username invalid' },
+ firstname: { maxLength: 25, type: 'string', error: 'user firstname invalid', optional: true },
+ lastname: { maxLength: 25, type: 'string', error: 'user lastname invalid', optional: true },
+ avatar: { maxLength: 75, type: 'string', error: 'user avatar invalid', optional: true },
+ email: { maxLength: 50, type: 'string', error: 'user email invalid' },
+ password: { maxLength: 255, type: 'string', error: 'user password invalid' },
+ created_timestamp: { maxLength: 50, type: 'string', error: 'user created timestamp invalid' },
+ updated_timestamp: { maxLength: 50, type: 'string', error: 'user updated timestamp invalid' },
+ });
+
public get(username: string): Promise<UserDB> {
return new Promise((resolve, reject) => {
this.app.db.query<UserDB[]>('SELECT * FROM users WHERE username = ? LIMIT 1', [username], async (err, results) => {
if (err) return reject('Internal database error.');
- if (!results[0]) return reject('Bad username.');
+ if (!results[0]) return reject('Bad username or password.');
resolve(results[0]);
});
});
@@ -17,7 +31,7 @@ export class UsersManager extends Base<User> {
public getPublic(id: string): Promise<UserDB> {
return new Promise((resolve, reject) => {
this.app.db.query<UserDB[]>(
- 'SELECT id, username, firstname, lastname, avatar, email, created_timestamp FROM users WHERE id = ? LIMIT 1',
+ 'SELECT id, username, firstname, lastname, avatar, email, created_timestamp, updated_timestamp FROM users WHERE id = ?',
[id],
async (err, results) => {
if (err) return reject('Internal database error.');
@@ -29,23 +43,35 @@ export class UsersManager extends Base<User> {
}
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) => {
+ this.app.db.query<UserDB[]>('SELECT * FROM users WHERE id = ?', [id], async (err, results) => {
if (err) return reject('Internal database error.');
if (!results[0]) return reject('Bad user id.');
resolve(results[0]);
});
});
}
-
- public validate(data: User): string | false {
- if (!data.id || data.id.length > 50) return 'user id invalid';
- if (!data.username || data.username.length > 25) return 'user username invalid';
- if (!data.firstname || data.firstname.length > 25) return 'user firstname invalid';
- if (!data.lastname || data.lastname.length > 25) return 'user lastname invalid';
- if (!data.avatar || data.avatar.length > 75) return 'user avatar invalid';
- if (!data.email || data.email.length > 50) return 'user email invalid';
- if (!data.password || data.password.length > 255) return 'user password invalid';
- if (!data.created_timestamp || data.created_timestamp.length > 50) return 'user created timestamp invalid';
- return false;
+ public put(id: string, data: Omit<User, 'id' | 'password' | 'created_timestamp'>) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<UserDB[]>(
+ 'UPDATE users SET firstname = ?, lastname = ?, avatar = ?, email = ?, updated_timestamp = ? WHERE id = ?',
+ [data.firstname, data.lastname, data.avatar, data.email, data.updated_timestamp, id],
+ err => {
+ if (err) return reject('Internal database error.');
+ resolve({ id, ...data });
+ },
+ );
+ });
+ }
+ public updatePassword(data: Pick<User, 'password' | 'id'>) {
+ return new Promise((resolve, reject) => {
+ const error = this.validator.validate(data);
+ if (error) return reject(error);
+ this.app.db.query<UserDB[]>('UPDATE users SET password = ? WHERE id = ?', [data.password, data.id], err => {
+ if (err) return reject('Internal database error.');
+ resolve(true);
+ });
+ });
}
}
diff --git a/backend/classes/Validator.ts b/backend/classes/Validator.ts
new file mode 100644
index 00000000..d9b2a738
--- /dev/null
+++ b/backend/classes/Validator.ts
@@ -0,0 +1,50 @@
+import Logger from '../utils/Logger';
+type FieldConfig = {
+ minLength?: number;
+ maxLength?: number;
+ type?: 'string' | 'number' | 'boolean';
+ optional?: boolean;
+ error: string;
+};
+
+type ValidationConfig = {
+ [key: string]: FieldConfig;
+};
+
+export class Validator {
+ private config: ValidationConfig;
+
+ constructor(config: ValidationConfig) {
+ this.config = config;
+ }
+
+ public validate(data: Partial<Record<string, any>>): string | false {
+ for (const field in data) {
+ if (!data.hasOwnProperty(field)) continue;
+ const value = data[field];
+ const fieldConfig = this.config[field];
+ if (!fieldConfig) continue; // Skip validation for fields not in the config
+
+ if (fieldConfig.optional && !value) {
+ continue;
+ }
+
+ if (fieldConfig.type && typeof value !== fieldConfig.type) {
+ return fieldConfig.error;
+ }
+
+ if (fieldConfig.minLength && value.length < fieldConfig.minLength) {
+ return fieldConfig.error;
+ }
+
+ if (fieldConfig.maxLength && value.length > fieldConfig.maxLength) {
+ return fieldConfig.error;
+ }
+ }
+ Logger.success(`Validation passed for ${Object.keys(data)}`);
+
+ return false;
+ }
+}
+
+export default Validator;
diff --git a/backend/controllers/BaseController.ts b/backend/controllers/BaseController.ts
index d1767dba..546a5599 100644
--- a/backend/controllers/BaseController.ts
+++ b/backend/controllers/BaseController.ts
@@ -1,7 +1,7 @@
import * as utils from '../utils';
import type Base from '../classes/Base';
-export default abstract class BaseController<T extends Base<V>, V> {
+export default abstract class BaseController<T extends Base> {
public app: App;
protected manager: T;
diff --git a/backend/controllers/auth.controller.ts b/backend/controllers/auth.controller.ts
index e1312738..c5a6d5d1 100644
--- a/backend/controllers/auth.controller.ts
+++ b/backend/controllers/auth.controller.ts
@@ -8,7 +8,7 @@ import { UsersManager, SessionsManager, ConnectionsLogsManager } from '../classe
import type { Session, User, ConnectionLog } from '../types';
import type { Request, Response } from 'express';
-export default class Authentification extends BaseController<UsersManager, User> {
+export default class Authentification extends BaseController<UsersManager> {
sessions: SessionsManager;
logs: ConnectionsLogsController;
constructor(app: App) {
@@ -18,7 +18,6 @@ export default class Authentification extends BaseController<UsersManager, User>
}
public async login(req: Request, res: Response) {
try {
- 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.');
@@ -35,12 +34,9 @@ export default class Authentification extends BaseController<UsersManager, User>
await this.sessions.createConnection(session);
const accessToken = this.sign_access_token(user);
- console.log(`[AUTH] User ${user.id} connected. Signing new token...`);
this.set_cookies(res, accessToken, session.refresh_token);
const { password, ...userWithoutPassword } = user;
res.status(200).json(this.utils.success({ auth: true, user: userWithoutPassword }));
-
- this.app.logger.success(`[AUTH] User ${user.username} connected.`);
this.logs.add(req, 'login', user.id);
} catch (e) {
res.status(500).json(this.utils.error(e));
@@ -59,7 +55,6 @@ export default class Authentification extends BaseController<UsersManager, User>
const refreshToken = req.cookies.user_refresh_token;
try {
if (!refreshToken) throw 'No refresh token provided';
-
// Check if refresh token is valid
const session = await this.sessions.getSession(refreshToken);
if (!session) throw 'Session not found';
@@ -81,11 +76,12 @@ export default class Authentification extends BaseController<UsersManager, User>
this.app.logger.success(`[AUTH] User ${user.username} refreshed token.`);
} catch (e) {
this.app.logger.error(`[AUTH] Error while refreshing token: ${e}`);
- this.sessions.deleteSession(refreshToken);
+ //this.sessions.deleteSession(refreshToken);
res.status(401).json(this.utils.error(e));
}
}
private async check_password(user: User, password: string): Promise<boolean> {
+ if (!password || !user.password) return false;
const valid = await compare(password, user.password);
return valid;
}
@@ -109,7 +105,7 @@ export default class Authentification extends BaseController<UsersManager, User>
}
}
-class ConnectionsLogsController extends BaseController<ConnectionsLogsManager, ConnectionLog> {
+class ConnectionsLogsController extends BaseController<ConnectionsLogsManager> {
constructor(app: App) {
super(new ConnectionsLogsManager(app));
}
diff --git a/backend/controllers/categories.controller.ts b/backend/controllers/categories.controller.ts
index a1a561ca..82051870 100644
--- a/backend/controllers/categories.controller.ts
+++ b/backend/controllers/categories.controller.ts
@@ -1,17 +1,16 @@
import BaseController from './BaseController';
import { CategoriesManager } from '../classes';
import type { Request, Response } from 'express';
-import type { Category } from '../types';
-export default class CategoriesController extends BaseController<CategoriesManager, Category> {
+export default class CategoriesController extends BaseController<CategoriesManager> {
constructor(app: App) {
super(new CategoriesManager(app));
}
- getAll(_: Request, res: Response) {
+ getAll(req: Request, res: Response) {
this.manager
- .getAll()
+ .getAll(req.user_id!)
.then((result: any) => res.status(200).json(this.utils.success(result)))
- .catch((err: Error) => res.status(500).json(this.utils.error(err.message)));
+ .catch((err: Error) => res.status(500).json(this.utils.error(err)));
}
add(req: Request, res: Response) {
@@ -20,30 +19,36 @@ export default class CategoriesController extends BaseController<CategoriesManag
id: this.app.snowflake.generate().toString(),
name: req.body.name,
icon: req.body.icon,
- order: req.body.order,
- parent_id: req.body.parent_id,
+ order: req.body.order || 0,
+ parent_id: req.body.parent_id || null,
+ author_id: req.user_id!,
})
.then(r => res.status(201).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ .catch(err => res.status(500).json(this.utils.error(err)));
}
- update(req: Request, res: Response) {
- this.manager
- .update({
+ async update(req: Request, res: Response) {
+ try {
+ const db_cat = await this.manager.get(req.params.id!, req.user_id!);
+ if (!db_cat) return res.status(404).json(this.utils.error('Category not found or unauthorized.'));
+ const r = await this.manager.update({
id: req.params.id!,
name: req.body.name,
icon: req.body.icon,
order: req.body.order,
parent_id: req.body.parent_id,
- })
- .then(r => res.status(200).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ author_id: req.user_id!,
+ });
+ return res.status(200).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
}
delete(req: Request, res: Response) {
this.manager
.delete(req.params.id!)
.then(r => res.status(200).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ .catch(err => res.status(500).json(this.utils.error(err)));
}
}
diff --git a/backend/controllers/cdn.controller.ts b/backend/controllers/cdn.controller.ts
index 2cec331f..57e4ef3b 100644
--- a/backend/controllers/cdn.controller.ts
+++ b/backend/controllers/cdn.controller.ts
@@ -17,7 +17,7 @@ export function convertImageToWebp(upload_path: string, filename: string): Promi
});
});
}
-export default class RessourcesController extends BaseController<RessourcesManager, Ressource> {
+export default class RessourcesController extends BaseController<RessourcesManager> {
constructor(app: App) {
super(new RessourcesManager(app));
}
@@ -58,7 +58,26 @@ export default class RessourcesController extends BaseController<RessourcesManag
this.manager
.createRessource(ressource)
.then(r => res.status(201).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ .catch(err => res.status(500).json(this.utils.error(err)));
+ } catch (err) {
+ res.status(500).json(this.utils.error(err));
+ }
+ }
+
+ async addAvatar(req: Request, res: Response) {
+ try {
+ if (typeof req.files != 'object' || !('file' in req.files) || !req.files.file[0]) {
+ throw new Error('No file provided.');
+ }
+ const file = req.files['file'][0];
+ const filename = file.filename;
+
+ if (!filename) throw new Error('No file provided.');
+
+ if (Object.keys(this.utils.MIME_TYPES_IMAGE).includes(file.mimetype)) {
+ const converted = await convertImageToWebp(this.app.config.upload_path, filename);
+ res.status(201).json(this.utils.success({ original_path: converted[0], transformed_path: converted[1] }));
+ }
} catch (err) {
res.status(500).json(this.utils.error(err));
}
diff --git a/backend/controllers/documents.controller.ts b/backend/controllers/documents.controller.ts
index b9d9ee77..a89395ea 100644
--- a/backend/controllers/documents.controller.ts
+++ b/backend/controllers/documents.controller.ts
@@ -3,24 +3,27 @@ import { DocumentsManager } from '../classes';
import type { Response, Request } from 'express';
import type { Document } from '../types';
-export default class DocumentsController extends BaseController<DocumentsManager, Document> {
+export default class DocumentsController extends BaseController<DocumentsManager> {
constructor(app: App) {
super(new DocumentsManager(app));
}
getAllDocuments(req: Request, res: Response) {
this.manager
- .getAll(req.query.all?.toString())
+ .getAll(req.user_id!)
.then((result: Partial<Document>[]) => res.status(200).json(this.utils.success(result)))
.catch(e => res.status(500).json(this.utils.error(e)));
}
- getDocument(req: Request, res: Response) {
- this.manager
- .get(req.params.id as string)
- .then(r => res.status(200).json(this.utils.success(r)))
- .catch(e => res.status(500).json(this.utils.error(e)));
+ async getDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ return res.status(200).json(this.utils.success(db_doc));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
}
- add(req: Request, res: Response) {
+ async add(req: Request, res: Response) {
const document: Document = {
id: this.app.snowflake.generate().toString(),
name: req.body.name,
@@ -35,34 +38,44 @@ export default class DocumentsController extends BaseController<DocumentsManager
created_timestamp: Date.now().toString(),
updated_timestamp: Date.now().toString(),
};
- const err = this.manager.validate(document);
- if (err) return res.status(400).json(this.utils.error(err));
- return this.manager
- .add(document)
- .then(r => res.status(201).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ try {
+ const r = await this.manager.add(document);
+ return res.status(201).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
}
- updateDocument(req: Request, res: Response) {
- return this.manager
- .put(req.params.id as string, {
- name: req.body.name,
- description: req.body.description,
- tags: req.body.tags,
- category: req.body.category,
- parent_id: req.body.parent_id,
- accessibility: req.body.accessibility,
- content_markdown: req.body.content_markdown,
- content_html: req.body.content_html,
- author_id: req.user_id!,
+ async updateDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ const result = await this.manager.put(req.params.id as string, {
+ name: req.body.name ?? db_doc.name,
+ description: req.body.description ?? db_doc.description,
+ tags: req.body.tags ?? db_doc.tags,
+ category: req.body.category ?? db_doc.category,
+ parent_id: req.body.parent_id ?? db_doc.parent_id,
+ accessibility: req.body.accessibility ?? db_doc.accessibility,
+ content_markdown: req.body.content_markdown ?? db_doc.content_markdown,
+ content_html: req.body.content_html ?? db_doc.content_html,
+ author_id: db_doc.author_id,
updated_timestamp: Date.now().toString(),
- })
- .then(r => res.status(201).json(this.utils.success(r)))
- .catch(err => res.status(500).json(this.utils.error(err.message)));
+ });
+ return res.status(200).json(this.utils.success(result));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
}
- deleteDocument(req: Request, res: Response) {
- this.manager
- .delete(req.params.id as string)
- .then(r => res.status(201).json(this.utils.success(r)))
- .catch((err: Error) => res.status(500).json(this.utils.error(err.message)));
+ async deleteDocument(req: Request, res: Response) {
+ try {
+ const db_doc = await this.manager.get(req.params.id as string, req.user_id!);
+ if (!db_doc) return res.status(404).json(this.utils.error('Document not found or unauthorized.'));
+ return this.manager
+ .delete(req.params.id as string)
+ .then(r => res.status(200).json(this.utils.success(r)))
+ .catch(e => res.status(500).json(this.utils.error(e)));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
}
}
diff --git a/backend/controllers/users.controller.ts b/backend/controllers/users.controller.ts
index 8b359cb1..6372812f 100644
--- a/backend/controllers/users.controller.ts
+++ b/backend/controllers/users.controller.ts
@@ -1,17 +1,53 @@
+import { hash } from 'bcrypt';
import BaseController from './BaseController';
-import { UsersManager } from '../classes';
+import { UsersManager, ConnectionsLogsManager } from '../classes';
-import type { User } from '../types';
import type { Request, Response } from 'express';
-export default class Authentification extends BaseController<UsersManager, User> {
+export default class Authentification extends BaseController<UsersManager> {
+ connections: ConnectionsLogsManager;
constructor(app: App) {
super(new UsersManager(app));
+ this.connections = new ConnectionsLogsManager(app);
}
public async getMe(req: Request, res: Response) {
- this.manager
- .getPublic(req.user_id as string)
+ try {
+ const user = await this.manager.getPublic(req.user_id as string);
+ const last_connection = await this.connections.getLastConnection(req.user_id as string);
+ res.status(200).json(this.utils.success({ user, last_connection }));
+ } catch (e) {
+ res.status(500).json(this.utils.error(e));
+ }
+ }
+ public async update(req: Request, res: Response) {
+ const user_db = await this.manager.getById(req.params.id!);
+ if (!user_db) return res.status(404).json(this.utils.error('User not found.'));
+ if (req.params.id != req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ return this.manager
+ .put(req.params.id!, {
+ username: user_db.username,
+ firstname: req.body.firstname ?? user_db.firstname,
+ lastname: req.body.lastname ?? user_db.lastname,
+ avatar: req.body.avatar ?? user_db.avatar,
+ email: req.body.email ?? user_db.email,
+ updated_timestamp: Date.now().toString(),
+ })
.then(r => res.status(200).json(this.utils.success(r)))
.catch(e => res.status(500).json(this.utils.error(e)));
}
+ public async updatePassword(req: Request, res: Response) {
+ try {
+ const passwordStr = req.body.password as string;
+ if (!passwordStr) return res.status(400).json(this.utils.error('Password must be provided.'));
+ if (req.params.id != req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ const hashed = await hash(passwordStr, 10);
+ const r = await this.manager.updatePassword({
+ id: req.params.id!,
+ password: hashed,
+ });
+ return res.status(200).json(this.utils.success(r));
+ } catch (e) {
+ return res.status(500).json(this.utils.error(e));
+ }
+ }
}
diff --git a/backend/routes/v1/categories.ts b/backend/routes/v1/categories.ts
index 0b8d5525..774a0f70 100644
--- a/backend/routes/v1/categories.ts
+++ b/backend/routes/v1/categories.ts
@@ -10,7 +10,7 @@ export default (client: App): Iroute => {
route: 'categories',
version: 1,
router() {
- CategoriesRouter.get('/', (req, res) => controller.getAll(req, res));
+ CategoriesRouter.get('/', authMid, (req, res) => controller.getAll(req, res));
CategoriesRouter.post('', authMid, (req, res) => controller.add(req, res));
CategoriesRouter.patch('/:id', authMid, (req, res) => controller.update(req, res));
CategoriesRouter.delete('/:id', authMid, (req, res) => controller.delete(req, res));
diff --git a/backend/routes/v1/cdn.ts b/backend/routes/v1/cdn.ts
index acf6b70b..b95d70fc 100644
--- a/backend/routes/v1/cdn.ts
+++ b/backend/routes/v1/cdn.ts
@@ -14,6 +14,7 @@ export default (client: App): Iroute => {
version: 1,
router() {
CDNRouter.get('/', auth, (req: Request, res: Response) => controller.get(req, res));
+ CDNRouter.post('/avatar', auth, multerCdn, (req: Request, res: Response) => controller.addAvatar(req, res), multerErrors);
CDNRouter.post('/', auth, multerCdn, (req: Request, res: Response) => controller.add(req, res), multerErrors);
return CDNRouter;
},
diff --git a/backend/routes/v1/documents.ts b/backend/routes/v1/documents.ts
index f8ab79b2..1221eac0 100644
--- a/backend/routes/v1/documents.ts
+++ b/backend/routes/v1/documents.ts
@@ -10,7 +10,7 @@ export default (client: App): Iroute => {
route: 'documents',
version: 1,
router() {
- DocumentsRouter.get('/', (req, res) => controller.getAllDocuments(req, res));
+ DocumentsRouter.get('/', authMid, (req, res) => controller.getAllDocuments(req, res));
DocumentsRouter.get('/:id', authMid, (req, res) => controller.getDocument(req, res));
DocumentsRouter.post('/', authMid, (req, res) => controller.add(req, res));
DocumentsRouter.patch('/:id', authMid, (req, res) => controller.updateDocument(req, res));
diff --git a/backend/routes/v1/users.ts b/backend/routes/v1/users.ts
index 88a12d18..9a2deaa0 100644
--- a/backend/routes/v1/users.ts
+++ b/backend/routes/v1/users.ts
@@ -11,6 +11,9 @@ export default (client: App): Iroute => {
version: 1,
router() {
UsersRouter.get('/@me', authMid, (req, res) => controller.getMe(req, res));
+ UsersRouter.patch('/:id/password', authMid, (req, res) => controller.updatePassword(req, res));
+ UsersRouter.patch('/:id', authMid, (req, res) => controller.update(req, res));
+
//UsersRouter.get('/:id', authMid, (req, res) => controller.getDocument(req, res));
//UsersRouter.post('/', (req, res) => controller.add(req, res));
//UsersRouter.patch('/:id', authMid, (req, res) => controller.updateDocument(req, res));
diff --git a/backend/types/Structures.d.ts b/backend/types/Structures.d.ts
index c35d6984..0635b69b 100644
--- a/backend/types/Structures.d.ts
+++ b/backend/types/Structures.d.ts
@@ -21,6 +21,7 @@ export interface Category {
icon?: string;
order?: number;
parent_id?: string;
+ author_id: string;
}
export interface User {
@@ -32,6 +33,7 @@ export interface User {
email: string;
password: string;
created_timestamp: string;
+ updated_timestamp: string;
}
export interface Ressource {
diff --git a/backend/utils/constants.ts b/backend/utils/constants.ts
index 9251150b..10a6aaba 100644
--- a/backend/utils/constants.ts
+++ b/backend/utils/constants.ts
@@ -1,10 +1,16 @@
import type { CookieOptions } from 'express';
-const COOKIE_CONFIG: CookieOptions = {
+/*const COOKIE_CONFIG: CookieOptions = {
httpOnly: true,
domain: process.env.FRONT_DOMAIN,
secure: process.env.NODE_ENV == 'production' ? true : false,
sameSite: 'lax',
+};*/
+const COOKIE_CONFIG: CookieOptions = {
+ httpOnly: true,
+ domain: process.env.NODE_ENV == 'production' ? process.env.FRONT_DOMAIN : undefined,
+ secure: process.env.NODE_ENV == 'production' ? true : false,
+ sameSite: 'lax',
};
const MIME_TYPES_IMAGE = {