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.

Add documentations for layers

Smaug673978b4b1fdbcdc
diff --git a/backend/README.md b/backend/README.md
new file mode 100644
index 00000000..ec96e7f2
--- /dev/null
+++ b/backend/README.md
@@ -0,0 +1,138 @@
+# Alexandrie Backend
+
+## Overview
+
+The Alexandrie backend is a REST API built with Go and the Gin web framework. It provides authentication, nodes management, permissions, and file storage capabilities with a layered architecture.
+
+## Quick Start
+
+```bash
+# Install dependencies
+go mod download
+
+# Copy environment file
+cp .env.example .env
+
+# Run database migrations
+go run migrations/*.go
+
+# Start the server
+go run main.go
+```
+
+The API will be available at `http://localhost:8201` (or your configured port).
+
+## Architecture Layers
+
+The backend follows a **clean layered architecture**:
+
+1. **Router** β†’ Routes HTTP requests to controllers
+2. **Middlewares** β†’ Authentication, logging, CORS
+3. **Controllers** β†’ Parse requests, call services, format responses
+4. **Services** β†’ Business logic and validation
+5. **Repositories** β†’ Database queries with prepared statements
+6. **Models** β†’ Data structures
+
+Each layer has a specific responsibility and communicates only with adjacent layers.
+
+## Configuration
+
+Key environment variables in `.env`:
+
+```env
+# Server
+BACKEND_PORT=8201
+FRONTEND_URL=http://localhost:3000
+
+# Database
+DATABASE_URL=user:password@tcp(localhost:3306)/alexandrie
+
+# JWT
+JWT_SECRET=your-secret-key
+JWT_ACCESS_EXPIRATION=15m
+JWT_REFRESH_EXPIRATION=7d
+
+# Object Storage (MinIO/S3) (optional)
+MINIO_ENDPOINT=localhost:9000
+MINIO_ACCESS_KEY=minioadmin
+MINIO_SECRET_KEY=minioadmin
+```
+
+## Starting Points
+
+### Adding a New Feature
+
+1. **Define the model** in `models/` (data structure)
+2. **Create repository** in `repositories/` (database queries)
+3. **Implement service** in `services/` (business logic)
+4. **Add controller** in `controllers/` (HTTP handlers)
+5. **Register routes** in `router/routes/`
+
+### Understanding Request Flow
+
+```
+HTTP Request
+ ↓
+router/router.go (route matching)
+ ↓
+middlewares/ (auth, logging)
+ ↓
+controllers/ (parse & validate)
+ ↓
+services/ (business logic)
+ ↓
+repositories/ (database)
+ ↓
+Response
+```
+
+### Code Entry Points
+
+- **`main.go`** - Application startup
+- **`app/app.go`** - App initialization (DB, services, repositories)
+- **`server/server.go`** - HTTP server setup
+- **`router/router.go`** - Route configuration
+
+## Common Tasks
+
+### Run the server
+
+```bash
+go run main.go
+```
+
+### Database migrations
+
+Migrations are in the `migrations/` folder. They are automatically run on startup.
+
+## Detailed Documentation
+
+Each layer has detailed documentation:
+
+- **[Controllers](./controllers/README.md)** - HTTP handlers and request validation
+- **[Services](./services/README.md)** - Business logic implementation
+- **[Repositories](./repositories/README.md)** - Database access patterns
+- **[Models](./models/README.md)** - Data structures and validation
+- **[Utils](./utils/README.md)** - Helper functions and utilities
+
+## Dependencies
+
+Key Go packages used:
+
+- **[gin-gonic/gin](https://github.com/gin-gonic/gin)** - Web framework
+- **[golang-jwt/jwt](https://github.com/golang-jwt/jwt)** - JWT authentication
+- **[go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)** - MySQL driver
+- **[minio/minio-go](https://github.com/minio/minio-go)** - S3-compatible storage
+- **[joho/godotenv](https://github.com/joho/godotenv)** - Environment variables
+
+## Contributing
+
+When contributing to the backend:
+
+1. Follow the layered architecture pattern
+2. Update relevant README files
+3. Use prepared statements in repositories
+4. Validate input in controllers
+5. Keep business logic in services
+
+See [CONTRIBUTING.md](../CONTRIBUTING.md) for full guidelines.
diff --git a/backend/controllers/README.md b/backend/controllers/README.md
new file mode 100644
index 00000000..6b892ac6
--- /dev/null
+++ b/backend/controllers/README.md
@@ -0,0 +1,228 @@
+# Controllers Layer
+
+## Overview
+
+Controllers handle HTTP requests and responses in the Alexandrie application. They act as the entry point for all API endpoints, validating input, calling appropriate services, and formatting responses.
+
+## Architecture
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ HTTP Request β”‚ ← Client sends request
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Middleware β”‚ ← Auth, CORS, Logging
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Controllers β”‚ ← Input validation & routing (This layer)
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Services β”‚ ← Business logic
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Repositories β”‚ ← Data access
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## Key Components
+
+### Base Controller (`index.go`)
+
+The foundation for all controllers, providing shared dependencies:
+
+```go
+type Controller struct {
+ app *app.App
+ authorizer permissions.Authorizer
+}
+```
+
+### Available Controllers
+
+- **`authentication.controller.go`** - User login, registration, token refresh
+- **`users.controller.go`** - User profile management, updates
+- **`nodes.controller.go`** - Document/note CRUD operations
+- **`permissions.controller.go`** - Access control management
+- **`ressources.controller.go`** - File upload and media handling
+
+## Usage Example
+
+### Controller Structure
+
+```go
+func (c *Controller) GetNodeById(ctx *fiber.Ctx) error {
+ // 1. Extract and validate input
+ nodeId, err := ctx.ParamsInt("id")
+ if err != nil {
+ return ctx.Status(400).JSON(fiber.Map{
+ "error": "Invalid node ID",
+ })
+ }
+
+ // 2. Call service layer
+ node, err := c.app.Services.Node.GetNodeById(uint64(nodeId))
+ if err != nil {
+ return ctx.Status(404).JSON(fiber.Map{
+ "error": "Node not found",
+ })
+ }
+
+ // 3. Return formatted response
+ return ctx.Status(200).JSON(node)
+}
+```
+
+### Error Handling Pattern
+
+Controllers should use consistent HTTP status codes:
+
+- **200** - Success
+- **201** - Created
+- **400** - Bad request (validation error)
+- **401** - Unauthorized
+- **403** - Forbidden
+- **404** - Not found
+- **409** - Conflict (duplicate resource)
+- **500** - Internal server error
+
+## Best Practices
+
+### Input Validation
+
+Always validate user input at the controller level:
+
+```go
+// Validate required fields
+if req.Username == "" || req.Password == "" {
+ return ctx.Status(400).JSON(fiber.Map{
+ "error": "Username and password required",
+ })
+}
+
+// Validate format
+if len(req.Username) < 3 || len(req.Username) > 25 {
+ return ctx.Status(400).JSON(fiber.Map{
+ "error": "Username must be 3-25 characters",
+ })
+}
+```
+
+### Request Body Parsing
+
+Use Fiber's built-in parser with error handling:
+
+```go
+var req CreateNodeRequest
+if err := ctx.BodyParser(&req); err != nil {
+ return ctx.Status(400).JSON(fiber.Map{
+ "error": "Invalid request body",
+ })
+}
+```
+
+### Authorization Checks
+
+Use the authorizer for permission checks:
+
+```go
+// Check if user can access the node
+if !c.authorizer.CanUserAccessNode(userId, nodeId, permission.Read) {
+ return ctx.Status(403).JSON(fiber.Map{
+ "error": "Access denied",
+ })
+}
+```
+
+## Common Issues
+
+### Issue: "Cannot parse request body"
+
+**Cause**: Incorrect Content-Type header or malformed JSON
+
+**Solution**: Ensure client sends `Content-Type: application/json` and valid JSON:
+
+```go
+// Add better error message
+if err := ctx.BodyParser(&req); err != nil {
+ return ctx.Status(400).JSON(fiber.Map{
+ "error": "Invalid JSON format",
+ "details": err.Error(),
+ })
+}
+```
+
+### Issue: Middleware not executing
+
+**Cause**: Route registered before middleware in router
+
+**Solution**: Check `router/` directory - middleware must be registered before routes:
+
+```go
+// Correct order
+app.Use(middlewares.AuthMiddleware)
+app.Get("/nodes", controller.GetNodes)
+```
+
+### Issue: Context deadline exceeded
+
+**Cause**: Long-running operations blocking the request
+
+**Solution**: Set appropriate timeouts and use async operations for heavy tasks:
+
+```go
+// Add timeout to context
+ctx.Context().SetTimeout(30 * time.Second)
+```
+
+## Testing Controllers
+
+Example test structure:
+
+```go
+func TestGetNodeById(t *testing.T) {
+ app := fiber.New()
+ controller := NewController(testApp)
+
+ app.Get("/nodes/:id", controller.GetNodeById)
+
+ req := httptest.NewRequest("GET", "/nodes/123", nil)
+ resp, err := app.Test(req)
+
+ assert.NoError(t, err)
+ assert.Equal(t, 200, resp.StatusCode)
+}
+```
+
+## Response Format
+
+Controllers should return consistent JSON responses:
+
+```go
+// Success response
+{
+ "data": { /* resource object */ },
+ "message": "Operation successful"
+}
+
+// Error response
+{
+ "error": "Error message",
+ "code": "ERROR_CODE"
+}
+
+// List response
+{
+ "data": [ /* array of resources */ ],
+ "total": 100,
+ "page": 1,
+ "pageSize": 20
+}
+```
diff --git a/backend/models/README.md b/backend/models/README.md
new file mode 100644
index 00000000..90c87886
--- /dev/null
+++ b/backend/models/README.md
@@ -0,0 +1,164 @@
+# Models Layer
+
+## Overview
+
+Models define the data structures used throughout the Alexandrie application. They represent database tables, API request/response formats, and business entities with their properties and relationships.
+
+## Architecture
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Database β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚ Maps to
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Models β”‚ ← Data structures (This layer)
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚ Used by
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Repositories β”‚
+β”‚ Services β”‚
+β”‚ Controllers β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## JSON Serialization
+
+### Excluding Fields from JSON
+
+Use `json:"-"` to hide sensitive data:
+
+```go
+type User struct {
+ Password string `json:"-"` // Never included in JSON
+ Email string `json:"email,omitempty"` // Omit if empty
+}
+```
+
+### Custom JSON Field Names
+
+```go
+type Node struct {
+ CreatedTimestamp int64 `json:"created_at"` // Maps to "created_at" in JSON
+ UpdatedTimestamp int64 `json:"updated_at"`
+}
+```
+
+## Database Tags
+
+Models use struct tags for database mapping:
+
+```go
+type User struct {
+ ID uint64 `json:"id" db:"id"`
+ Username string `json:"username" db:"username" validate:"required,min=3,max=25"`
+}
+```
+
+## Validation
+
+### Built-in Validation
+
+Use validation tags for automatic checks:
+
+```go
+type CreateUserRequest struct {
+ Username string `json:"username" validate:"required,min=3,max=25"`
+ Email string `json:"email" validate:"required,email"`
+ Password string `json:"password" validate:"required,min=8"`
+}
+
+// In controller/service
+if err := validator.Validate(request); err != nil {
+ return fmt.Errorf("validation error: %w", err)
+}
+```
+
+## Request/Response DTOs
+
+### Separate DTOs from Models
+
+Create specific types for API requests/responses:
+
+```go
+// Request DTO
+type CreateNodeRequest struct {
+ Name string `json:"name" validate:"required,max=50"`
+ ParentID uint64 `json:"parent_id"`
+ Role int `json:"role" validate:"required,min=1,max=4"`
+ Content string `json:"content"`
+}
+
+// Response DTO
+type NodeResponse struct {
+ ID uint64 `json:"id"`
+ Name string `json:"name"`
+ CreatedAt int64 `json:"created_at"`
+ Owner string `json:"owner"`
+}
+
+// Convert model to response
+func ToNodeResponse(node *Node, ownerName string) NodeResponse {
+ return NodeResponse{
+ ID: node.ID,
+ Name: node.Name,
+ CreatedAt: node.CreatedTimestamp,
+ Owner: ownerName,
+ }
+}
+```
+
+## Common Issues
+
+### Issue: "json: unsupported type" error
+
+**Cause**: Trying to serialize unsupported types (channels, functions)
+
+**Solution**: Use proper JSON-serializable types:
+
+```go
+// Wrong
+type Node struct {
+ Metadata chan string // Cannot serialize
+}
+
+// Correct
+type Node struct {
+ Metadata interface{} // Use json.RawMessage or map[string]interface{}
+}
+```
+
+### Issue: Circular reference during JSON serialization
+
+**Cause**: Model references itself or creates a cycle
+
+**Solution**: Use pointers and omit empty, or create response DTOs:
+
+```go
+// Problematic
+type Node struct {
+ Parent *Node
+ Children []Node // Causes infinite loop
+}
+
+// Better
+type Node struct {
+ ParentID uint64
+ // Load children separately when needed
+}
+```
+
+### Issue: Zero values being serialized
+
+**Cause**: Not using `omitempty` tag
+
+**Solution**: Add `omitempty` for optional fields:
+
+```go
+type Node struct {
+ ParentID uint64 `json:"parent_id,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+```
diff --git a/backend/services/README.md b/backend/services/README.md
new file mode 100644
index 00000000..fd171e33
--- /dev/null
+++ b/backend/services/README.md
@@ -0,0 +1,276 @@
+# Services Layer
+
+## Overview
+
+The services layer contains the business logic of the Alexandrie application. Services orchestrate operations between repositories, enforce business rules, and handle complex workflows that span multiple data entities.
+
+## Architecture
+
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Controllers β”‚ ← HTTP Request Handlers
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Services β”‚ ← Business Logic Layer (This layer)
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Repositories β”‚ ← Data Access Layer
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β–Ό
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ Database β”‚ ← MySQL
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+```
+
+## Key Components
+
+### Service Manager (`manager.go`)
+
+**Initialization:**
+
+```go
+serviceMgr, err := services.NewServiceManager(repos, snowflake, minioClient)
+if err != nil {
+ log.Fatal(err)
+}
+```
+
+### Available Services
+
+- **`auth.service.go`** - Authentication, login, registration, token management
+- **`user.service.go`** - User profile operations, validation, updates
+- **`node.service.go`** - Document/note business logic, hierarchy management
+- **`permission.service.go`** - Access control rules and authorization
+- **`session.service.go`** - User session lifecycle management
+- **`log.service.go`** - Activity and connection logging
+- **`minio.service.go`** - Object storage operations
+- **`ressource.service.go`** - File and media management
+
+## Usage Example
+
+### Service Implementation Pattern
+
+```go
+type NodeService interface {
+ GetNodeById(id uint64) (*models.Node, error)
+ CreateNode(node *models.Node) error
+ UpdateNode(node *models.Node) error
+ DeleteNode(id uint64) error
+}
+
+type nodeService struct {
+ nodeRepo repositories.NodeRepository
+ permissionRepo repositories.PermissionRepository
+ snowflake *utils.Snowflake
+}
+
+func (s *nodeService) CreateNode(node *models.Node) error {
+ // 1. Validate business rules
+ if err := s.validateNode(node); err != nil {
+ return fmt.Errorf("validation failed: %w", err)
+ }
+
+ // 2. Generate unique ID
+ node.ID = s.snowflake.Generate()
+
+ // 3. Perform repository operations
+ if err := s.nodeRepo.Create(node); err != nil {
+ return fmt.Errorf("failed to create node: %w", err)
+ }
+
+ // 4. Handle related operations (permissions, logs, etc.)
+ if err := s.createDefaultPermissions(node); err != nil {
+ return fmt.Errorf("failed to set permissions: %w", err)
+ }
+
+ return nil
+}
+```
+
+### Cross-repos Communication
+
+Services can depend on other repos for complex operations:
+
+```go
+// Permission service uses node service for validation
+func (s *permissionService) GrantAccess(nodeId, userId uint64, level int) error {
+ // Verify node exists
+ node, err := s.nodeRepo.GetByID(nodeId)
+ if err != nil {
+ return fmt.Errorf("node not found: %w", err)
+ }
+
+ // Verify user exists
+ user, err := s.userRepo.GetByID(userId)
+ if err != nil {
+ return fmt.Errorf("user not found: %w", err)
+ }
+
+ // Create permission
+ permission := &models.Permission{
+ NodeID: nodeId,
+ UserID: userId,
+ Level: level,
+ }
+
+ return s.permissionRepo.Create(permission)
+}
+```
+
+## Best Practices
+
+### Business Rule Validation
+
+Services enforce all business rules before data persistence:
+
+```go
+func (s *nodeService) validateNode(node *models.Node) error {
+ // Check required fields
+ if node.Name == "" {
+ return errors.New("node name is required")
+ }
+
+ // Validate name length
+ if len(node.Name) < 1 || len(node.Name) > 50 {
+ return errors.New("node name must be 1-50 characters")
+ }
+
+ // Check parent exists if specified
+ if node.ParentID != 0 {
+ _, err := s.nodeRepo.GetByID(node.ParentID)
+ if err != nil {
+ return errors.New("parent node not found")
+ }
+ }
+
+ return nil
+}
+```
+
+### Error Wrapping
+
+Provide context when wrapping errors:
+
+```go
+if err := s.nodeRepo.Create(node); err != nil {
+ return fmt.Errorf("failed to create node '%s': %w", node.Name, err)
+}
+```
+
+### Transaction Management
+
+For operations spanning multiple repositories, use transactions:
+
+```go
+func (s *nodeService) MoveNode(nodeId, newParentId uint64) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+
+ // Update node parent
+ if err := s.nodeRepo.UpdateParent(tx, nodeId, newParentId); err != nil {
+ return err
+ }
+
+ // Update hierarchy metadata
+ if err := s.updateHierarchy(tx, nodeId); err != nil {
+ return err
+ }
+
+ return tx.Commit()
+}
+```
+
+## Common Patterns
+
+### ID Generation
+
+Use Snowflake for distributed unique IDs:
+
+```go
+func (s *nodeService) CreateNode(node *models.Node) error {
+ node.ID = s.snowflake.Generate()
+ node.CreatedTimestamp = time.Now().Unix()
+ node.UpdatedTimestamp = time.Now().Unix()
+
+ return s.nodeRepo.Create(node)
+}
+```
+
+## Common Issues
+
+### Issue: Circular dependency between services
+
+**Cause**: Service A imports Service B, which imports Service A
+
+**Solution**: Extract shared logic to a utility package or use interfaces:
+
+```go
+// Instead of importing the service, define an interface
+type NodeValidator interface {
+ Exists(id uint64) bool
+}
+
+// Pass interface in constructor
+func NewPermissionService(nodeValidator NodeValidator) *permissionService {
+ return &permissionService{validator: nodeValidator}
+}
+```
+
+### Issue: Service grows too large
+
+**Cause**: Single service handling too many responsibilities
+
+**Solution**: Split into smaller, focused services (for future refactoring):
+
+```go
+// Instead of one large NodeService, split into:
+- NodeService // Basic CRUD
+- NodeHierarchyService // Parent/child operations
+- NodeSearchService // Search and filtering
+- NodeExportService // Export to PDF, Markdown, etc.
+```
+
+### Issue: Race conditions in concurrent operations
+
+**Cause**: Multiple goroutines modifying shared state
+
+**Solution**: Use proper locking or atomic operations:
+
+```go
+import "sync"
+
+type nodeService struct {
+ mu sync.RWMutex
+ cache map[uint64]*models.Node
+}
+
+func (s *nodeService) GetFromCache(id uint64) *models.Node {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.cache[id]
+}
+```
+
+## Service Initialization
+
+Services are initialized through the ServiceManager in the main application:
+
+```go
+// In main.go or app initialization
+app, err := app.InitApp(config)
+if err != nil {
+ log.Fatal(err)
+}
+
+// Access services through app
+user, err := app.Services.User.GetUserById(userId)
+node, err := app.Services.Node.GetNodeById(nodeId)
+```
diff --git a/backend/utils/README.md b/backend/utils/README.md
new file mode 100644
index 00000000..e5c9f72a
--- /dev/null
+++ b/backend/utils/README.md
@@ -0,0 +1,141 @@
+# 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: "&lt;script&gt;alert('xss')&lt;/script&gt;"
+```
+
+### Domain Utilities (`domains.go`)
+
+Manage application domains and environment variables.
+
+SetDomainEnv initializes DOMAIN_CLIENT and COOKIE_DOMAIN environment variables
+based on FRONTEND_URL (if defined).
+If FRONTEND_URL is not set, the function does nothing.
+
+**Examples:**
+
+FRONTEND_URL=https://alexandrie-hub.fr
+-> DOMAIN_CLIENT=https://alexandrie-hub.fr
+-> COOKIE_DOMAIN=alexandrie-hub.fr
+
+FRONTEND_URL=http://localhost:8200
+-> DOMAIN_CLIENT=http://localhost:8200
+-> COOKIE_DOMAIN=localhost
+
+### 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/permissions.go b/backend/utils/context.go
similarity index 94%
rename from backend/utils/permissions.go
rename to backend/utils/context.go
index ad3aa555..d1b5e254 100644
--- a/backend/utils/permissions.go
+++ b/backend/utils/context.go
@@ -1,5 +1,7 @@
package utils
+// Utility functions to extract information from the Gin context
+
import (
"alexandrie/permissions"
"alexandrie/types"
diff --git a/backend/utils/domains.go b/backend/utils/domains.go
index b4a2f1d5..cdb06ca6 100644
--- a/backend/utils/domains.go
+++ b/backend/utils/domains.go
@@ -1,5 +1,7 @@
package utils
+// Utility functions for domain and environment variable management
+
import (
"fmt"
"net/url"
diff --git a/backend/utils/escape-html.go b/backend/utils/escape-html.go
index a7e57e9f..c2b20329 100644
--- a/backend/utils/escape-html.go
+++ b/backend/utils/escape-html.go
@@ -1,5 +1,7 @@
package utils
+// Utility functions for HTML escaping and sanitization to prevent XSS
+
import (
"github.com/microcosm-cc/bluemonday"
)
diff --git a/backend/utils/pointers.go b/backend/utils/pointers.go
index 3f30d901..2c7dfa8a 100644
--- a/backend/utils/pointers.go
+++ b/backend/utils/pointers.go
@@ -1,5 +1,7 @@
package utils
+// Utility functions for pointer handling
+
func StringValue(s *string) string {
if s == nil {
return ""
diff --git a/backend/utils/snowflake.go b/backend/utils/snowflake.go
index dd70852b..b4b03f68 100644
--- a/backend/utils/snowflake.go
+++ b/backend/utils/snowflake.go
@@ -1,5 +1,7 @@
package utils
+// Utility functions for Snowflake ID generation and management
+
import (
"alexandrie/types"
"os"
diff --git a/frontend/README.md b/frontend/README.md
index f5db2a2d..ac24a469 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -1,75 +1,123 @@
-# Nuxt 3 Minimal Starter
+# Frontend - Alexandrie
-Look at the [Nuxt 3 documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
+## Overview
-## Setup
+The Alexandrie frontend is a Vue 3 application built with Nuxt 4. It features a component-based architecture, state management with Pinia, and a rich editing experience.
-Make sure to install the dependencies:
+## Technology Stack
-```bash
-# npm
-npm install
-
-# pnpm
-pnpm install
+- **Framework**: Nuxt 4 (Vue 3)
+- **State Management**: Pinia
+- **Editor**: CodeMirror 6
+- **Markdown**: markdown-it with custom extensions
+- **Styling**: SCSS with custom design system
+- **Build Tool**: Vite
+- **PWA**: Offline support with @vite-pwa/nuxt
-# yarn
-yarn install
+## Architecture
-# bun
-bun install
+```
+β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+β”‚ User Interface β”‚
+β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
+ β”‚ Pages β”‚ ← Route components
+ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
+ β”‚ Components β”‚ ← Reusable UI elements
+ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ β”‚ Composables β”‚ ← Business logic & API calls
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ β”‚ Pinia Stores β”‚ ← State management
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ β”‚
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ β”‚ Backend API β”‚ ← REST API
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
-## Development Server
+## Directory Structure
-Start the development server on `http://localhost:3000`:
+### `/app/components`
-```bash
-# npm
-npm run dev
+Reusable Vue components organized by feature:
-# pnpm
-pnpm run dev
+**Base Components**:
-# yarn
-yarn dev
+- `AppX.vue` - Generic UI elements: (buttons, inputs, modals, etc.)
+- `Folder/` - Folder represent a single component (for big components)
+- `Other.vue` - Misc reusable components
-# bun
-bun run dev
-```
+_Sometimes components are stored in `pages/<page>/_components/` if they are only used by that page._
-## Production
+### `/app/composables`
-Build the application for production:
+Reusable composition functions for shared logic:
-```bash
-# npm
-npm run build
+- **`useNotifications.ts`** - Toast notifications system
+- **`useContextMenu.ts`** - Right-click context menus
+- **`useNodesTree.ts`** - Tree structure operations on nodes
+- **`user.ts`** - User authentication state
+- **`Preferences.ts`** - User preferences management
+- **`utils.ts`** - Helper functions
-# pnpm
-pnpm run build
+### `/app/stores`
-# yarn
-yarn build
+Pinia stores for application state:
-# bun
-bun run build
-```
+- **`user.store.ts`** - User authentication and profile
+- **`nodes.store.ts`** - Documents and categories management
+- **`resources.store.ts`** - File uploads and media
+- **`admin.store.ts`** - Admin operations
+
+### `/app/middleware`
+
+Route middleware for navigation guards:
-Locally preview production build:
+## API Integration
+
+API calls are centralized in `stores/_utils.ts` using the Fetch API with error handling and authentication tokens (also refresh token implementation).
+
+## Development Commands
```bash
-# npm
+# Install dependencies
+npm install
+
+# Development server (http://localhost:3000)
+npm run dev
+
+# Development with host access (for mobile testing)
+npm run dev:host
+
+# Build for production
+npm run build
+
+# Preview production build
npm run preview
-# pnpm
-pnpm run preview
+# Lint code
+npm run lint
-# yarn
-yarn preview
+# Lint and auto-fix
+npm run lint:fix
-# bun
-bun run preview
+# Lint CSS/SCSS
+npm run lint:css
```
-Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
+## Environment Configuration
+
+Create `.env` file:
+
+```env
+# API Configuration
+NUXT_PUBLIC_BASE_API=http://localhost:8201
+NUXT_PUBLIC_BASE_CDN=http://localhost:9000/alexandrie
+```