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.

Improve data management, permission system

Smaug6739dbc5a9ace181
diff --git a/backend/controllers/nodes.controller.go b/backend/controllers/nodes.controller.go
index aeb2232c..b827b746 100644
--- a/backend/controllers/nodes.controller.go
+++ b/backend/controllers/nodes.controller.go
@@ -56,7 +56,7 @@ func (ctr *Controller) GetPublicNode(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) GetSharedNodes(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
+ id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
if err != nil {
return http.StatusUnauthorized, err
}
@@ -76,7 +76,7 @@ func (ctr *Controller) GetSharedNodes(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) GetNodes(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
+ id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
if err != nil {
return http.StatusUnauthorized, err
}
@@ -105,7 +105,7 @@ func (ctr *Controller) GetNode(c *gin.Context) (int, any) {
if err != nil {
return http.StatusInternalServerError, err
}
- err, _ = utils.RessourceAccess(c, node, ctr.app.Services.Permissions, 1)
+ _, err = utils.NodePermission(c, node, ctr.app.Services.Permissions, utils.READ)
if err != nil {
return http.StatusUnauthorized, err
}
@@ -176,7 +176,7 @@ func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {
if err != nil {
return http.StatusInternalServerError, err
}
- err, userIdContext := utils.RessourceAccess(c, db_node, ctr.app.Services.Permissions, 2)
+ connectedUserId, err := utils.NodePermission(c, db_node, ctr.app.Services.Permissions, utils.WRITE)
if err != nil {
return http.StatusUnauthorized, err
}
@@ -185,7 +185,7 @@ func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {
return http.StatusBadRequest, err
}
- if db_node.UserId != userIdContext {
+ if db_node.UserId != connectedUserId {
// If the user is not the owner of the node, they cannot change the owner or the parent
node.ParentId = db_node.ParentId
node.UserId = db_node.UserId
@@ -236,7 +236,7 @@ func (ctr *Controller) DeleteNode(c *gin.Context) (int, any) {
if err != nil {
return http.StatusInternalServerError, err
}
- err, _ = utils.RessourceAccess(c, db_node, ctr.app.Services.Permissions, 3)
+ _, err = utils.NodePermission(c, db_node, ctr.app.Services.Permissions, utils.ADMIN)
if err != nil {
return http.StatusUnauthorized, err
}
diff --git a/backend/router/routes/users.go b/backend/router/routes/users.go
index 9140778a..9d863395 100644
--- a/backend/router/routes/users.go
+++ b/backend/router/routes/users.go
@@ -14,9 +14,9 @@ func Users(app *app.App, router *gin.RouterGroup) {
usrCtrl := controllers.NewUserController(app)
usr.GET("", middlewares.Auth(), middlewares.Admin(), utils.WP(usrCtrl.GetUsers))
- usr.GET("/:id", middlewares.Auth(), utils.WP(usrCtrl.GetUserById))
+ usr.GET("/:userId", middlewares.Auth(), utils.WP(usrCtrl.GetUserById))
usr.POST("", utils.WP(usrCtrl.CreateUser))
- usr.PATCH("/:id", middlewares.Auth(), utils.WP(usrCtrl.UpdateUser))
- usr.PATCH("/:id/password", middlewares.Auth(), utils.WP(usrCtrl.UpdatePassword))
- usr.DELETE("/:id", middlewares.Auth(), utils.WP(usrCtrl.DeleteUser))
+ usr.PATCH("/:userId", middlewares.Auth(), utils.WP(usrCtrl.UpdateUser))
+ usr.PATCH("/:userId/password", middlewares.Auth(), utils.WP(usrCtrl.UpdatePassword))
+ usr.DELETE("/:userId", middlewares.Auth(), utils.WP(usrCtrl.DeleteUser))
}
diff --git a/backend/utils/permissions.go b/backend/utils/permissions.go
index 8d944ee7..fbb460ea 100644
--- a/backend/utils/permissions.go
+++ b/backend/utils/permissions.go
@@ -18,6 +18,12 @@ const (
MODERATOR = 1 << 3
)
+const (
+ READ = 1
+ WRITE = 2
+ ADMIN = 3
+)
+
// CheckPermission checks if the user has the required permission.
func CheckPermission(userRole, requiredRole int) bool {
return userRole&requiredRole == requiredRole
@@ -61,62 +67,63 @@ func GetUserIdCtx(ctx *gin.Context) (types.Snowflake, error) {
return types.Snowflake(id), nil
}
-func SelfOrPermission(ctx *gin.Context, allowed int, key ...string) (types.Snowflake, error) {
+func SelfOrPermission(ctx *gin.Context, allowed int) (types.Snowflake, error) {
// Check if the c.Param("id") is "@me" or c.Param("id") is the same as the user ID in the context
// If not, check if the user has the required permission
// If one of the above is true, return the user ID from the context
// Otherwise, return an error
- search_key := "id"
- if len(key) > 0 {
- search_key = key[0]
- }
- id_param, err := GetIdParam(ctx, ctx.Param(search_key))
+
+ // --- 1. Get the target user ID
+ targetUserId, err := GetIdParam(ctx, ctx.Param("userId"))
if err != nil {
return 0, err
}
- userId, err := GetUserIdCtx(ctx)
+ // --- 2. Get the connected user ID
+ connectedUserId, err := GetUserIdCtx(ctx)
if err != nil {
return 0, err
}
- if id_param == userId {
- return id_param, nil
+ // --- 3. Check if the connected user is the target user => allow
+ if targetUserId == connectedUserId {
+ return targetUserId, nil
}
+ // --- 4. Check if the connected user is an app administrator => allow
role, exists := ctx.Get("user_role")
if !exists {
return 0, errors.New("user role not found in context")
}
- if id_param != userId && CheckPermission(role.(int), allowed) {
- return id_param, nil
+ if CheckPermission(role.(int), allowed) {
+ return targetUserId, nil
}
return 0, errors.New("unauthorized")
}
-func RessourceAccess(ctx *gin.Context, node *models.Node, permissionService services.PermissionService, permission int) (error, types.Snowflake) {
- // Check if the connected user has access to the resource (userId == targetId) or if the user has the required permission (app ADMINISTRATOR or node permission)
+func NodePermission(ctx *gin.Context, node *models.Node, permissionService services.PermissionService, permission int) (types.Snowflake, error) {
+ // Check if the connected user has access to the resource (connectedUserId == targetId) or if the user has the required permission (app ADMINISTRATOR or node permission)
// Check user is correctly authenticated
- userId, err := GetUserIdCtx(ctx)
+ connectedUserId, err := GetUserIdCtx(ctx)
if err != nil {
- return err, 0
+ return 0, err
}
// Case 1: User is the owner of the resource
- if userId == node.UserId {
- return nil, userId
+ if connectedUserId == node.UserId {
+ return connectedUserId, nil
}
// Case 2: User is an app administrator
role, exists := ctx.Get("user_role")
if !exists {
- return errors.New("user role not found in context"), userId
+ return connectedUserId, errors.New("user role not found in context")
}
if CheckPermission(role.(int), ADMINISTRATOR) {
- return nil, userId
+ return connectedUserId, nil
}
// Case 3: User has the required permission on the resource
- hasPermission := permissionService.HasPermission(userId, node.Id, permission)
+ hasPermission := permissionService.HasPermission(connectedUserId, node.Id, permission)
if hasPermission {
- return nil, userId
+ return connectedUserId, nil
}
- return errors.New("unauthorized"), userId
+ return 0, errors.New("unauthorized")
}
diff --git a/frontend/app/components/Sidebar/CollapseItem.vue b/frontend/app/components/Sidebar/CollapseItem.vue
index aadf7ba6..e4a7e616 100644
--- a/frontend/app/components/Sidebar/CollapseItem.vue
+++ b/frontend/app/components/Sidebar/CollapseItem.vue
@@ -16,7 +16,8 @@
<SidebarItem v-else-if="item.data.role !== -1 || item.show.value" :item="item" />
</template>
<script setup lang="ts">
-const props = defineProps<{ item: Item; root?: boolean }>();
+import type { DefaultItem } from './helpers';
+const props = defineProps<{ item: Item | DefaultItem; root?: boolean }>();
const toggleShow = () => {
setCollapseState(props.item.id, !props.item.show.value);
diff --git a/frontend/app/components/Sidebar/Sidebar.vue b/frontend/app/components/Sidebar/Sidebar.vue
index 7e5472d2..83e11c72 100644
--- a/frontend/app/components/Sidebar/Sidebar.vue
+++ b/frontend/app/components/Sidebar/Sidebar.vue
@@ -63,7 +63,7 @@ import { navigationItems } from './helpers';
import NewCategoryModal from '@/pages/dashboard/categories/_modals/CreateCategoryModal.vue';
import Dock from './Dock.vue';
-const { isOpened, hasSidebar } = useSidebar();
+const { isOpened, hasSidebar, filtered } = useSidebar();
const nodesStore = useNodesStore();
const preferences = usePreferences();
const userStore = useUserStore();
@@ -78,7 +78,7 @@ const filterItems = (items: Item[]): Item[] => {
return filterRecursive(items, filter);
};
-const tree = computed(() => filterItems(sidebarTree.filtered.value));
+const tree = computed(() => filterItems(filtered.value));
const handleClickOutside = (e: MouseEvent) => {
if (isOpened.value && e.target && !(e.target as Element).closest('.sidebar') && !(e.target as Element).closest('.open-sidebar')) isOpened.value = false;
diff --git a/frontend/app/components/Sidebar/SidebarItem.vue b/frontend/app/components/Sidebar/SidebarItem.vue
index 49f06275..597585e6 100644
--- a/frontend/app/components/Sidebar/SidebarItem.vue
+++ b/frontend/app/components/Sidebar/SidebarItem.vue
@@ -25,10 +25,11 @@
</template>
<script setup lang="ts">
-import { navigationItems } from './helpers';
+import type { Node } from '~/stores';
+import { navigationItems, type DefaultItem } from './helpers';
const nodesStore = useNodesStore();
const { isOpened } = useSidebar();
-const props = defineProps<{ item: Item }>();
+const props = defineProps<{ item: Item | DefaultItem }>();
const customClass = computed(() => {
if ('color' in props.item.data && props.item.data.color != null && props.item.data.color != -1)
return `item-icon ${getAppColor(props.item.data.color as number)}`;
@@ -73,12 +74,13 @@ const drop = async (event: DragEvent) => {
if (draggedItem.role === -1) return; // Prevent dropping nav items
if (props.item.data.role === 4) return; // Prevent dropping on ressource items
if (draggedItem.id === props.item.id) return; // Prevent dropping on itself
+ if (draggedItem.role <= 2 && props.item.data.role > 2) return; // Prevent dropping categories / workspaces on ressources / documents
// Move item to root
if (props.item.data.role === -1) {
- return nodesStore.update({ ...draggedItem, parent_id: workspaceId.value });
+ return nodesStore.update({ ...(draggedItem as Node), parent_id: workspaceId.value });
}
- nodesStore.update({ ...draggedItem, parent_id: props.item.id });
+ nodesStore.update({ ...(draggedItem as Node), parent_id: props.item.id });
};
</script>
diff --git a/frontend/app/components/Sidebar/helpers.ts b/frontend/app/components/Sidebar/helpers.ts
index cc58e0f1..f0d2d165 100644
--- a/frontend/app/components/Sidebar/helpers.ts
+++ b/frontend/app/components/Sidebar/helpers.ts
@@ -1,21 +1,13 @@
import type { Node } from '~/stores';
-export interface DefaultItem {
- id: string;
- type: 'navigation';
- role: -1; // 0: Navigation item
- label: string;
- icon?: string;
- route: string;
- childrens: DefaultItem[];
-}
+export type DefaultItem = Item<Omit<Node, 'user_id' | 'data' | 'show' | 'shared' | 'created_timestamp' | 'updated_timestamp'>>;
export interface Workspace {
text: string;
value?: string;
meta?: Partial<Node>;
}
const sidebarItemsPrefs = usePreferences().get('sidebarItems');
-export const navigationItems: Item<DefaultItem>[] = [
+export const navigationItems: DefaultItem[] = [
{
id: 'home',
parent_id: '',
@@ -24,12 +16,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'dashboard',
data: {
id: 'home',
- type: 'navigation',
role: -1,
- label: 'Home',
+ name: 'Home',
icon: 'dashboard',
- route: '/dashboard/home',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.home!),
},
@@ -41,12 +30,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'categories',
data: {
id: 'manage-categories',
- type: 'navigation',
role: -1,
- label: 'Manage categories',
+ name: 'Manage categories',
icon: 'categories',
- route: '/dashboard/categories',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.manageCategories!),
},
@@ -58,12 +44,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'cdn',
data: {
id: 'cdn',
- type: 'navigation',
role: -1,
- label: 'CDN',
+ name: 'CDN',
icon: 'cdn',
- route: '/dashboard/cdn',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.cdn!),
},
@@ -75,12 +58,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'user_settings',
data: {
id: 'settings',
- type: 'navigation',
role: -1,
- label: 'Settings',
+ name: 'Settings',
icon: 'user_settings',
- route: '/dashboard/settings',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.settings!),
},
@@ -92,12 +72,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'files',
data: {
id: 'documents',
- type: 'navigation',
role: -1,
- label: 'Documents',
+ name: 'Documents',
icon: 'files',
- route: '/dashboard/docs',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.documents!),
},
@@ -109,12 +86,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'import',
data: {
id: 'import',
- type: 'navigation',
role: -1,
- label: 'Import',
+ name: 'Import',
icon: 'import',
- route: '/dashboard/import',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.importation!),
},
@@ -126,12 +100,9 @@ export const navigationItems: Item<DefaultItem>[] = [
icon: 'add_file',
data: {
id: 'new-page',
- type: 'navigation',
role: -1,
- label: 'New Page',
+ name: 'New Page',
icon: 'add_file',
- route: '/dashboard/docs/new',
- childrens: [],
},
show: computed(() => sidebarItemsPrefs.value.newPage!),
},
diff --git a/frontend/app/composables/Sidebar.ts b/frontend/app/composables/Sidebar.ts
index b90778f4..05996e3d 100644
--- a/frontend/app/composables/Sidebar.ts
+++ b/frontend/app/composables/Sidebar.ts
@@ -4,10 +4,19 @@ const paneWidth = ref(isMobile() ? 350 : 390); // initial width of pane 1
const isResizing = ref(false);
const workspaceId = ref<string | undefined>(undefined);
const active_id = ref<string | null>(null);
-export function useSidebar() {
- const toggleSidebar = () => (isOpened.value = !isOpened.value);
+const toggleSidebar = () => (isOpened.value = !isOpened.value);
+
+const filtered = computed(() => {
+ const found = tree.value.find(i => i.id === workspaceId.value);
+ if (found) return found.childrens || [];
+ if (workspaceId.value === 'shared') return tree.value.filter(i => i.data && i.data.shared);
+ return tree.value;
+});
+
+export function useSidebar() {
return {
+ filtered,
toggleSidebar,
isOpened,
hasSidebar,
diff --git a/frontend/app/composables/TreeStructure.ts b/frontend/app/composables/TreeStructure.ts
index 7e895b70..9a4f830b 100644
--- a/frontend/app/composables/TreeStructure.ts
+++ b/frontend/app/composables/TreeStructure.ts
@@ -1,5 +1,4 @@
import type { Node } from '~/stores';
-import type { DefaultItem } from '../components/Sidebar/helpers';
export interface ANode {
id: string | number;
@@ -8,7 +7,7 @@ export interface ANode {
childrens?: ANode[];
}
-export interface Item<T = Node | DefaultItem> extends ANode {
+export interface Item<T = Node> extends ANode {
id: string;
route: string;
data: T;
diff --git a/frontend/app/composables/useSidebarTree.ts b/frontend/app/composables/useNodesTree.ts
similarity index 88%
rename from frontend/app/composables/useSidebarTree.ts
rename to frontend/app/composables/useNodesTree.ts
index ebaaa8cb..2adb5fcc 100644
--- a/frontend/app/composables/useSidebarTree.ts
+++ b/frontend/app/composables/useNodesTree.ts
@@ -1,12 +1,10 @@
// useSidebarTree.ts
-import type { DefaultItem } from '~/components/Sidebar/helpers';
import type { Node } from '~/stores';
const preferencesStore = usePreferences();
-const { workspaceId } = useSidebar();
let nodes: ComputedRef<Item<Node>[]> | Ref<Item<Node>[]> = ref([]);
-const allItems = computed(() => nodes.value.filter(n => n.data.role !== 1));
+const allItems = computed(() => nodes.value);
const structure = computed(() => new TreeStructure(allItems.value));
const resolveIcon = (item: Node) => {
@@ -39,19 +37,13 @@ const tree = computed(() => {
for (const item of tree) {
if ((item.data as Node).shared) {
- item.parent_id = 'shared';
+ item.parent_id = undefined;
item.icon = 'users';
}
}
return tree;
});
-const filtered = computed(() =>
- tree.value.filter(item => {
- if (workspaceId.value) return (item as Item<Node>).parent_id === workspaceId.value;
- return true;
- }),
-);
const collapseAll = () => {
allItems.value.forEach(item => {
if (item.show.value) item.show.value = false;
@@ -91,7 +83,7 @@ function useSidebarTree() {
}
const groupedByWorkspace = () => {
- const workspaces: Item<Node | DefaultItem>[] = [
+ const workspaces: Item<Node>[] = [
...nodesStore.getAll
.filter(c => c.role === 1)
.map(c => ({
@@ -139,8 +131,7 @@ function useSidebarTree() {
groupedByWorkspace,
getCategoryFromNode,
tree,
- filtered,
};
}
-export { useSidebarTree, tree, filtered };
+export { useSidebarTree, tree };
diff --git a/frontend/app/pages/dashboard/categories/[id]/edit.vue b/frontend/app/pages/dashboard/categories/[id]/edit.vue
index 7d4dfab4..22c0636d 100644
--- a/frontend/app/pages/dashboard/categories/[id]/edit.vue
+++ b/frontend/app/pages/dashboard/categories/[id]/edit.vue
@@ -49,7 +49,7 @@ import DeleteModal from '../_modals/DeleteCategoryModal.vue';
const nodesStore = useNodesStore();
const route = useRoute();
const category = computed(() => nodesStore.getById(route.params.id as string));
-const categoriesItem = computed(() => new TreeStructure(useSidebarTree().nodes.value).generateTree().filter(i => i.data.role == 1));
+const categoriesItem = computed(() => new TreeStructure(useSidebarTree().nodes.value.filter(i => i.data.role <= 2)).generateTree());
definePageMeta({ breadcrumb: 'Edit' });
diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.ts
index 226ca824..e1dee13a 100644
--- a/frontend/app/stores/db_strustures.d.ts
+++ b/frontend/app/stores/db_strustures.d.ts
@@ -5,7 +5,7 @@ export interface DB_Node {
name: string;
description?: string;
tags?: string;
- role: 1 | 2 | 3 | 4; // 1: Workspace; 2: Category; 3: Document; 4: Ressource
+ role: -1 | 1 | 2 | 3 | 4; // 1: Workspace; 2: Category; 3: Document; 4: Ressource
color?: number; // -1: Default; 0: None; 1-7: App colors
icon?: string;
thumbnail?: string;