Skip to content

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

New CDN, fixes, using ressources store

Smaug6739fa4c3737643c
diff --git a/backend/controllers/auth.controller.ts b/backend/controllers/auth.controller.ts
index 2de1663c..e1312738 100644
--- a/backend/controllers/auth.controller.ts
+++ b/backend/controllers/auth.controller.ts
@@ -37,7 +37,9 @@ export default class Authentification extends BaseController<UsersManager, User>
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);
- res.status(200).json(this.utils.success({ auth: true }));
+ 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) {
diff --git a/backend/controllers/cdn.controller.ts b/backend/controllers/cdn.controller.ts
index 5df474e9..2cec331f 100644
--- a/backend/controllers/cdn.controller.ts
+++ b/backend/controllers/cdn.controller.ts
@@ -23,8 +23,9 @@ export default class RessourcesController extends BaseController<RessourcesManag
}
async get(req: Request, res: Response) {
- this.manager
- .getRessources(req.params.user_id as string)
+ if (!req.user_id) return res.status(401).json(this.utils.error('Unauthorized'));
+ return this.manager
+ .getRessources(req.user_id)
.then((result: Ressource[]) => res.status(200).json(this.utils.success(result)))
.catch(e => res.status(500).json(this.utils.error(e)));
}
diff --git a/backend/routes/v1/cdn.ts b/backend/routes/v1/cdn.ts
index 5783b10b..acf6b70b 100644
--- a/backend/routes/v1/cdn.ts
+++ b/backend/routes/v1/cdn.ts
@@ -13,7 +13,7 @@ export default (client: App): Iroute => {
route: 'ressources',
version: 1,
router() {
- CDNRouter.get('/:user_id', auth, (req: Request, res: Response) => controller.get(req, res));
+ CDNRouter.get('/', auth, (req: Request, res: Response) => controller.get(req, res));
CDNRouter.post('/', auth, multerCdn, (req: Request, res: Response) => controller.add(req, res), multerErrors);
return CDNRouter;
},
diff --git a/frontend/components/DataTable.vue b/frontend/components/DataTable.vue
index afa9b0f2..66023cb5 100644
--- a/frontend/components/DataTable.vue
+++ b/frontend/components/DataTable.vue
@@ -37,14 +37,12 @@
paginator.totalItems.value }} entries</p>
<div class="pagination">
<button type="button" @click="paginator.previous()" :disabled="!paginator.hasPrevious()">&lt;</button>
- <button v-if="shouldShowPage(1)" @click="paginator.setPage(1)"
- :class="{ active: paginator.currentPage.value === 1 }">1</button>
+ <button @click="paginator.setPage(1)" :class="{ active: paginator.currentPage.value === 1 }">1</button>
<span v-if="shouldShowEllipsisBefore" class="ellipsis">...</span>
<button v-for="page in visiblePages" :key="page" @click="paginator.setPage(page)"
:class="{ active: paginator.currentPage.value === page }">{{ page }}</button>
<span v-if="shouldShowEllipsisAfter" class="ellipsis">...</span>
- <button v-if="shouldShowPage(paginator.totalPages.value)"
- @click="paginator.setPage(paginator.totalPages.value)"
+ <button v-if="paginator.totalPages.value > 1" @click="paginator.setPage(paginator.totalPages.value)"
:class="{ active: paginator.currentPage.value === paginator.totalPages.value }">{{
paginator.totalPages.value }}</button>
<button type="button" @click="paginator.next()" :disabled="!paginator.hasNext()">&gt;</button>
@@ -83,8 +81,6 @@ const visiblePages = computed(() => {
return pages;
});
-const shouldShowPage = (page: number) => page === 1 || page === paginator.totalPages.value;
-
const shouldShowEllipsisAfter = computed(() => {
const lastVisiblePage = visiblePages.value[visiblePages.value.length - 1];
return lastVisiblePage !== undefined && lastVisiblePage < paginator.totalPages.value - 1;
@@ -140,15 +136,15 @@ td {
th {
color: var(--font-color-dark);
- border-top: 1px solid var(--border-color);
}
td {
color: var(--font-color-light);
-}
-tr {
- border-bottom: 1px solid var(--border-color);
+ &:has(.footer) {
+ border-bottom-left-radius: 15px;
+ border-bottom-right-radius: 15px;
+ }
}
button {
@@ -189,6 +185,7 @@ button {
display: flex;
width: 100%;
justify-content: space-between;
+
}
select {
diff --git a/frontend/components/sidebar/SidebarItem.vue b/frontend/components/sidebar/SidebarItem.vue
index f50db2a1..8ad516ee 100644
--- a/frontend/components/sidebar/SidebarItem.vue
+++ b/frontend/components/sidebar/SidebarItem.vue
@@ -123,7 +123,7 @@ const drop = async (event: DragEvent) => {
&:deep(svg) {
fill: var(--blue);
width: 20px;
- max-height: 25px;
+ max-height: 22px;
margin-right: 5px;
path {
diff --git a/frontend/components/table-of-content/TableOfContents.vue b/frontend/components/table-of-content/TableOfContents.vue
index b680c522..f8b3e515 100644
--- a/frontend/components/table-of-content/TableOfContents.vue
+++ b/frontend/components/table-of-content/TableOfContents.vue
@@ -1,7 +1,7 @@
<template>
<aside>
<ul ref="list" class="toc">
- <h4>Table des matières</h4>
+ <h4>Table of content</h4>
<NodeTree v-if="headers.length" v-for="header of headers_tree" :node="header" :key="header.link" />
<p v-else>Aucun élément à afficher</p>
</ul>
@@ -35,7 +35,7 @@ const getHTMLHeaders = (): HTMLElement[] => {
function getHeaders(headers: HTMLElement[]): GroupedHeaders[] {
const tree: GroupedHeaders[] = [];
for (const header of headers) {
- const level = parseInt(header.tagName[1]);
+ const level = parseInt(header.tagName[1] || '1');
const title = header.textContent?.replace(/#/g, '') || '';
const link = `#${header.id}`;
const node: GroupedHeaders = { title, link, level };
diff --git a/frontend/composables/utils.ts b/frontend/composables/utils.ts
index a0c2351d..841af0fa 100644
--- a/frontend/composables/utils.ts
+++ b/frontend/composables/utils.ts
@@ -8,7 +8,7 @@ export function useColorHash(str: string): string {
}
const index = Math.abs(hash % colors.length);
- return colors[index];
+ return colors[index] as string;
}
export interface APIResult<Data> {
@@ -25,22 +25,20 @@ export const isMobile = () => (import.meta.client ? window.innerWidth <= 768 : f
export const baseUrl = import.meta.env.VITE_BASE_API?.toString() || '';
import type { DB_Document, DB_Category, DB_Ressource } from '../store/db_strustures';
-export async function makeRequest(
- route: string,
- method: string,
- body: Object,
- retry = false,
-): Promise<APIResult<DB_Document | DB_Category | DB_Ressource | DB_Document[] | DB_Category[] | DB_Ressource[]>> {
+export async function makeRequest(route: string, method: string, body: Object, retry = false): Promise<APIResult<DB_Document | DB_Category | DB_Ressource | DB_Document[] | DB_Category[] | DB_Ressource[]>> {
+ console.log(`[API] Requesting ${method} ${route}`);
+ console.log(body);
+
const response = await fetch(`${baseUrl}/api/v1/${route}`, {
method: method,
- body: method === 'GET' || method === 'DELETE' ? null : JSON.stringify(body),
- headers: { 'Content-Type': 'application/json; charset=UTF-8' },
+ body: method === 'GET' || method === 'DELETE' ? null : body instanceof FormData ? body : JSON.stringify(body),
+ headers: body instanceof FormData ? {} : { 'Content-Type': 'application/json; charset=UTF-8' },
credentials: 'include',
});
if (response.status === 401 && !retry) {
console.log('\x1b[41m[AUTH]\x1b[0m Access token invalid. Getting new access token...');
- const login = await makeRequest(`auth/refreshToken/152981937240150016`, 'GET', {}, true);
+ const login = await makeRequest(`auth/refreshToken/152981937240150016`, 'GET', {}, true); // TODO: remove hardcoded user_id
if (login.status === 'success') {
console.log('\x1b[42m[AUTH]\x1b[0m New access token received.');
return await makeRequest(route, method, body, true);
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index 15da2bfe..e5d5be2f 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -1,8 +1,10 @@
export default defineNuxtConfig({
devtools: { enabled: true },
+
future: {
compatibilityVersion: 4,
},
+
vite: {
css: {
preprocessorOptions: {
@@ -52,4 +54,6 @@ export default defineNuxtConfig({
],
},
},
-});
+
+ compatibilityDate: '2024-07-19',
+});
\ No newline at end of file
diff --git a/frontend/pages/dashboard/cdn.vue b/frontend/pages/dashboard/cdn.vue
index 89e583ef..6e08105e 100644
--- a/frontend/pages/dashboard/cdn.vue
+++ b/frontend/pages/dashboard/cdn.vue
@@ -1,6 +1,6 @@
<template>
<div class="cdn-component">
- <h2>Uploader un fichier sur le CDN</h2>
+ <h2>CDN: File manager</h2>
<div class="dropzone" :class="{ 'drag-over': isDragOver }" @dragover.prevent @drop.prevent="handleFileDrop"
@dragenter.prevent="dragEnter" @dragleave.prevent="dragLeave">
<input type="file" ref="fileInput" @change="handleFileSelect" />
@@ -9,27 +9,17 @@
<div class="file-size">{{ readableFileSize(selectedFile.size) }}</div>
</div>
<div v-else>
- Glissez et déposez un fichier ici ou <span class="clickable" @click="triggerFileSelect">cliquez pour
- sélectionner</span>.
+ Drop file here or <span class="clickable" @click="triggerFileSelect">click to select from computed</span>.
</div>
</div>
- <button @click="submitFile" :disabled="!selectedFile">Uploader sur le serveur</button>
+ <button @click="submitFile" :disabled="!selectedFile">Upload on server</button>
<div v-if="isLoading" class="loading-spinner"></div>
<div v-if="fileLink" class="link-section">
<input type="text" v-model="fileLink" readonly />
<button @click="copyLink">Copy link</button>
</div>
- <h2>Ressources existantes</h2>
<div v-if="ressources.length" class="ressources-list">
- <div v-for="ressource in ressources" :key="ressource.id" class="ressource-item">
- <div class="ressource-info">
- <span class="ressource-name">{{ ressource.filename }}</span>
- <span class="ressource-size">{{ readableFileSize(ressource.file_size) }}</span>
- <span class="ressource-type">{{ ressource.file_type }}</span>
- <span class="ressource-date">{{ formatDate(ressource.created_timestamp) }}</span>
- </div>
- <a :href="`/static${ressource.transformed_path || ressource.original_path}`" target="_blank">View</a>
- </div>
+ <DataTable :headers="headers" :rows="rows" />
</div>
<div v-else>
No ressource found.
@@ -37,11 +27,11 @@
</div>
</template>
<script setup lang="ts">
-import { useNotifications, useRessourcesStore } from '~/store';
+import { useNotifications, useRessourcesStore, type DB_Ressource } from '~/store';
const ressourcesStore = useRessourcesStore();
await ressourcesStore.fetch();
-const selectedFile: Ref<File | null> = ref(null);
+const selectedFile: Ref<File | null | undefined> = ref(null);
const isDragOver = ref(false);
const fileLink = ref('');
const fileInput: Ref<HTMLInputElement | null> = ref(null);
@@ -68,18 +58,12 @@ const submitFile = async () => {
const body = new FormData();
body.append("file", selectedFile.value);
- clearForm();
-
- const response = await fetch(`${import.meta.env.VITE_BASE_API}/api/v1/ressources`, {
- method: "POST",
- credentials: "include",
- body: body,
- });
-
- const result = await response.json();
- isLoading.value = false;
- if (result.status === "success") fileLink.value = `${import.meta.env.VITE_BASE_API}/static${result.result.transformed_path || result.result.original_path}`;
- else useNotifications().add({ type: "error", title: "Error", message: result.message, timeout: 5000 })
+ selectedFile.value = null; // Reset selected file
+
+ await ressourcesStore.post(body)
+ .then((r) => fileLink.value = `${import.meta.env.VITE_BASE_API}/static${(r as DB_Ressource).transformed_path || (r as DB_Ressource).original_path}`)
+ .catch((e) => useNotifications().add({ type: "error", title: "Error", message: e, timeout: 5000 }))
+ .finally(() => isLoading.value = false);
}
const readableFileSize = (size: number): string => {
@@ -87,12 +71,24 @@ const readableFileSize = (size: number): string => {
return `${(size / Math.pow(1024, i)).toFixed(2)} ${["B", "kB", "MB", "GB", "TB"][i]}`
}
-const formatDate = (timestamp: string): string => {
- const date = new Date(parseInt(timestamp));
- return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
-}
+const headers = [
+ { label: 'Name', key: 'name' },
+ { label: 'Size', key: 'size' },
+ { label: 'Type', key: 'type' },
+ { label: 'Date', key: 'date' },
+ { label: 'Action', key: 'action' },
+];
+const color = (type: string) => type.includes('image') ? 'green' : type.includes('video') ? 'blue' : type.includes('pdf') ? 'yellow' : 'red';
+const rows: any = computed(() => ressources.map((res) => {
+ return {
+ name: { content: res.filename },
+ size: { content: readableFileSize(res.file_size) },
+ type: { content: `<span class="tag ${color(res.file_type)}">${res.file_type}</span>`, type: 'html' },
+ date: { content: new Date(res.created_timestamp).toLocaleDateString() },
+ action: { content: `<a href="${import.meta.env.VITE_BASE_API}/static${res.transformed_path || res.original_path}" target="_blank">View</a>`, type: 'html' },
+ };
+}));
-const clearForm = () => selectedFile.value = null;
</script>
<style scoped lang="scss">
@@ -101,7 +97,7 @@ const clearForm = () => selectedFile.value = null;
flex-direction: column;
align-items: center;
gap: 1.5rem;
- padding: 2rem;
+ padding: 3rem;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
diff --git a/frontend/store/ressources.store.ts b/frontend/store/ressources.store.ts
index 4e3208e6..0414ceca 100644
--- a/frontend/store/ressources.store.ts
+++ b/frontend/store/ressources.store.ts
@@ -2,13 +2,14 @@ import { defineStore } from 'pinia';
import type { DB_Ressource } from './db_strustures';
export const useRessourcesStore = defineStore('ressources', {
state: () => ({
- ressources: [] as DB_Ressource[],
+ ressources: ref<DB_Ressource[]>([]),
}),
getters: {
getAll: state => state.ressources,
},
actions: {
fetch: async function () {
+ if (this.ressources.length > 0) return this.ressources;
return new Promise(async (resolve, reject) => {
const request = await makeRequest(`ressources`, 'GET', {});
if (request.status == 'success') {
@@ -17,11 +18,13 @@ export const useRessourcesStore = defineStore('ressources', {
} else reject(request.message);
});
},
- post(ressource: DB_Ressource) {
+ post(ressource: FormData): Promise<DB_Ressource | string> {
return new Promise(async (resolve, reject) => {
const request = await makeRequest(`ressources`, 'POST', ressource);
- if (request.status == 'success') resolve(this.ressources.push(request.result as DB_Ressource));
- else reject(request.message);
+ if (request.status == 'success') {
+ this.ressources.push(request.result as DB_Ressource);
+ resolve(request.result as DB_Ressource);
+ } else reject(request.message);
});
},
delete(id: string) {
diff --git a/frontend/styles/_variables.scss b/frontend/styles/_variables.scss
index a4ebf834..87ba5013 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%);
-
@import "./font.scss";
$external-font: 'Poppins', sans-serif;
diff --git a/frontend/styles/theme.scss b/frontend/styles/theme.scss
index 5cf97355..deb155b9 100644
--- a/frontend/styles/theme.scss
+++ b/frontend/styles/theme.scss
@@ -27,7 +27,6 @@ button {
border: none;
border-radius: 6px;
color: var(--font-color);
- font-size: 15px;
cursor: pointer;
transition: transform $transition-duration;
width: fit-content;
@@ -121,7 +120,6 @@ textarea {
border: 1px solid var(--border-color);
color: var(--font-color);
border-radius: 6px;
- font-size: 15px;
transition: border-color $transition-duration, box-shadow $transition-duration;
&:focus {
@@ -142,7 +140,6 @@ mark {
}
option {
- font-size: 16px;
padding: 8px 12px;
&:hover {
@@ -176,7 +173,7 @@ table {
}
tbody tr {
- border-bottom: 1px solid var(--border-color);
+ border-top: 1px solid var(--border-color);
}
tbody tr:nth-of-type(even) {
@@ -191,7 +188,6 @@ table {
textarea {
font-family: $monospace-font;
- font-size: 16px;
resize: none;
}