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.

Permission system (functional !) :tada:

Smaug6739c76c6a658f75
diff --git a/backend/controllers/permissions.controller.go b/backend/controllers/permissions.controller.go
new file mode 100644
index 00000000..1018abdd
--- /dev/null
+++ b/backend/controllers/permissions.controller.go
@@ -0,0 +1,160 @@
+package controllers
+
+import (
+ "alexandrie/app"
+ "alexandrie/models"
+ "alexandrie/utils"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+)
+
+type PermissionsController interface {
+ GetNodePermissions(c *gin.Context) (int, any)
+ CreatePermission(c *gin.Context) (int, any)
+ UpdatePermission(c *gin.Context) (int, any)
+ DeletePermission(c *gin.Context) (int, any)
+}
+
+func NewPermissionsController(app *app.App) PermissionsController {
+ return &Controller{
+ app: app,
+ }
+}
+
+// Get node permissions by id
+// @Summary Get all node permissions by id
+// @Method GET
+// @Router /permissions/{nodeId} [get]
+// @Security Authenfification: Auth
+// @Param nodeId path string true "Node ID"
+// @Success 200 {object} Success([]models.Permission)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) GetNodePermissions(c *gin.Context) (int, any) {
+ nodeId, err := utils.GetIdParam(c, c.Param("nodeId"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ node, err := ctr.app.Services.Nodes.GetNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ _, err = utils.NodePermission(c, node, ctr.app.Services.Permissions, utils.OWNER)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ perms, err := ctr.app.Services.Permissions.GetNodePermission(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, perms
+}
+
+// Create permission
+// @Summary Create permission
+// @Method POST
+// @Router /permissions [post]
+// @Security Authenfification: Auth
+// @Body permission body models.Permission true "Permission"
+// @Success 200 {object} Success(models.Permission)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) CreatePermission(c *gin.Context) (int, any) {
+ perm := &models.Permission{}
+ if err := c.ShouldBindJSON(perm); err != nil {
+ return http.StatusBadRequest, err
+ }
+ node, err := ctr.app.Services.Nodes.GetNode(perm.NodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ _, err = utils.NodePermission(c, node, ctr.app.Services.Permissions, utils.OWNER)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ perm = &models.Permission{
+ Id: ctr.app.Snowflake.Generate(),
+ NodeId: perm.NodeId,
+ UserId: perm.UserId,
+ Permission: perm.Permission,
+ CreatedTimestamp: time.Now().UnixMilli(),
+ }
+ err = ctr.app.Services.Permissions.CreatePermission(perm)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, perm
+}
+
+// Update permission
+// @Summary Update permission
+// @Method PUT
+// @Router /permissions/{id} [put]
+// @Security Authenfification: Auth
+// @Param id path string true "Permissions ID"
+// @Body node body models.Permissions true "Permissions"
+// @Success 200 {object} Success(models.Permissions)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) UpdatePermission(c *gin.Context) (int, any) {
+ permId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ perm, err := ctr.app.Services.Permissions.GetPermission(permId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ node, err := ctr.app.Services.Nodes.GetNode(perm.NodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ _, err = utils.NodePermission(c, node, ctr.app.Services.Permissions, utils.OWNER)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ requestChange := &models.Permission{}
+ if err := c.ShouldBindJSON(requestChange); err != nil {
+ return http.StatusBadRequest, err
+ }
+ err = ctr.app.Services.Permissions.UpdatePermission(permId, requestChange.Permission)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return 0, nil
+}
+
+// Delete permission
+// @Summary Delete permission
+// @Method DELETE
+// @Router /permissions/{id} [delete]
+// @Security Authenfification: Auth
+// @Param id path string true "Permissions ID"
+// @Success 200 {object} Success(string)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) DeletePermission(c *gin.Context) (int, any) {
+ permId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ perm, err := ctr.app.Services.Permissions.GetPermission(permId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ node, err := ctr.app.Services.Nodes.GetNode(perm.NodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ _, err = utils.NodePermission(c, node, ctr.app.Services.Permissions, utils.OWNER)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ err = ctr.app.Services.Permissions.DeletePermission(permId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, "Permission deleted"
+}
diff --git a/backend/models/permission.model.go b/backend/models/permission.model.go
new file mode 100644
index 00000000..fdd7e382
--- /dev/null
+++ b/backend/models/permission.model.go
@@ -0,0 +1,11 @@
+package models
+
+import "alexandrie/types"
+
+type Permission struct {
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ NodeId types.Snowflake `json:"node_id" form:"node_id"`
+ UserId types.Snowflake `json:"user_id" form:"user_id"`
+ Permission int `json:"permission" form:"permission"`
+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
+}
diff --git a/backend/router/router.go b/backend/router/router.go
index 0495dc5b..b3aa4e47 100644
--- a/backend/router/router.go
+++ b/backend/router/router.go
@@ -39,5 +39,6 @@ func InitRouter(app *app.App) *gin.Engine {
routes.Auth(app, mainGroup)
routes.Uploads(app, mainGroup)
routes.Nodes(app, mainGroup)
+ routes.Permissions(app, mainGroup)
return router
}
diff --git a/backend/router/routes/permissions.go b/backend/router/routes/permissions.go
new file mode 100644
index 00000000..64a8edb4
--- /dev/null
+++ b/backend/router/routes/permissions.go
@@ -0,0 +1,20 @@
+package routes
+
+import (
+ "alexandrie/app"
+ "alexandrie/controllers"
+ "alexandrie/middlewares"
+ "alexandrie/utils"
+
+ "github.com/gin-gonic/gin"
+)
+
+func Permissions(app *app.App, router *gin.RouterGroup) {
+ usr := router.Group("/permissions")
+ permissionsCtrl := controllers.NewPermissionsController(app)
+
+ usr.GET("/:nodeId", middlewares.Auth(), utils.WP(permissionsCtrl.GetNodePermissions))
+ usr.POST("", middlewares.Auth(), utils.WP(permissionsCtrl.CreatePermission))
+ usr.PATCH("/:id", middlewares.Auth(), utils.WP(permissionsCtrl.UpdatePermission))
+ usr.DELETE("/:id", middlewares.Auth(), utils.WP(permissionsCtrl.DeletePermission))
+}
diff --git a/backend/services/permissions.service.go b/backend/services/permissions.service.go
index 12403319..fbebd964 100644
--- a/backend/services/permissions.service.go
+++ b/backend/services/permissions.service.go
@@ -1,20 +1,57 @@
package services
import (
+ "alexandrie/models"
"alexandrie/types"
"database/sql"
)
type PermissionService interface {
+ GetNodePermission(nodeId types.Snowflake) ([]*models.Permission, error)
+ GetPermission(id types.Snowflake) (*models.Permission, error)
HasPermission(userId, nodeId types.Snowflake, required int) bool
- //GrantPermission(userId, nodeId types.Snowflake, permission int) error
- //RevokePermission(userId, nodeId types.Snowflake) error
+ CreatePermission(permission *models.Permission) error
+ UpdatePermission(id types.Snowflake, permission int) error
+ DeletePermission(id types.Snowflake) error
}
func NewPermissionService(db *sql.DB) PermissionService {
return &Service{db: db}
}
+func (s *Service) GetPermission(id types.Snowflake) (*models.Permission, error) {
+ var p models.Permission
+ err := s.db.QueryRow(`SELECT id, node_id, user_id, permission, created_timestamp FROM permissions WHERE id = ?`, id).Scan(
+ &p.Id, &p.NodeId, &p.UserId, &p.Permission, &p.CreatedTimestamp,
+ )
+ if err != nil {
+ return nil, err
+ }
+ return &p, nil
+}
+
+func (s *Service) GetNodePermission(nodeId types.Snowflake) ([]*models.Permission, error) {
+ rows, err := s.db.Query(`
+ SELECT id, node_id, user_id, permission, created_timestamp
+ FROM permissions
+ WHERE node_id = ?
+ `, nodeId)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var permissions []*models.Permission
+ for rows.Next() {
+ var p models.Permission
+ if err := rows.Scan(&p.Id, &p.NodeId, &p.UserId, &p.Permission, &p.CreatedTimestamp); err != nil {
+ return nil, err
+ }
+ permissions = append(permissions, &p)
+ }
+ return permissions, nil
+}
+
func (s *Service) HasPermission(userId, nodeId types.Snowflake, required int) bool {
var perm int
err := s.db.QueryRow(`
@@ -37,12 +74,12 @@ func (s *Service) HasPermission(userId, nodeId types.Snowflake, required int) bo
WHERE p.user_id = ?
`, nodeId, userId).Scan(&perm)
- // Cas 1 : permission explicite suffisante
+ // Case 1 : Explicit permission sufficient
if perm >= required {
return true
}
- // Cas 2 : pas assez de permissions → vérifier si propriétaire d’un ancêtre
+ // Case 2 : Not enough permissions → check if owner of an ancestor
var owns int
err = s.db.QueryRow(`
WITH RECURSIVE ancestors AS (
@@ -62,10 +99,26 @@ func (s *Service) HasPermission(userId, nodeId types.Snowflake, required int) bo
LIMIT 1
`, nodeId, userId).Scan(&owns)
if err == nil && owns == 1 {
- // propriétaire d’un ancêtre = permission max
+ // Owner of an ancestor = max permission
return required <= 3
}
- // sinon pas de permission
+ // Otherwise no permission
return false
}
+
+func (s *Service) CreatePermission(permission *models.Permission) error {
+ _, err := s.db.Exec(`INSERT INTO permissions (id, node_id, user_id, permission, created_timestamp) VALUES (?, ?, ?, ?, ?)`,
+ permission.Id, permission.NodeId, permission.UserId, permission.Permission, permission.CreatedTimestamp)
+ return err
+}
+
+func (s *Service) UpdatePermission(id types.Snowflake, permission int) error {
+ _, err := s.db.Exec(`UPDATE permissions SET permission = ? WHERE id = ?`, permission, id)
+ return err
+}
+
+func (s *Service) DeletePermission(id types.Snowflake) error {
+ _, err := s.db.Exec(`DELETE FROM permissions WHERE id = ?`, id)
+ return err
+}
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index 05a0b15f..92698f76 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -10,7 +10,7 @@ type UserService interface {
GetAllUsers() ([]*models.User, error)
GetUserById(id types.Snowflake) (*models.User, error)
GetUserByUsername(username string) (*models.User, error)
- GetPublicUser(usernameOrEmail string) (*models.User, error)
+ GetPublicUser(usernameOrEmailOrId string) (*models.User, error)
CheckUsernameExists(username string) bool
CreateUser(user *models.User) (*models.User, error)
UpdateUser(id types.Snowflake, user *models.User) (*models.User, error)
@@ -75,9 +75,9 @@ func (s *Service) GetUserByUsername(username string) (*models.User, error) {
return &user, nil
}
-func (s *Service) GetPublicUser(usernameOrEmail string) (*models.User, error) {
+func (s *Service) GetPublicUser(usernameOrEmailOrId string) (*models.User, error) {
var user models.User
- err := s.db.QueryRow("SELECT id, username, avatar, created_timestamp, updated_timestamp FROM users WHERE username = ? OR email = ?", usernameOrEmail, usernameOrEmail).Scan(
+ err := s.db.QueryRow("SELECT id, username, avatar, created_timestamp, updated_timestamp FROM users WHERE username = ? OR email = ? OR id = ?", usernameOrEmailOrId, usernameOrEmailOrId, usernameOrEmailOrId).Scan(
&user.Id, &user.Username, &user.Avatar, &user.CreatedTimestamp, &user.UpdatedTimestamp,
)
if err != nil {
diff --git a/backend/utils/permissions.go b/backend/utils/permissions.go
index fbb460ea..6c3d8b25 100644
--- a/backend/utils/permissions.go
+++ b/backend/utils/permissions.go
@@ -19,6 +19,7 @@ const (
)
const (
+ OWNER = 0
READ = 1
WRITE = 2
ADMIN = 3
@@ -99,7 +100,11 @@ func SelfOrPermission(ctx *gin.Context, allowed int) (types.Snowflake, error) {
}
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 if the connected user has access to the resource
+ // Case 1: User is the owner of the node (connectedUserId == targetId) => allow
+ // Case 2: The user is an app administrator => allow
+ // Case 3: The user has the required permission on the resource => allow
+ // Otherwise, return an error
// Check user is correctly authenticated
connectedUserId, err := GetUserIdCtx(ctx)
@@ -118,6 +123,11 @@ func NodePermission(ctx *gin.Context, node *models.Node, permissionService servi
if CheckPermission(role.(int), ADMINISTRATOR) {
return connectedUserId, nil
}
+
+ if permission == OWNER {
+ return 0, errors.New("unauthorized")
+ }
+
// Case 3: User has the required permission on the resource
hasPermission := permissionService.HasPermission(connectedUserId, node.Id, permission)
diff --git a/frontend/app/components/Sidebar/SidebarWorkspaces.vue b/frontend/app/components/Sidebar/SidebarWorkspaces.vue
index 4b39fbbc..7ece813f 100644
--- a/frontend/app/components/Sidebar/SidebarWorkspaces.vue
+++ b/frontend/app/components/Sidebar/SidebarWorkspaces.vue
@@ -1,7 +1,7 @@
<template>
<div class="dropdown-container" @click="toggleDropdown">
<div class="dropdown-selected" :class="{ open: isOpen }">
- <span v-if="selectedOption"><SidebarWorkspace :option="selectedOption" /></span>
+ <span v-if="selectedOption" style="flex: 1"><SidebarWorkspace :option="selectedOption" /></span>
<Icon name="expand" :small="true" fill="var(--font-color)" />
</div>
<ul v-show="isOpen" class="dropdown-options">
diff --git a/frontend/app/pages/dashboard/categories/[id]/index.vue b/frontend/app/pages/dashboard/categories/[id]/index.vue
index c7be8b20..ff8e8608 100644
--- a/frontend/app/pages/dashboard/categories/[id]/index.vue
+++ b/frontend/app/pages/dashboard/categories/[id]/index.vue
@@ -3,6 +3,7 @@
<header>
<h1 style="font-size: 20px">Documents of category <tag class="blue">New</tag></h1>
<div style="display: flex; align-items: center; gap: 8px">
+ <NuxtLink @click="openPermissionsModal"><Icon name="users" :big="true" fill="var(--font-color)" /></NuxtLink>
<NuxtLink :to="`/dashboard/categories/${categoryId}/edit`"><Icon name="settings" :big="true" fill="var(--font-color)" /></NuxtLink>
<ViewSelection v-model="view" />
</div>
@@ -22,6 +23,7 @@
</template>
<script setup lang="ts">
+import NodePermissions from '../../docs/_modals/NodePermissions.vue';
const route = useRoute();
const categoryId = route.params.id as string;
const nodesStore = useNodesStore();
@@ -33,6 +35,8 @@ const view: Ref<'table' | 'list'> = ref('list');
// return category?.name || '';
// },
// });
+const openPermissionsModal = () => useModal().add(new Modal(shallowRef(NodePermissions), { props: { nodeId: categoryId }, size: 'small' }));
+
const documents = computed(() => {
const documents = nodesStore.getByCategories(categoryId);
const childCategories = nodesStore.getChilds(categoryId);
diff --git a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
index f951a0d9..f8be919f 100644
--- a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
+++ b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
@@ -46,7 +46,7 @@ const props = defineProps<{ doc: Node }>();
const print = () => window.print();
const openDeleteModal = () => useModal().add(new Modal(shallowRef(DeleteDocumentModal), { props: { documentId: props.doc.id } }));
const openEditModal = () => useModal().add(new Modal(shallowRef(DocumentMeta), { props: { doc: props.doc }, size: 'small' }));
-const openPermissionsModal = () => useModal().add(new Modal(shallowRef(NodePermissions), { props: { doc: props.doc }, size: 'small' }));
+const openPermissionsModal = () => useModal().add(new Modal(shallowRef(NodePermissions), { props: { nodeId: props.doc.id }, size: 'small' }));
function exportMarkdown() {
const blob = new Blob([props.doc.content || ''], { type: 'text/markdown' });
diff --git a/frontend/app/pages/dashboard/docs/_modals/NodePermissions.vue b/frontend/app/pages/dashboard/docs/_modals/NodePermissions.vue
index 6d3b0157..3c95576f 100644
--- a/frontend/app/pages/dashboard/docs/_modals/NodePermissions.vue
+++ b/frontend/app/pages/dashboard/docs/_modals/NodePermissions.vue
@@ -1,29 +1,70 @@
-<!-- This components is a modal for advanced editing document metadata -->
<template>
<div class="modal-content">
- <h2>Manage permissions <tag yellow>Beta</tag></h2>
- <form @submit.prevent>
+ <h2 class="title">Manage permissions <tag yellow>Beta</tag></h2>
+
+ <!-- Search + add -->
+ <form @submit.prevent="addPermission">
<label for="user">Search user</label>
<input id="user" v-model="query" placeholder="Username or email" />
- <div v-if="user" style="background-color: var(--bg-ui); border-radius: 8px">
+
+ <div v-if="user" class="user-card">
<div class="user-info-row">
- <span style="display: flex; align-items: center; gap: 10px">
- <img v-if="user.avatar" :src="useAvatar(user)" alt="avatar" style="width: 30px; height: 30px; border-radius: 50%; margin: 0" />
+ <span class="user-meta">
+ <img :src="useAvatar(user)" alt="avatar" class="avatar" />
<span>{{ user.username }}</span>
</span>
- <span style="color: var(--font-color-light); font-size: 14px"> Joined on {{ new Date(user.created_timestamp).toLocaleDateString() }} </span>
+ <span class="joined"> Joined on {{ new Date(user.created_timestamp).toLocaleDateString() }} </span>
+ </div>
+
+ <div class="user-actions">
+ <select v-model="selectedPermission">
+ <option :value="1">Viewer</option>
+ <option :value="2">Editor</option>
+ <option :value="3">Admin</option>
+ </select>
+ <button type="submit">Add</button>
</div>
</div>
</form>
+
+ <!-- Current permissions -->
+ <h3>Current permissions</h3>
+ <ul class="permissions-list">
+ <li v-for="perm in permissions" :key="perm.id" class="permission-item">
+ <div class="user-info-row">
+ <span class="user-meta">
+ <img :src="useAvatar(perm.user)" alt="avatar" class="avatar" />
+ <span>{{ perm.user?.username }}</span>
+ </span>
+
+ <div class="user-actions">
+ <select v-model="perm.permission" @change="updatePermission(perm)">
+ <option :value="1">Viewer</option>
+ <option :value="2">Editor</option>
+ <option :value="3">Admin</option>
+ </select>
+ <button @click="removePermission(perm)">Remove</button>
+ </div>
+ </div>
+ </li>
+ </ul>
</div>
</template>
<script setup lang="ts">
-import type { PublicUser } from '~/stores';
+import type { Permission, PublicUser } from '~/stores';
+
+const props = defineProps<{
+ nodeId: string;
+}>();
const usersStore = useUserStore();
+const nodesStore = useNodesStore();
+
const query = ref('');
-const user = ref(null as null | PublicUser);
+const user = ref<PublicUser | null>(null);
+const selectedPermission = ref(1);
+const permissions = ref<Permission[]>([]);
watch(query, async newQuery => {
if (newQuery) {
@@ -32,44 +73,126 @@ watch(query, async newQuery => {
user.value = null;
}
});
+
+onMounted(async () => {
+ permissions.value = await nodesStore.fetchPermissions(props.nodeId);
+});
+
+const addPermission = async () => {
+ if (!user.value) return;
+ const perm = await nodesStore.addPermission({
+ node_id: props.nodeId,
+ user_id: user.value.id,
+ permission: selectedPermission.value,
+ });
+ if (perm) permissions.value.push(perm);
+ user.value = null;
+ query.value = '';
+ selectedPermission.value = 1;
+};
+
+const updatePermission = async (perm: Permission) => {
+ await nodesStore.updatePermission(perm);
+};
+
+const removePermission = async (perm: Permission) => {
+ await nodesStore.removePermission(props.nodeId, perm.user_id);
+ permissions.value = permissions.value.filter(p => p.id !== perm.id);
+};
</script>
<style scoped>
.modal-content {
display: flex;
flex-direction: column;
+ gap: 15px;
}
-form {
- padding: 0 5px 25px;
- flex: 1;
- overflow-y: auto;
+.title {
+ font-size: 20px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
}
-label {
+form {
+ padding-bottom: 15px;
display: flex;
- align-items: center;
+ flex-direction: column;
+ gap: 10px;
}
-textarea {
- height: 50px;
- min-height: 50px;
- max-height: 50px;
- font-size: 14px;
- resize: none;
+input {
+ padding: 6px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--border-color, #ccc);
+}
+
+.user-card {
+ background-color: var(--bg-ui);
+ border-radius: 8px;
+ padding: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
}
.user-info-row {
display: flex;
justify-content: space-between;
align-items: center;
+}
+
+.user-meta {
+ display: flex;
+ align-items: center;
gap: 10px;
- padding: 8px;
- transition: background-color 0.2s;
- border-radius: 8px;
}
-.user-info-row:hover {
- background-color: var(--bg-ui);
+.avatar {
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+}
+
+.joined {
+ color: var(--font-color-light);
+ font-size: 12px;
+}
+
+.user-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+select {
+ padding: 4px 8px;
+ border-radius: 6px;
+ border: 1px solid var(--border-color, #ccc);
+}
+
+button {
+ padding: 4px 8px;
+ border: none;
+ border-radius: 6px;
+ cursor: pointer;
+ background: var(--primary-color, #444);
+ color: white;
+}
+
+button:hover {
+ background: var(--primary-hover, #666);
+}
+
+.permissions-list {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+
+.permission-item {
+ padding: 8px;
+ border-bottom: 1px solid var(--border-color, #ddd);
}
</style>
diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.ts
index 26e01dde..33defedc 100644
--- a/frontend/app/stores/db_strustures.d.ts
+++ b/frontend/app/stores/db_strustures.d.ts
@@ -47,6 +47,15 @@ export interface DB_Node {
updated_timestamp: string;
}
+export interface Permission {
+ id: string;
+ user_id: string;
+ node_id: string;
+ permission: number; // 1: Read; 2: Write; 3: Admin;
+ created_timestamp: string;
+ user?: PublicUser;
+}
+
export interface Node extends DB_Node {
partial?: boolean;
shared: boolean;
diff --git a/frontend/app/stores/nodes.store.ts b/frontend/app/stores/nodes.store.ts
index 6000dee6..1c8912d2 100644
--- a/frontend/app/stores/nodes.store.ts
+++ b/frontend/app/stores/nodes.store.ts
@@ -1,5 +1,5 @@
import { makeRequest, type FetchOptions } from './_utils';
-import type { DB_Node, Node } from './db_strustures';
+import type { DB_Node, Node, Permission } from './db_strustures';
interface SearchOptions {
query?: string;
@@ -14,6 +14,7 @@ export const useNodesStore = defineStore('nodes', {
state: () => ({
nodes: [] as Array<Node | Node>,
public_nodes: [] as Node[],
+ permissions: [] as Permission[],
allTags: [] as string[],
isFetching: false,
}),
@@ -163,6 +164,46 @@ export const useNodesStore = defineStore('nodes', {
return this.nodes;
} else throw request;
},
+ async fetchPermissions(nodeId: string): Promise<Permission[]> {
+ console.log(`[store/nodes/permissions] Fetching permissions for node: ${nodeId}`);
+ const node = this.nodes.find(d => d.id === nodeId);
+ if (!node) throw 'Node not found in store, cannot fetch permissions';
+ const request = await makeRequest(`permissions/${nodeId}`, 'GET', {});
+ if (request.status === 'success') {
+ for (const perm of request.result as Permission[]) {
+ perm.user = await useUserStore().fetchPublicUser(perm.user_id);
+ const index = this.permissions.findIndex(p => p.id == perm.id);
+ if (index == -1) this.permissions.push(perm);
+ else this.permissions[index] = perm;
+ }
+ return request.result as Permission[];
+ } else throw request;
+ },
+ async addPermission(perm: Omit<Permission, 'id' | 'created_timestamp'>): Promise<Permission> {
+ console.log(`[store/nodes/permissions] Adding permission for user ${perm.user_id} on node ${perm.node_id}`);
+ const request = await makeRequest(`permissions`, 'POST', perm);
+ if (request.status === 'success') {
+ this.permissions.push(request.result as Permission);
+ return request.result as Permission;
+ } else throw request.message;
+ },
+ async updatePermission(perm: Permission) {
+ console.log(`[store/nodes/permissions] Updating permission for user ${perm.user_id} on node ${perm.node_id}`);
+ const request = await makeRequest(`permissions/${perm.id}`, 'PATCH', { permission: perm.permission });
+ if (request.status === 'success') {
+ const index = this.permissions.findIndex(p => p.id === perm.id);
+ if (index !== -1) this.permissions[index]!.permission = perm.permission;
+ } else throw request.message;
+ },
+ async removePermission(nodeId: string, userId: string) {
+ console.log(`[store/nodes/permissions] Removing permission for user ${userId} on node ${nodeId}`);
+ const perm = this.permissions.find(p => p.node_id === nodeId && p.user_id === userId);
+ if (!perm) throw 'Permission not found in store, cannot remove permission';
+ const request = await makeRequest(`permissions/${perm.id}`, 'DELETE', {});
+ if (request.status === 'success') {
+ this.permissions = this.permissions.filter(p => p.id !== perm.id);
+ } else throw request.message;
+ },
async post(node: Partial<Node>): Promise<DB_Node> {
const request = await makeRequest('nodes', 'POST', node);
if (request.status == 'success') {
diff --git a/frontend/app/stores/user.store.ts b/frontend/app/stores/user.store.ts
index 7f19ccdd..0cf9e022 100644
--- a/frontend/app/stores/user.store.ts
+++ b/frontend/app/stores/user.store.ts
@@ -34,8 +34,10 @@ export const useUserStore = defineStore('user', {
return this.user;
} else throw responce.message;
},
- async fetchPublicUser(usernameOrEmail: string): Promise<PublicUser> {
- const responce = await makeRequest<PublicUser>(`users/public/${usernameOrEmail}`, 'GET', {});
+ async fetchPublicUser(usernameOrEmailOrId: string): Promise<PublicUser> {
+ const existingUser = this.users.find(u => u.id === usernameOrEmailOrId);
+ if (existingUser) return existingUser;
+ const responce = await makeRequest<PublicUser>(`users/public/${usernameOrEmailOrId}`, 'GET', {});
if (responce.status === 'success') {
const user = responce.result as PublicUser;
if (!this.users.find(u => u.id === user.id)) this.users.push(user);