Skip to content

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

New authorization service (end), remove old system

Smaug6739820103ea7ece
diff --git a/backend/controllers/nodes.controller.go b/backend/controllers/nodes.controller.go
index 14dca201..284cc41b 100644
--- a/backend/controllers/nodes.controller.go
+++ b/backend/controllers/nodes.controller.go
@@ -237,7 +237,7 @@ func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {
return http.StatusBadRequest, err
}
- if dbNode.UserId != connectedUserId && level < utils.OWNER {
+ if dbNode.UserId != connectedUserId && level < permissions.PermOwner {
// If the user is not owner or admin of the node he cannot change some fields
node.ParentId = dbNode.ParentId
node.UserId = dbNode.UserId
diff --git a/backend/controllers/ressources.controller.go b/backend/controllers/ressources.controller.go
index ba87a19a..4fc27363 100644
--- a/backend/controllers/ressources.controller.go
+++ b/backend/controllers/ressources.controller.go
@@ -3,6 +3,7 @@ package controllers
import (
"alexandrie/app"
"alexandrie/models"
+ "alexandrie/permissions"
"alexandrie/types"
"alexandrie/utils"
"bytes"
@@ -30,7 +31,8 @@ type RessourceController interface {
func NewRessourceController(app *app.App) RessourceController {
return &Controller{
- app: app,
+ app: app,
+ authorizer: permissions.NewAuthorizer(app.Services.Permissions),
}
}
@@ -214,23 +216,28 @@ func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
if ctr.app.MinioClient == nil {
return http.StatusInternalServerError, errors.New("minio client not initialized")
}
- id, err := utils.GetTargetId(c, c.Param("id"))
+ // Get connected user ID and role from context
+ connectedUserId, connectedUserRole, err := utils.GetUserContext(c)
if err != nil {
- return http.StatusBadRequest, errors.New("invalid id format")
+ return http.StatusUnauthorized, err
}
- userId, err := utils.GetUserIdCtx(c)
+
+ nodeTargetId, err := utils.GetTargetId(c, c.Param("id"))
if err != nil {
- return http.StatusUnauthorized, err
+ return http.StatusBadRequest, errors.New("invalid id format")
}
- node, err := ctr.app.Services.Nodes.GetNode(id)
+
+ node, err := ctr.app.Services.Nodes.GetNode(nodeTargetId)
if err != nil {
return http.StatusInternalServerError, "failed to get node"
}
if node == nil {
return http.StatusBadRequest, errors.New("node not found")
}
- if node.UserId != userId && !utils.CheckUserRequestPermission(c, utils.ADMINISTRATOR) {
- return http.StatusUnauthorized, errors.New("you are not authorized to delete this node")
+
+ // Check if the user has permission to delete the node
+ if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, node.UserId, connectedUserRole); !allowed || err != nil {
+ return http.StatusUnauthorized, err
}
prefix := fmt.Sprintf("%d/%d", node.UserId, node.Id)
@@ -251,9 +258,9 @@ func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
return http.StatusInternalServerError, fmt.Errorf("failed to delete object: %v", err)
}
}
- err = ctr.app.Services.Nodes.DeleteNode(id)
+ err = ctr.app.Services.Nodes.DeleteNode(nodeTargetId)
if err != nil {
return http.StatusInternalServerError, err
}
- return http.StatusOK, "File deleted successfully"
+ return http.StatusOK, "Ressource deleted successfully"
}
diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.go
index 5a606334..b552707c 100644
--- a/backend/controllers/users.controller.go
+++ b/backend/controllers/users.controller.go
@@ -3,6 +3,7 @@ package controllers
import (
"alexandrie/app"
"alexandrie/models"
+ "alexandrie/permissions"
"alexandrie/utils"
"errors"
"net/http"
@@ -24,7 +25,8 @@ type UserController interface {
func NewUserController(app *app.App) UserController {
return &Controller{
- app: app,
+ app: app,
+ authorizer: permissions.NewAuthorizer(app.Services.Permissions),
}
}
@@ -75,18 +77,30 @@ func (ctr *Controller) GetPublicUser(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) GetUserById(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
+ // Define targets and connected user
+ connectedUserId, connectedUserRole, err := utils.GetUserContext(c)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ // Target user ID from param
+ targetUserId, err := utils.GetTargetId(c, c.Param("userId"))
if err != nil {
return http.StatusBadRequest, err
}
- user, err := ctr.app.Services.User.GetUserById(id)
+
+ // Check permissions
+ if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {
+ return http.StatusUnauthorized, err
+ }
+ // Get user from database
+ user, err := ctr.app.Services.User.GetUserById(targetUserId)
if err != nil {
return http.StatusInternalServerError, err
}
if user == nil {
return http.StatusNotFound, errors.New("user not found")
}
- last_connection, err := ctr.app.Services.Log.GetLastConnection(id)
+ last_connection, err := ctr.app.Services.Log.GetLastConnection(targetUserId)
if err != nil {
last_connection = nil
}
@@ -155,33 +169,44 @@ func (ctr *Controller) CreateUser(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
+ // Define targets and connected user
+ connectedUserId, connectedUserRole, err := utils.GetUserContext(c)
if err != nil {
return http.StatusUnauthorized, err
}
+ // Target user ID from param
+ targetUserId, err := utils.GetTargetId(c, c.Param("userId"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+
+ // Check permissions
+ if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {
+ return http.StatusUnauthorized, err
+ }
+
var user models.User
if err := c.ShouldBind(&user); err != nil {
return http.StatusBadRequest, err
}
- dbUser, err := ctr.app.Services.User.GetUserById(id)
+ dbUser, err := ctr.app.Services.User.GetUserById(targetUserId)
if err != nil || dbUser == nil {
return http.StatusInternalServerError, err
}
// Only update provided fields
user = models.User{
- Id: id,
+ Id: targetUserId,
Username: dbUser.Username,
Firstname: utils.IfNotNilPointer(user.Firstname, dbUser.Firstname),
Lastname: utils.IfNotNilPointer(user.Lastname, dbUser.Lastname),
Avatar: utils.IfNotNilPointer(user.Avatar, dbUser.Avatar),
- Role: dbUser.Role,
Email: utils.IfNotNilValue(&user.Email, dbUser.Email),
CreatedTimestamp: dbUser.CreatedTimestamp,
UpdatedTimestamp: time.Now().UnixMilli(),
}
- updatedUser, err := ctr.app.Services.User.UpdateUser(id, &user)
+ updatedUser, err := ctr.app.Services.User.UpdateUser(targetUserId, &user)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -199,10 +224,21 @@ func (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
+ // Define targets and connected user
+ connectedUserId, connectedUserRole, err := utils.GetUserContext(c)
if err != nil {
return http.StatusUnauthorized, err
}
+ // Target user ID from param
+ targetUserId, err := utils.GetTargetId(c, c.Param("userId"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+
+ // Check permissions
+ 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"`
}
@@ -217,7 +253,7 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {
if err != nil {
return http.StatusInternalServerError, errors.New("failed to hash password")
}
- err = ctr.app.Services.User.UpdatePassword(id, string(hash))
+ err = ctr.app.Services.User.UpdatePassword(targetUserId, string(hash))
if err != nil {
return http.StatusInternalServerError, err
}
@@ -234,17 +270,28 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) DeleteUser(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR)
+ // Define targets and connected user
+ connectedUserId, connectedUserRole, err := utils.GetUserContext(c)
if err != nil {
return http.StatusUnauthorized, err
}
+ // Target user ID from param
+ targetUserId, err := utils.GetTargetId(c, c.Param("userId"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+
+ // Check permissions
+ if allowed, err := ctr.authorizer.CanAccessUser(connectedUserId, targetUserId, connectedUserRole); !allowed || err != nil {
+ return http.StatusUnauthorized, err
+ }
// Delete uploaded files
- err = ctr.app.Services.Minio.DeleteAllFromUser(id)
+ err = ctr.app.Services.Minio.DeleteAllFromUser(targetUserId)
if err != nil {
return http.StatusInternalServerError, err
}
- err = ctr.app.Services.User.DeleteUser(id)
+ err = ctr.app.Services.User.DeleteUser(targetUserId)
if err != nil {
return http.StatusInternalServerError, err
}
diff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.go
index 742ff407..2ffd8d0f 100644
--- a/backend/middlewares/authentification.go
+++ b/backend/middlewares/authentification.go
@@ -2,6 +2,7 @@ package middlewares
import (
"alexandrie/permissions"
+ "alexandrie/types"
"alexandrie/utils"
"net/http"
"os"
@@ -48,9 +49,9 @@ func Auth() gin.HandlerFunc {
c.Abort() // Stop further processing if unauthorized
return
}
- c.Set("user_id", user_id) // Set user ID in context
+ c.Set("user_id", types.Snowflake(user_id)) // Set user ID in context
c.Set("user_role", permissions.UserRole(user_role))
- c.Set("claims", claims)
+ //c.Set("claims", claims)
c.Next() // Proceed to the next handler if authorized
}
}
diff --git a/backend/permissions/constants.go b/backend/permissions/constants.go
index e09e9000..420df18e 100644
--- a/backend/permissions/constants.go
+++ b/backend/permissions/constants.go
@@ -14,11 +14,11 @@ const (
type NodePermissionLevel int
const (
- PermNone NodePermissionLevel = iota
- PermRead
- PermWrite
- PermAdmin
- PermOwner
+ PermNone NodePermissionLevel = iota // No access
+ PermRead // Read access
+ PermWrite // Write access
+ PermAdmin // Admin access
+ PermOwner // Full control, including managing permissions
)
// NodeAction define actions that can be performed on nodes
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index 8e3cc673..8b2d3f6a 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -108,8 +108,8 @@ func (s *Service) GetUserById(id types.Snowflake) (*models.User, error) {
}
func (s *Service) UpdateUser(id types.Snowflake, user *models.User) (*models.User, error) {
- _, err := s.db.Exec("UPDATE users SET username=?, firstname=?, lastname=?, role=?, avatar=?, email=?, updated_timestamp=? WHERE id=?",
- user.Username, user.Firstname, user.Lastname, user.Role, user.Avatar, user.Email, user.UpdatedTimestamp, id)
+ _, err := s.db.Exec("UPDATE users SET username=?, firstname=?, lastname=?, avatar=?, email=?, updated_timestamp=? WHERE id=?",
+ user.Username, user.Firstname, user.Lastname, user.Avatar, user.Email, user.UpdatedTimestamp, id)
if err != nil {
return nil, err
}
diff --git a/backend/utils/permissions.go b/backend/utils/permissions.go
index 72ed189b..ad3aa555 100644
--- a/backend/utils/permissions.go
+++ b/backend/utils/permissions.go
@@ -9,38 +9,6 @@ import (
"github.com/gin-gonic/gin"
)
-// We define user roles as bit flags to allow for easy combination and checking of permissions.
-
-const (
- ADMINISTRATOR = 1 << 1
- MANAGER = 1 << 2
- MODERATOR = 1 << 3
-)
-
-const (
- READ = 1
- WRITE = 2
- ADMIN = 3
- OWNER = 4
-)
-
-// CheckPermission checks if the user has the required permission.
-func CheckPermission(userRole, requiredRole permissions.UserRole) bool {
- return userRole&requiredRole == requiredRole
-}
-
-func CheckUserRequestPermission(ctx *gin.Context, requiredRole permissions.UserRole) bool {
- // Check if the user has the required permission
- role, exists := ctx.Get("user_role")
- if !exists {
- return false
- }
- if CheckPermission(role.(permissions.UserRole), requiredRole) {
- return true
- }
- return false
-}
-
func GetTargetId(ctx *gin.Context, param string) (types.Snowflake, error) {
if param == "" {
return 0, errors.New("parameter is empty")
@@ -61,11 +29,11 @@ func GetUserIdCtx(ctx *gin.Context) (types.Snowflake, error) {
if !exists {
return 0, errors.New("user ID not found in context")
}
- id, ok := userId.(uint64)
+ id, ok := userId.(types.Snowflake)
if !ok {
return 0, errors.ErrUnsupported
}
- return types.Snowflake(id), nil
+ return id, nil
}
// Return the user ID and user role from the context
@@ -74,44 +42,13 @@ func GetUserContext(ctx *gin.Context) (types.Snowflake, permissions.UserRole, er
if !exists {
return 0, 0, errors.New("user ID not found in context")
}
- id, ok := userId.(uint64)
+ id, ok := userId.(types.Snowflake)
if !ok {
return 0, 0, errors.ErrUnsupported
}
role, exists := ctx.Get("user_role")
if !exists {
- return 0, 0, errors.New("user role not found in context")
- }
- return types.Snowflake(id), role.(permissions.UserRole), nil
-}
-
-func SelfOrPermission(ctx *gin.Context, allowed permissions.UserRole) (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
-
- // --- 1. Get the target user ID
- targetUserId, err := GetTargetId(ctx, ctx.Param("userId"))
- if err != nil {
- return 0, err
- }
- // --- 2. Get the connected user ID
- connectedUserId, err := GetUserIdCtx(ctx)
- if err != nil {
- return 0, err
- }
- // --- 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 CheckPermission(role.(permissions.UserRole), allowed) {
- return targetUserId, nil
+ role = permissions.RoleNone
}
- return 0, errors.New("unauthorized")
+ return id, role.(permissions.UserRole), nil
}