π The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
Refactor access control and permissions handling - Remove old permissions system - Update to use new system based on actor - Update middlewares to use the new system
Smaug6739bc8de305a1e8
diff --git a/backend/controllers/access.go b/backend/controllers/access.gonew file mode 100644index 00000000..a20c3824--- /dev/null+++ b/backend/controllers/access.go@@ -0,0 +1,30 @@+package controllers++import (+ "alexandrie/permissions"+ "errors"+ "net/http"++ "github.com/gin-gonic/gin"+)++func actorFromRequest(c *gin.Context) (permissions.Actor, error) {+ actor, ok := permissions.ActorFromContext(c.Request.Context())+ if !ok || actor.UserID == 0 {+ return permissions.Actor{}, permissions.ErrUnauthorized+ }+ return actor, nil+}++func statusFromAccessError(err error) int {+ if errors.Is(err, permissions.ErrUnauthorized) {+ return http.StatusUnauthorized+ }+ if errors.Is(err, permissions.ErrForbidden) {+ return http.StatusForbidden+ }+ if errors.Is(err, permissions.ErrNotFound) {+ return http.StatusNotFound+ }+ return http.StatusInternalServerError+}diff --git a/backend/controllers/backup.controller.go b/backend/controllers/backup.controller.goindex 224e3093..19ab3483 100644--- a/backend/controllers/backup.controller.go+++ b/backend/controllers/backup.controller.go@@ -2,7 +2,6 @@ package controllersimport ("alexandrie/app"- "alexandrie/permissions""alexandrie/types""alexandrie/utils""errors"@@ -19,8 +18,7 @@ type BackupController interface {func NewBackupController(app *app.App) BackupController {return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}diff --git a/backend/controllers/index.go b/backend/controllers/index.goindex 366f606a..d2a03999 100644--- a/backend/controllers/index.go+++ b/backend/controllers/index.go@@ -2,10 +2,8 @@ package controllersimport ("alexandrie/app"- "alexandrie/permissions")type Controller struct {- app *app.App- authorizer permissions.Authorizer+ app *app.App}diff --git a/backend/controllers/nodes.controller.go b/backend/controllers/nodes.controller.goindex 913d420c..5bbc455b 100644--- a/backend/controllers/nodes.controller.go+++ b/backend/controllers/nodes.controller.go@@ -3,7 +3,6 @@ package controllersimport ("alexandrie/app""alexandrie/models"- "alexandrie/permissions""alexandrie/utils""net/http""strconv"@@ -25,8 +24,7 @@ type NodeController interface {func NewNodeController(app *app.App) NodeController {utils.InitBluemonday()return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}@@ -54,18 +52,18 @@ func (ctr *Controller) GetPublicNode(c *gin.Context) (int, any) {// @Param userId path string true "Target User ID"// @Router /nodes/shared/{userId} [get]func (ctr *Controller) GetSharedNodes(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))if err != nil {return http.StatusBadRequest, err}- nodes, err := ctr.app.Services.Node.GetSharedNodes(targetUserId, connectedUserId, connectedUserRole)+ nodes, err := ctr.app.Services.Node.GetSharedNodes(c.Request.Context(), targetUserId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, nodes}@@ -76,18 +74,19 @@ func (ctr *Controller) GetSharedNodes(c *gin.Context) (int, any) {// @Param userId path string true "Target User ID"// @Router /nodes/{userId} [get]func (ctr *Controller) GetNodes(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))+if err != nil {return http.StatusBadRequest, err}- nodes, err := ctr.app.Services.Node.GetAllNodes(targetUserId, connectedUserId, connectedUserRole)+ nodes, err := ctr.app.Services.Node.GetAllNodes(c.Request.Context(), targetUserId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, nodes}@@ -102,14 +101,13 @@ func (ctr *Controller) GetNode(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- result, err := ctr.app.Services.Node.GetNode(nodeId, connectedUserId, connectedUserRole, ctr.authorizer)+ result, err := ctr.app.Services.Node.GetNode(c.Request.Context(), nodeId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, result}@@ -123,11 +121,6 @@ func (ctr *Controller) GetNode(c *gin.Context) (int, any) {// - content: include content body in search (optional, default false)// - limit: max results (optional, default 20, max 100)func (ctr *Controller) SearchNodes(c *gin.Context) (int, any) {- connectedUserId, _, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err- }-query := c.Query("q")if len(query) < 2 {return http.StatusBadRequest, "Search query must be at least 2 characters"@@ -142,7 +135,7 @@ func (ctr *Controller) SearchNodes(c *gin.Context) (int, any) {}}- results, err := ctr.app.Services.Node.SearchNodes(connectedUserId, query, includeContent, limit)+ results, err := ctr.app.Services.Node.SearchNodes(c.Request.Context(), query, includeContent, limit)if err != nil {return http.StatusInternalServerError, err}@@ -159,14 +152,13 @@ func (ctr *Controller) CreateNode(c *gin.Context) (int, any) {if err := c.ShouldBind(&node); err != nil {return http.StatusBadRequest, err}- userId, _, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- createdNode, err := ctr.app.Services.Node.CreateNode(&node, userId)+ createdNode, err := ctr.app.Services.Node.CreateNode(c.Request.Context(), &node)if err != nil {- return http.StatusInternalServerError, err+ return statusFromAccessError(err), err}return http.StatusOK, createdNode}@@ -181,9 +173,8 @@ func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}var node models.Node@@ -191,9 +182,9 @@ func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {return http.StatusBadRequest, err}- updatedNode, err := ctr.app.Services.Node.UpdateNode(nodeId, &node, connectedUserId, connectedUserRole, ctr.authorizer)+ updatedNode, err := ctr.app.Services.Node.UpdateNode(c.Request.Context(), nodeId, &node)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, updatedNode}@@ -208,14 +199,13 @@ func (ctr *Controller) DeleteNode(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- err = ctr.app.Services.Node.DeleteNode(nodeId, connectedUserId, connectedUserRole, ctr.authorizer)+ err = ctr.app.Services.Node.DeleteNode(c.Request.Context(), nodeId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, "OK"}diff --git a/backend/controllers/nodes.permissions.controller.go b/backend/controllers/nodes.permissions.controller.goindex 4324daa4..194050f3 100644--- a/backend/controllers/nodes.permissions.controller.go+++ b/backend/controllers/nodes.permissions.controller.go@@ -3,7 +3,6 @@ package controllersimport ("alexandrie/app""alexandrie/models"- "alexandrie/permissions""alexandrie/utils""net/http"@@ -19,8 +18,7 @@ type PermissionsController interface {func NewPermissionsController(app *app.App) PermissionsController {return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}@@ -34,14 +32,13 @@ func (ctr *Controller) GetNodePermissions(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- perms, err := ctr.app.Services.Permission.GetNodePermissions(nodeId, connectedUserId, connectedUserRole, ctr.authorizer)+ perms, err := ctr.app.Services.Permission.GetNodePermissions(c.Request.Context(), nodeId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, perms}@@ -60,14 +57,13 @@ func (ctr *Controller) CreatePermission(c *gin.Context) (int, any) {if err := c.ShouldBindJSON(&perm); err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- createdPerm, err := ctr.app.Services.Permission.CreatePermission(nodeId, perm.UserId, perm.Permission, connectedUserId, connectedUserRole, ctr.authorizer)+ createdPerm, err := ctr.app.Services.Permission.CreatePermission(c.Request.Context(), nodeId, perm.UserId, perm.Permission)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, createdPerm}@@ -82,9 +78,8 @@ func (ctr *Controller) UpdatePermission(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}var requestChange models.Permission@@ -92,9 +87,9 @@ func (ctr *Controller) UpdatePermission(c *gin.Context) (int, any) {return http.StatusBadRequest, err}- err = ctr.app.Services.Permission.UpdatePermission(permId, requestChange.Permission, connectedUserId, connectedUserRole, ctr.authorizer)+ err = ctr.app.Services.Permission.UpdatePermission(c.Request.Context(), permId, requestChange.Permission)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, "Permission updated"}@@ -109,14 +104,13 @@ func (ctr *Controller) DeletePermission(c *gin.Context) (int, any) {if err != nil {return http.StatusBadRequest, err}- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}- err = ctr.app.Services.Permission.DeletePermission(permId, connectedUserId, connectedUserRole, ctr.authorizer)+ err = ctr.app.Services.Permission.DeletePermission(c.Request.Context(), permId)if err != nil {- return http.StatusUnauthorized, err+ return statusFromAccessError(err), err}return http.StatusOK, "Permission deleted"}diff --git a/backend/controllers/resources.controller.go b/backend/controllers/resources.controller.goindex ce0a7c1d..3c8f1e45 100644--- a/backend/controllers/resources.controller.go+++ b/backend/controllers/resources.controller.go@@ -2,7 +2,6 @@ package controllersimport ("alexandrie/app"- "alexandrie/permissions""alexandrie/types""alexandrie/utils""errors"@@ -19,8 +18,7 @@ type ResourceController interface {func NewResourceController(app *app.App) ResourceController {return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}@@ -37,6 +35,9 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {int64(ctr.app.Config.Cdn.MaxSize),)file, header, err := c.Request.FormFile("file")+ if err != nil {+ return http.StatusBadRequest, errors.New("file too large or failed to get file")+ }parentIdStr := c.Request.FormValue("parent_id")var parentId *types.Snowflake = nil@@ -50,22 +51,21 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {return http.StatusInternalServerError, errors.New("failed to read file")}- userId, err := utils.GetUserIdCtx(c)- if err != nil {- return http.StatusBadRequest, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}mimeType := header.Header.Get("Content-Type")node, err := ctr.app.Services.Resource.UploadFile(+ c.Request.Context(),header.Filename,header.Size,fileContent,mimeType,parentId,- userId,)if err != nil {- return http.StatusBadRequest, err+ return statusFromAccessError(err), err}return http.StatusOK, node@@ -96,7 +96,7 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {userId, err := utils.GetUserIdCtx(c)if err != nil {- return http.StatusBadRequest, err+ return http.StatusUnauthorized, err}mimeType := header.Header.Get("Content-Type")diff --git a/backend/controllers/user_settings.controller.go b/backend/controllers/user_settings.controller.goindex d2244721..e5beb3a1 100644--- a/backend/controllers/user_settings.controller.go+++ b/backend/controllers/user_settings.controller.go@@ -3,7 +3,6 @@ package controllersimport ("alexandrie/app""alexandrie/models"- "alexandrie/permissions""alexandrie/types""alexandrie/utils""net/http"@@ -18,8 +17,7 @@ type UserSettingsController interface {func NewUserSettingsController(app *app.App) UserSettingsController {return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.goindex 70e21193..5698d4cf 100644--- a/backend/controllers/users.controller.go+++ b/backend/controllers/users.controller.go@@ -3,7 +3,6 @@ package controllersimport ("alexandrie/app""alexandrie/models"- "alexandrie/permissions""alexandrie/utils""errors""net/http"@@ -24,8 +23,7 @@ type UserController interface {func NewUserController(app *app.App) UserController {return &Controller{- app: app,- authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ app: app,}}@@ -76,22 +74,18 @@ func (ctr *Controller) GetPublicUser(c *gin.Context) (int, any) {// @Failure 400 {object} Error// @Failure 401 {object} Errorfunc (ctr *Controller) GetUserById(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))if err != nil {return http.StatusBadRequest, err}- if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {- return http.StatusUnauthorized, err- }-- result, err := ctr.app.Services.User.GetUserById(targetUserId)+ result, err := ctr.app.Services.User.GetUserById(c.Request.Context(), targetUserId)if err != nil {- return http.StatusInternalServerError, err+ return statusFromAccessError(err), err}return http.StatusOK, result@@ -142,27 +136,23 @@ func (ctr *Controller) CreateUser(c *gin.Context) (int, any) {// @Failure 400 {object} Error// @Failure 401 {object} Errorfunc (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))if err != nil {return http.StatusBadRequest, err}- if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {- return http.StatusUnauthorized, err- }-var user models.Userif err := c.ShouldBind(&user); err != nil {return http.StatusBadRequest, err}- updatedUser, err := ctr.app.Services.User.UpdateUser(targetUserId, user.Firstname, user.Lastname, user.Avatar, user.Email)+ updatedUser, err := ctr.app.Services.User.UpdateUser(c.Request.Context(), targetUserId, user.Firstname, user.Lastname, user.Avatar, user.Email)if err != nil {- return http.StatusInternalServerError, err+ return statusFromAccessError(err), err}return http.StatusOK, updatedUser}@@ -178,19 +168,15 @@ func (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {// @Failure 400 {object} Error// @Failure 401 {object} Errorfunc (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))if err != nil {return http.StatusBadRequest, err}- if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {- return http.StatusUnauthorized, err- }-var payload struct {Password string `form:"password" json:"password"`}@@ -198,9 +184,9 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {return http.StatusBadRequest, errors.New("invalid request payload")}- err = ctr.app.Services.User.UpdatePassword(targetUserId, payload.Password)+ err = ctr.app.Services.User.UpdatePassword(c.Request.Context(), targetUserId, payload.Password)if err != nil {- return http.StatusInternalServerError, err+ return statusFromAccessError(err), err}return http.StatusOK, "Password updated successfully"}@@ -215,22 +201,17 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {// @Failure 400 {object} Error// @Failure 401 {object} Errorfunc (ctr *Controller) DeleteUser(c *gin.Context) (int, any) {- connectedUserId, connectedUserRole, err := utils.GetUserContext(c)- if err != nil {- return http.StatusUnauthorized, err+ if _, err := actorFromRequest(c); err != nil {+ return statusFromAccessError(err), err}+targetUserId, err := utils.GetTargetId(c, c.Param("userId"))if err != nil {return http.StatusBadRequest, err}-- if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {- return http.StatusUnauthorized, err- }-- err = ctr.app.Services.User.DeleteUser(targetUserId, ctr.app.Services.Minio)+ err = ctr.app.Services.User.DeleteUser(c.Request.Context(), targetUserId, ctr.app.Services.Minio)if err != nil {- return http.StatusInternalServerError, err+ return statusFromAccessError(err), err}return http.StatusOK, "User deleted successfully"}diff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.goindex f21133db..6665c616 100644--- a/backend/middlewares/authentification.go+++ b/backend/middlewares/authentification.go@@ -54,6 +54,8 @@ func Auth() gin.HandlerFunc {}c.Set("user_id", types.Snowflake(user_id))c.Set("user_role", permissions.UserRole(user_role))+ actor := permissions.Actor{UserID: types.Snowflake(user_id), Role: permissions.UserRole(user_role)}+ c.Request = c.Request.WithContext(permissions.WithActor(c.Request.Context(), actor))//c.Set("claims", claims)c.Next()}diff --git a/backend/permissions/service.go b/backend/permissions/service.goindex a1e2c30e..13f7543c 100644--- a/backend/permissions/service.go+++ b/backend/permissions/service.go@@ -4,52 +4,117 @@ import ("alexandrie/models""alexandrie/repositories""alexandrie/types"+ "context""errors")-type Authorizer interface {- CanAccessNode(userID types.Snowflake, userRole UserRole, node *models.Node, action NodeAction) (bool, NodePermissionLevel, error)- CanAccessUser(connectedID, targetID types.Snowflake, userRole UserRole) (bool, error)+type Actor struct {+ UserID types.Snowflake+ Role UserRole+}++type actorContextKey string++const ACTOR_CTX_KEY actorContextKey = "actor"++func WithActor(ctx context.Context, actor Actor) context.Context {+ return context.WithValue(ctx, ACTOR_CTX_KEY, actor)+}++func ActorFromContext(ctx context.Context) (Actor, bool) {+ if ctx == nil {+ return Actor{}, false+ }+ actor, ok := ctx.Value(ACTOR_CTX_KEY).(Actor)+ return actor, ok+}++var (+ ErrUnauthorized = errors.New("unauthorized")+ ErrForbidden = errors.New("forbidden")+ ErrNotFound = errors.New("not found")+)++type NodeDecision struct {+ Node *models.Node+ Level NodePermissionLevel+ Owner bool+}++type AccessGuard interface {+ RequireNodeAction(actor Actor, nodeID types.Snowflake, action NodeAction) (NodeDecision, error)+ CheckNodeAction(actor Actor, node *models.Node, action NodeAction) (NodePermissionLevel, error)+ RequireUserAccess(actor Actor, targetID types.Snowflake) errorIsAppAdmin(userRole UserRole) bool}-type DefaultAuthorizer struct {+type DefaultAccessGuard struct {+ nodeRepo repositories.NodeRepositorypermRepo repositories.PermissionRepository}-func NewAuthorizer(permRepo repositories.PermissionRepository) Authorizer {- return &DefaultAuthorizer{permRepo: permRepo}+func NewAccessGuard(nodeRepo repositories.NodeRepository, permRepo repositories.PermissionRepository) AccessGuard {+ return &DefaultAccessGuard{nodeRepo: nodeRepo, permRepo: permRepo}}-func (a *DefaultAuthorizer) CanAccessNode(userID types.Snowflake, userRole UserRole, node *models.Node, action NodeAction) (bool, NodePermissionLevel, error) {+// RequireNodeAction checks if the actor has the required permissions for the specified action on the node.+func (a *DefaultAccessGuard) RequireNodeAction(actor Actor, nodeID types.Snowflake, action NodeAction) (NodeDecision, error) {+ node, err := a.nodeRepo.GetByID(nodeID)+ if err != nil {+ return NodeDecision{}, err+ }+ if node == nil {+ return NodeDecision{}, ErrNotFound+ }++ level, err := a.CheckNodeAction(actor, node, action)+ if err != nil {+ return NodeDecision{Node: node, Level: level, Owner: actor.UserID == node.UserId}, err+ }++ return NodeDecision{Node: node, Level: level, Owner: actor.UserID == node.UserId}, nil+}++// CheckNodeAction checks the permission level of the actor for the specified action on the node.+func (a *DefaultAccessGuard) CheckNodeAction(actor Actor, node *models.Node, action NodeAction) (NodePermissionLevel, error) {+ if actor.UserID == 0 {+ return PermNone, ErrUnauthorized+ }+// Case 1: Owner of the node- if userID == node.UserId {- return true, PermOwner, nil+ if actor.UserID == node.UserId {+ return PermOwner, nil}// Case 2: Global app admin- if a.IsAppAdmin(userRole) {- return true, PermOwner, nil+ if a.IsAppAdmin(actor.Role) {+ return PermOwner, nil}// Case 3: Check in DB via PermissionRepository- hasPermission, level := a.permRepo.HasPermission(userID, node.Id, int(action.RequiredLevel()))+ hasPermission, level := a.permRepo.HasPermission(actor.UserID, node.Id, int(action.RequiredLevel()))if hasPermission {- return true, NodePermissionLevel(level), nil+ return NodePermissionLevel(level), nil}- return false, PermNone, errors.New("unauthorized")++ return PermNone, ErrForbidden}-func (a *DefaultAuthorizer) CanAccessUser(connectedID, targetID types.Snowflake, userRole UserRole) (bool, error) {- if connectedID == targetID {- return true, nil+// RequireUserAccess checks if the actor has access to the target user ID (either it's their own ID or they are an app admin).+func (a *DefaultAccessGuard) RequireUserAccess(actor Actor, targetID types.Snowflake) error {+ if actor.UserID == 0 {+ return ErrUnauthorized+ }++ if actor.UserID == targetID {+ return nil}- if a.IsAppAdmin(userRole) {- return true, nil+ if a.IsAppAdmin(actor.Role) {+ return nil}- return false, errors.New("unauthorized")+ return ErrForbidden}-func (a *DefaultAuthorizer) IsAppAdmin(userRole UserRole) bool {+func (a *DefaultAccessGuard) IsAppAdmin(userRole UserRole) bool {return userRole == RoleAdministrator}diff --git a/backend/services/access.go b/backend/services/access.gonew file mode 100644index 00000000..661ee85c--- /dev/null+++ b/backend/services/access.go@@ -0,0 +1,14 @@+package services++import (+ "alexandrie/permissions"+ "context"+)++func actorFromContext(ctx context.Context) (permissions.Actor, error) {+ actor, ok := permissions.ActorFromContext(ctx)+ if !ok || actor.UserID == 0 {+ return permissions.Actor{}, permissions.ErrUnauthorized+ }+ return actor, nil+}diff --git a/backend/services/manager.go b/backend/services/manager.goindex 6ad7799c..a70d4488 100644--- a/backend/services/manager.go+++ b/backend/services/manager.go@@ -1,6 +1,7 @@package servicesimport (+ "alexandrie/permissions""alexandrie/pkg/logger""alexandrie/pkg/snowflake""alexandrie/repositories"@@ -10,6 +11,7 @@ import ()type ServiceManager struct {+ Access permissions.AccessGuardAuth AuthServiceUser UserServiceNode NodeService@@ -36,13 +38,14 @@ func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowfla}func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, resourceConfig ResourceConfig) error {+ sm.Access = permissions.NewAccessGuard(repos.Node, repos.Permission)sm.Auth = NewAuthService(repos.User, repos.Session, repos.Log, snowflake)- sm.User = NewUserService(repos.User, repos.Log, snowflake)+ sm.User = NewUserService(repos.User, repos.Log, snowflake, sm.Access)sm.Minio = NewMinioService(minioClient)- sm.Node = NewNodeService(repos.Node, repos.Permission, sm.Minio, snowflake)- sm.Permission = NewPermissionService(repos.Permission, repos.Node, snowflake)+ sm.Node = NewNodeService(repos.Node, repos.Permission, sm.Minio, snowflake, sm.Access)+ sm.Permission = NewPermissionService(repos.Permission, repos.Node, snowflake, sm.Access)sm.Session = NewSessionService(repos.Session)- sm.Resource = NewResourceService(repos.Node, snowflake, minioClient, resourceConfig)+ sm.Resource = NewResourceService(repos.Node, snowflake, minioClient, resourceConfig, sm.Access)sm.Backup = NewBackupService(repos.Node, repos.UserSettings)sm.OIDC = NewOIDCService(repos.OIDCProvider, repos.User, sm.User, repos.Session, repos.Log, snowflake)sm.UserSettings = NewUserSettingsService(repos.UserSettings)diff --git a/backend/services/node.service.go b/backend/services/node.service.goindex 8b88685c..351cae76 100644--- a/backend/services/node.service.go+++ b/backend/services/node.service.go@@ -7,21 +7,21 @@ import ("alexandrie/repositories""alexandrie/types""alexandrie/utils"- "errors"+ "context""time")type NodeService interface {- GetAllNodes(userId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole) ([]*models.Node, error)- GetSharedNodes(userId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole) ([]*models.Node, error)+ GetAllNodes(ctx context.Context, userId types.Snowflake) ([]*models.Node, error)+ GetSharedNodes(ctx context.Context, userId types.Snowflake) ([]*models.Node, error)GetAllNodeBackup(userId types.Snowflake) ([]*models.Node, error)GetUserUploadsSize(userId types.Snowflake) (int64, error)GetPublicNode(nodeId types.Snowflake) (*models.PublicNodeResponse, error)- GetNode(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (map[string]any, error)- CreateNode(node *models.Node, userId types.Snowflake) (*models.Node, error)- UpdateNode(nodeId types.Snowflake, node *models.Node, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (*models.Node, error)- DeleteNode(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error- SearchNodes(userId types.Snowflake, query string, includeContent bool, limit int) ([]*models.NodeSearchResult, error)+ GetNode(ctx context.Context, nodeId types.Snowflake) (map[string]any, error)+ CreateNode(ctx context.Context, node *models.Node) (*models.Node, error)+ UpdateNode(ctx context.Context, nodeId types.Snowflake, node *models.Node) (*models.Node, error)+ DeleteNode(ctx context.Context, nodeId types.Snowflake) error+ SearchNodes(ctx context.Context, query string, includeContent bool, limit int) ([]*models.NodeSearchResult, error)}type nodeService struct {@@ -29,27 +29,37 @@ type nodeService struct {permRepo repositories.PermissionRepositoryminioService MinioServicesnowflake *snowflake.Snowflake+ access permissions.AccessGuard}-func NewNodeService(nodeRepo repositories.NodeRepository, permRepo repositories.PermissionRepository, minioService MinioService, snowflake *snowflake.Snowflake) NodeService {+func NewNodeService(nodeRepo repositories.NodeRepository, permRepo repositories.PermissionRepository, minioService MinioService, snowflake *snowflake.Snowflake, access permissions.AccessGuard) NodeService {return &nodeService{nodeRepo: nodeRepo,permRepo: permRepo,minioService: minioService,snowflake: snowflake,+ access: access,}}-func (s *nodeService) GetAllNodes(userId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole) ([]*models.Node, error) {- if connectedUserId != userId && connectedUserRole != permissions.RoleAdministrator {- return nil, errors.New("unauthorized")+func (s *nodeService) GetAllNodes(ctx context.Context, userId types.Snowflake) ([]*models.Node, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ if actor.UserID != userId && !s.access.IsAppAdmin(actor.Role) {+ return nil, permissions.ErrForbidden}return s.nodeRepo.GetAll(userId)}-func (s *nodeService) GetSharedNodes(userId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole) ([]*models.Node, error) {- if connectedUserId != userId && connectedUserRole != permissions.RoleAdministrator {- return nil, errors.New("unauthorized")+func (s *nodeService) GetSharedNodes(ctx context.Context, userId types.Snowflake) ([]*models.Node, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ if actor.UserID != userId && !s.access.IsAppAdmin(actor.Role) {+ return nil, permissions.ErrForbidden}return s.nodeRepo.GetShared(userId)}@@ -88,15 +98,15 @@ func (s *nodeService) GetPublicNode(nodeId types.Snowflake) (*models.PublicNodeR}, nil}-func (s *nodeService) GetNode(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (map[string]any, error) {- dbNode, err := s.nodeRepo.GetByID(nodeId)+func (s *nodeService) GetNode(ctx context.Context, nodeId types.Snowflake) (map[string]any, error) {+ actor, err := actorFromContext(ctx)if err != nil {return nil, err}- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionRead)- if !allowed || err != nil {- return nil, errors.New("unauthorized")+ decision, err := s.access.RequireNodeAction(actor, nodeId, permissions.ActionRead)+ if err != nil {+ return nil, err}perms, err := s.permRepo.GetByNode(nodeId)@@ -106,31 +116,46 @@ func (s *nodeService) GetNode(nodeId types.Snowflake, connectedUserId types.SnowfilteredPerms := []*models.Permission{}for _, p := range perms {- if p.UserId == connectedUserId || dbNode.UserId == connectedUserId {+ if p.UserId == actor.UserID || decision.Node.UserId == actor.UserID {filteredPerms = append(filteredPerms, p)}}return map[string]any{- "node": dbNode,+ "node": decision.Node,"permissions": filteredPerms,}, nil}-func (s *nodeService) CreateNode(node *models.Node, userId types.Snowflake) (*models.Node, error) {+func (s *nodeService) CreateNode(ctx context.Context, node *models.Node) (*models.Node, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+escapedHTMLContent := utils.EscapeHTML(node.ContentCompiled)- description := ""- if node.Description != nil {- description = *node.Description+ // Parent ID: Check if exists and user has permissions to create under it+ safeParentId := node.ParentId+ if node.ParentId != nil {+ parentNode, err := s.nodeRepo.GetByID(*node.ParentId)+ if err != nil {+ safeParentId = nil+ }+ if parentNode != nil {+ level, err := s.access.CheckNodeAction(actor, parentNode, permissions.ActionUpdate)+ if err != nil || level == permissions.PermNone {+ safeParentId = nil+ }+ }}createdNode := &models.Node{Id: s.snowflake.Generate(),- ParentId: node.ParentId,- UserId: userId,+ ParentId: safeParentId,+ UserId: actor.UserID,Name: node.Name,- Description: &description,+ Description: node.Description,Role: node.Role,Tags: node.Tags,Thumbnail: node.Thumbnail,@@ -155,24 +180,49 @@ func (s *nodeService) CreateNode(node *models.Node, userId types.Snowflake) (*moreturn createdNode, nil}-func (s *nodeService) UpdateNode(nodeId types.Snowflake, node *models.Node, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (*models.Node, error) {+func (s *nodeService) UpdateNode(ctx context.Context, nodeId types.Snowflake, node *models.Node) (*models.Node, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+dbNode, err := s.nodeRepo.GetByID(nodeId)if err != nil {return nil, err}+ if dbNode == nil {+ return nil, permissions.ErrNotFound+ }- allowed, level, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionUpdate)- if !allowed && (dbNode.Access < 2 || *dbNode.Accessibility != 3) {- return nil, errors.New("unauthorized")+ level, err := s.access.CheckNodeAction(actor, dbNode, permissions.ActionUpdate)+ if err != nil {+ if dbNode.Access < 2 || dbNode.Accessibility == nil || *dbNode.Accessibility != 3 {+ return nil, err+ }}- if dbNode.UserId != connectedUserId && level < permissions.PermOwner {+ if dbNode.UserId != actor.UserID && level < permissions.PermOwner {node.ParentId = dbNode.ParentIdnode.UserId = dbNode.UserIdnode.Accessibility = dbNode.Accessibilitynode.Access = dbNode.Access}+ // Parent ID: Check if exists and user has permissions to create under it+ safeParentId := node.ParentId+ if node.ParentId != nil {+ parentNode, err := s.nodeRepo.GetByID(*node.ParentId)+ if err != nil {+ safeParentId = nil+ }+ if parentNode != nil {+ parentLevel, err := s.access.CheckNodeAction(actor, parentNode, permissions.ActionUpdate)+ if err != nil || parentLevel == permissions.PermNone {+ safeParentId = nil+ }+ }+ }+escapedHTMLContent := utils.EscapeHTML(node.ContentCompiled)description := ""if node.Description != nil {@@ -181,7 +231,7 @@ func (s *nodeService) UpdateNode(nodeId types.Snowflake, node *models.Node, connupdatedNode := &models.Node{Id: nodeId,- ParentId: node.ParentId,+ ParentId: safeParentId,UserId: node.UserId,Name: node.Name,Description: &description,@@ -207,25 +257,21 @@ func (s *nodeService) UpdateNode(nodeId types.Snowflake, node *models.Node, connreturn updatedNode, nil}-func (s *nodeService) DeleteNode(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error {- dbNode, err := s.nodeRepo.GetByID(nodeId)+func (s *nodeService) DeleteNode(ctx context.Context, nodeId types.Snowflake) error {+ actor, err := actorFromContext(ctx)if err != nil {return err}- if dbNode == nil {- return errors.New("node not found")- }-- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionDelete)- if !allowed || err != nil {- return errors.New("unauthorized")+ decision, err := s.access.RequireNodeAction(actor, nodeId, permissions.ActionDelete)+ if err != nil {+ return err}// Get all descendant resources (role=4) before deletion// This is necessary because ON DELETE CASCADE will remove them from DB// but we need to clean up their files in MinIO first- resources, err := s.nodeRepo.GetDescendantResources(nodeId)+ resources, err := s.nodeRepo.GetDescendantResources(decision.Node.Id)if err != nil {// logger.Warn(fmt.Sprintf("Failed to get descendant resources for node %d: %v", nodeId, err))// Continue with deletion even if we can't get resources@@ -242,10 +288,14 @@ func (s *nodeService) DeleteNode(nodeId types.Snowflake, connectedUserId types.S}// Now delete the node from DB (CASCADE will handle children)- return s.nodeRepo.Delete(nodeId)+ return s.nodeRepo.Delete(decision.Node.Id)}// SearchNodes performs a fulltext search on user's documents-func (s *nodeService) SearchNodes(userId types.Snowflake, query string, includeContent bool, limit int) ([]*models.NodeSearchResult, error) {- return s.nodeRepo.SearchFulltext(userId, query, includeContent, limit)+func (s *nodeService) SearchNodes(ctx context.Context, query string, includeContent bool, limit int) ([]*models.NodeSearchResult, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ return s.nodeRepo.SearchFulltext(actor.UserID, query, includeContent, limit)}diff --git a/backend/services/permission.service.go b/backend/services/permission.service.goindex e29bf5fb..9cf78d11 100644--- a/backend/services/permission.service.go+++ b/backend/services/permission.service.go@@ -6,42 +6,43 @@ import ("alexandrie/pkg/snowflake""alexandrie/repositories""alexandrie/types"- "errors"+ "context""time")type PermissionService interface {- GetNodePermissions(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) ([]*models.Permission, error)+ GetNodePermissions(ctx context.Context, nodeId types.Snowflake) ([]*models.Permission, error)GetPermission(id types.Snowflake) (*models.Permission, error)HasPermission(userId, nodeId types.Snowflake, required int) (bool, int)- CreatePermission(nodeId, userId types.Snowflake, permission int, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (*models.Permission, error)- UpdatePermission(id types.Snowflake, permission int, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error- DeletePermission(id types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error+ CreatePermission(ctx context.Context, nodeId, userId types.Snowflake, permission int) (*models.Permission, error)+ UpdatePermission(ctx context.Context, id types.Snowflake, permission int) error+ DeletePermission(ctx context.Context, id types.Snowflake) error}type permissionService struct {permRepo repositories.PermissionRepositorynodeRepo repositories.NodeRepositorysnowflake *snowflake.Snowflake+ access permissions.AccessGuard}-func NewPermissionService(permRepo repositories.PermissionRepository, nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake) PermissionService {+func NewPermissionService(permRepo repositories.PermissionRepository, nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake, access permissions.AccessGuard) PermissionService {return &permissionService{permRepo: permRepo,nodeRepo: nodeRepo,snowflake: snowflake,+ access: access,}}-func (s *permissionService) GetNodePermissions(nodeId types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) ([]*models.Permission, error) {- dbNode, err := s.nodeRepo.GetByID(nodeId)+func (s *permissionService) GetNodePermissions(ctx context.Context, nodeId types.Snowflake) ([]*models.Permission, error) {+ actor, err := actorFromContext(ctx)if err != nil {return nil, err}- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionManagePermissions)- if !allowed || err != nil {- return nil, errors.New("unauthorized")+ if _, err = s.access.RequireNodeAction(actor, nodeId, permissions.ActionManagePermissions); err != nil {+ return nil, err}return s.permRepo.GetByNode(nodeId)@@ -55,15 +56,14 @@ func (s *permissionService) HasPermission(userId, nodeId types.Snowflake, requirreturn s.permRepo.HasPermission(userId, nodeId, required)}-func (s *permissionService) CreatePermission(nodeId, userId types.Snowflake, permission int, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) (*models.Permission, error) {- dbNode, err := s.nodeRepo.GetByID(nodeId)+func (s *permissionService) CreatePermission(ctx context.Context, nodeId, userId types.Snowflake, permission int) (*models.Permission, error) {+ actor, err := actorFromContext(ctx)if err != nil {return nil, err}- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionManagePermissions)- if !allowed || err != nil {- return nil, errors.New("unauthorized")+ if _, err = s.access.RequireNodeAction(actor, nodeId, permissions.ActionManagePermissions); err != nil {+ return nil, err}perm := &models.Permission{@@ -80,20 +80,19 @@ func (s *permissionService) CreatePermission(nodeId, userId types.Snowflake, perreturn perm, nil}-func (s *permissionService) UpdatePermission(id types.Snowflake, permission int, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error {-- perm, err := s.permRepo.GetByID(id)+func (s *permissionService) UpdatePermission(ctx context.Context, id types.Snowflake, permission int) error {+ actor, err := actorFromContext(ctx)if err != nil {return err}- dbNode, err := s.nodeRepo.GetByID(perm.NodeId)+ perm, err := s.permRepo.GetByID(id)if err != nil {return err}- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionManagePermissions)- if !allowed || err != nil {- return errors.New("unauthorized")++ if _, err = s.access.RequireNodeAction(actor, perm.NodeId, permissions.ActionManagePermissions); err != nil {+ return err}updatedPerm := &models.Permission{@@ -103,20 +102,19 @@ func (s *permissionService) UpdatePermission(id types.Snowflake, permission int,return s.permRepo.Update(updatedPerm)}-func (s *permissionService) DeletePermission(id types.Snowflake, connectedUserId types.Snowflake, connectedUserRole permissions.UserRole, authorizer permissions.Authorizer) error {- perm, err := s.permRepo.GetByID(id)+func (s *permissionService) DeletePermission(ctx context.Context, id types.Snowflake) error {+ actor, err := actorFromContext(ctx)if err != nil {return err}- dbNode, err := s.nodeRepo.GetByID(perm.NodeId)+ perm, err := s.permRepo.GetByID(id)if err != nil {return err}- allowed, _, err := authorizer.CanAccessNode(connectedUserId, connectedUserRole, dbNode, permissions.ActionManagePermissions)- if (!allowed || err != nil) && perm.UserId != connectedUserId {- return errors.New("unauthorized")+ if _, err = s.access.RequireNodeAction(actor, perm.NodeId, permissions.ActionManagePermissions); err != nil && perm.UserId != actor.UserID {+ return err}return s.permRepo.Delete(id)diff --git a/backend/services/resource.service.go b/backend/services/resource.service.goindex f09aa1cf..e83235ae 100644--- a/backend/services/resource.service.go+++ b/backend/services/resource.service.go@@ -2,6 +2,7 @@ package servicesimport ("alexandrie/models"+ "alexandrie/permissions""alexandrie/pkg/snowflake""alexandrie/repositories""alexandrie/types"@@ -25,7 +26,7 @@ type ResourceConfig struct {}type ResourceService interface {- UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake, userId types.Snowflake) (*models.Node, error)+ UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake) (*models.Node, error)UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake) error}@@ -34,18 +35,26 @@ type resourceService struct {snowflake *snowflake.SnowflakeminioClient *minio.Clientconfig ResourceConfig+ access permissions.AccessGuard}-func NewResourceService(nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake, minioClient *minio.Client, config ResourceConfig) ResourceService {+func NewResourceService(nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake, minioClient *minio.Client, config ResourceConfig, access permissions.AccessGuard) ResourceService {return &resourceService{nodeRepo: nodeRepo,snowflake: snowflake,minioClient: minioClient,config: config,+ access: access,}}-func (s *resourceService) UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake, userId types.Snowflake) (*models.Node, error) {+func (s *resourceService) UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake) (*models.Node, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ userId := actor.UserID+if s.minioClient == nil {return nil, errors.New("minio client not initialized")}@@ -77,10 +86,25 @@ func (s *resourceService) UploadFile(filename string, fileSize int64, fileConten}accessibility := utils.IntPtr(1)+ // Parent ID: Check if exists and user has permissions to create under it+ safeParentId := parentId+ if parentId != nil {+ parentNode, err := s.nodeRepo.GetByID(*parentId)+ if err != nil {+ safeParentId = nil+ }+ if parentNode != nil {+ level, err := s.access.CheckNodeAction(actor, parentNode, permissions.ActionUpdate)+ if err != nil || level == permissions.PermNone {+ safeParentId = nil+ }+ }+ }+node := &models.Node{Id: id,UserId: userId,- ParentId: parentId,+ ParentId: safeParentId,Name: name,Role: 4,Accessibility: accessibility,diff --git a/backend/services/user.service.go b/backend/services/user.service.goindex cd9de03d..4cf3ec08 100644--- a/backend/services/user.service.go+++ b/backend/services/user.service.go@@ -2,10 +2,12 @@ package servicesimport ("alexandrie/models"+ "alexandrie/permissions""alexandrie/pkg/snowflake""alexandrie/repositories""alexandrie/types""alexandrie/utils"+ "context""crypto/rand""errors""fmt"@@ -18,13 +20,13 @@ import (type UserService interface {GetAllUsers() ([]*models.User, error)- GetUserById(id types.Snowflake) (*models.User, error)+ GetUserById(ctx context.Context, id types.Snowflake) (*models.User, error)GetUserByUsername(username string) (*models.User, error)SearchPublicUsers(query string) ([]*models.User, error)CreateUser(username string, firstname, lastname, avatar, email string, password *string) (*models.User, error)- UpdateUser(id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error)- UpdatePassword(id types.Snowflake, newPassword string) error- DeleteUser(id types.Snowflake, minioService MinioService) error+ UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error)+ UpdatePassword(ctx context.Context, id types.Snowflake, newPassword string) error+ DeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) errorGenerateUniqueUsername(givenName *string, userID types.Snowflake) string}@@ -32,13 +34,15 @@ type userService struct {userRepo repositories.UserRepositorylogRepo repositories.LogRepositorysnowflake *snowflake.Snowflake+ access permissions.AccessGuard}-func NewUserService(userRepo repositories.UserRepository, logRepo repositories.LogRepository, snowflake *snowflake.Snowflake) UserService {+func NewUserService(userRepo repositories.UserRepository, logRepo repositories.LogRepository, snowflake *snowflake.Snowflake, access permissions.AccessGuard) UserService {return &userService{userRepo: userRepo,logRepo: logRepo,snowflake: snowflake,+ access: access,}}@@ -46,13 +50,21 @@ func (s *userService) GetAllUsers() ([]*models.User, error) {return s.userRepo.GetAll()}-func (s *userService) GetUserById(id types.Snowflake) (*models.User, error) {+func (s *userService) GetUserById(ctx context.Context, id types.Snowflake) (*models.User, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ if err := s.access.RequireUserAccess(actor, id); err != nil {+ return nil, err+ }+user, err := s.userRepo.GetByID(id)if err != nil {return nil, err}if user == nil {- return nil, errors.New("user not found")+ return nil, permissions.ErrNotFound}return user, nil@@ -106,10 +118,18 @@ func (s *userService) CreateUser(username, firstname, lastname, avatar, email streturn createdUser, nil}-func (s *userService) UpdateUser(id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error) {+func (s *userService) UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error) {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return nil, err+ }+ if err := s.access.RequireUserAccess(actor, id); err != nil {+ return nil, err+ }+dbUser, err := s.userRepo.GetByID(id)if err != nil || dbUser == nil {- return nil, errors.New("user not found")+ return nil, permissions.ErrNotFound}user := &models.User{@@ -126,7 +146,15 @@ func (s *userService) UpdateUser(id types.Snowflake, firstname, lastname, avatarreturn s.userRepo.Update(id, user)}-func (s *userService) UpdatePassword(id types.Snowflake, newPassword string) error {+func (s *userService) UpdatePassword(ctx context.Context, id types.Snowflake, newPassword string) error {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return err+ }+ if err := s.access.RequireUserAccess(actor, id); err != nil {+ return err+ }+if newPassword == "" {return errors.New("password is required")}@@ -139,7 +167,15 @@ func (s *userService) UpdatePassword(id types.Snowflake, newPassword string) errreturn s.userRepo.UpdatePassword(id, string(hash))}-func (s *userService) DeleteUser(id types.Snowflake, minioService MinioService) error {+func (s *userService) DeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) error {+ actor, err := actorFromContext(ctx)+ if err != nil {+ return err+ }+ if err := s.access.RequireUserAccess(actor, id); err != nil {+ return err+ }+if minioService != nil {if err := minioService.DeleteAllFromUser(id); err != nil {return errdiff --git a/backend/utils/README.md b/backend/utils/README.mddeleted file mode 100644index 5fdff353..00000000--- a/backend/utils/README.md+++ /dev/null@@ -1,123 +0,0 @@-# Utilities Layer--## Overview--The utilities layer provides reusable helper functions, constants, and tools used across the Alexandrie backend. These are stateless, pure functions that solve common problems.--## Available Utilities--### Snowflake ID Generator (`snowflake.go`)--Generates unique, distributed, time-ordered 64-bit IDs.--**Usage**:--```go-// Initialize (typically once at application start)-snowflake := utils.NewSnowflake(1) // 1 is the machine ID--// Generate IDs-id1 := snowflake.Generate() // e.g., 218914302160015361-id2 := snowflake.Generate() // e.g., 218914302160015362--// Extract timestamp from ID-timestamp := snowflake.GetTimestamp(id1)-```--**Benefits**:--- Unique across distributed systems-- Time-ordered (sortable)-- 64-bit integers (database-friendly)-- Very fast generation (>10k/sec per instance)--**Structure**:--```-64 bits total:-ββ 41 bits: Timestamp (milliseconds since epoch)-ββ 10 bits: Machine ID (supports 1024 machines)-ββ 12 bits: Sequence (4096 IDs per millisecond per machine)-```--### Context Helper (`context.go`)--Extracts user and request info from Gin context.--```go-// Get user ID from context-userID, permission, err := utils.GetUserContext(ctx)-if err != nil {- // Handle unauthenticated or error-}-```--### HTML Escape Utilities (`escape-html.go`)--Sanitize user input to prevent XSS attacks.--```go-// Escape HTML in user content-safeContent := utils.EscapeHTML(userInput)--// Example-input := `<script>alert('xss')</script>`-safe := utils.EscapeHTML(input)-// Result: "<script>alert('xss')</script>"-```--### Pointer Helpers (`pointers.go`)--Safely handle pointer conversions.--```go-// Convert value to pointer-strPtr := utils.StringPtr("hello")-intPtr := utils.IntPtr(42)-boolPtr := utils.BoolPtr(true)--// Convert pointer to value with default-str := utils.StringValue(strPtr, "default")-num := utils.IntValue(intPtr, 0)-flag := utils.BoolValue(boolPtr, false)--// Nil-safe operations-if utils.IsNil(ptr) {- // Handle nil case-}-```--## Best Practices--### Keep Utilities Pure--Utilities should be stateless and have no side effects:--```go-// Good: Pure function-func FormatTimestamp(ts int64) string {- return time.Unix(ts, 0).Format(time.RFC3339)-}--// Bad: Has side effects-func LogAndFormatTimestamp(ts int64) string {- log.Println("Formatting timestamp") // Side effect!- return time.Unix(ts, 0).Format(time.RFC3339)-}-```--### Use Utility Constants--Define magic numbers as constants:--```go-// Bad-if user.Role == 2 { // What does 2 mean?- // ...-}--// Good-if user.Role == utils.UserRoleAdmin {- // ...-}-```diff --git a/backend/utils/context.go b/backend/utils/context.goindex d1b5e254..71f64339 100644--- a/backend/utils/context.go+++ b/backend/utils/context.go@@ -27,30 +27,9 @@ func GetTargetId(ctx *gin.Context, param string) (types.Snowflake, error) {}func GetUserIdCtx(ctx *gin.Context) (types.Snowflake, error) {- userId, exists := ctx.Get("user_id")- if !exists {- return 0, errors.New("user ID not found in context")+ actor, ok := permissions.ActorFromContext(ctx.Request.Context())+ if !ok || actor.UserID == 0 {+ return 0, permissions.ErrUnauthorized}- id, ok := userId.(types.Snowflake)- if !ok {- return 0, errors.ErrUnsupported- }- return id, nil-}--// Return the user ID and user role from the context-func GetUserContext(ctx *gin.Context) (types.Snowflake, permissions.UserRole, error) {- userId, exists := ctx.Get("user_id")- if !exists {- return 0, 0, errors.New("user ID not found in context")- }- id, ok := userId.(types.Snowflake)- if !ok {- return 0, 0, errors.ErrUnsupported- }- role, exists := ctx.Get("user_role")- if !exists {- role = permissions.RoleNone- }- return id, role.(permissions.UserRole), nil+ return actor.UserID, nil}