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.

chore: clean backend comments, files and old code

Smaug6739a2331fd75bc6
diff --git a/backend/README.md b/backend/README.md
index ec96e7f2..9836aed1 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -2,7 +2,7 @@
## 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.
+The Alexandrie backend is a REST API built with Go and the Gin web framework. It provides authentication, nodes management, permissions, and file storage features with a layered architecture.
## Quick Start
@@ -14,7 +14,7 @@ go mod download
cp .env.example .env
# Run database migrations
-go run migrations/*.go
+go run app/migrations/*.go
# Start the server
go run main.go
@@ -22,42 +22,6 @@ 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
@@ -86,13 +50,6 @@ 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
@@ -103,36 +60,15 @@ 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
+Migrations are in the `app/migrations/` folder. They are automatically run on startup.
## 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
+1. Use prepared statements in repositories
+1. Validate input in controllers
+1. Keep business logic in services
See [CONTRIBUTING.md](../CONTRIBUTING.md) for full guidelines.
diff --git a/backend/app/app.go b/backend/app/app.go
index ea9e57fe..5b09fb6e 100644
--- a/backend/app/app.go
+++ b/backend/app/app.go
@@ -54,7 +54,6 @@ func InitApp(config Config) *App {
// Run database migrations / schema creation
Migrate(&config)
- // Initialize repository manager
repoManager, err := repositories.NewRepositoryManager(app.DB)
if err != nil {
log.Fatalf("Failed to initialize repository manager: %v", err)
@@ -62,7 +61,6 @@ func InitApp(config Config) *App {
app.Repos = repoManager
- // Initialize service manager
resourceConfig := services.ResourceConfig{
MaxUploadsSize: config.Cdn.MaxUploadsSize,
SupportedTypes: config.Cdn.SupportedTypes,
diff --git a/backend/app/database.go b/backend/app/database.go
index fe762f74..ede08f41 100644
--- a/backend/app/database.go
+++ b/backend/app/database.go
@@ -13,7 +13,6 @@ func DBConnection(config Config, multiStatements bool) *sqlx.DB {
User := os.Getenv("DATABASE_USER")
Password := os.Getenv("DATABASE_PASSWORD")
- // Use environment variables for host/port/database if set, otherwise fall back to config
Host := os.Getenv("DATABASE_HOST")
if Host == "" {
Host = config.Database.Host
diff --git a/backend/app/minio.go b/backend/app/minio.go
index ea610a47..30dff08f 100644
--- a/backend/app/minio.go
+++ b/backend/app/minio.go
@@ -30,10 +30,7 @@ func MinioConnection() (*minio.Client, *minio.Client, error) {
return nil, nil, fmt.Errorf("MINIO NOT CONFIGURED")
}
- // ---------------------------------------------------------------------
// TLS configuration
- // ---------------------------------------------------------------------
-
rootCAs, err := x509.SystemCertPool()
if err != nil {
rootCAs = x509.NewCertPool()
@@ -70,10 +67,7 @@ func MinioConnection() (*minio.Client, *minio.Client, error) {
TLSClientConfig: publicTLSConfig,
}
- // ---------------------------------------------------------------------
// Internal MinIO client
- // ---------------------------------------------------------------------
-
isSecure := true
if os.Getenv("MINIO_SECURE") != "" && os.Getenv("MINIO_SECURE") != "true" {
isSecure = false
@@ -91,10 +85,7 @@ func MinioConnection() (*minio.Client, *minio.Client, error) {
os.Exit(1)
}
- // ---------------------------------------------------------------------
// Signer client (public URLs / CDN)
- // ---------------------------------------------------------------------
-
publicURL, err := url.Parse(publicEndpoint)
if err != nil {
logger.Error("s3", "CONFIG: MINIO_PUBLIC_URL is not a valid URL")
@@ -115,10 +106,7 @@ func MinioConnection() (*minio.Client, *minio.Client, error) {
os.Exit(1)
}
- // ---------------------------------------------------------------------
// Buckets setup
- // ---------------------------------------------------------------------
-
bucketName := os.Getenv("MINIO_BUCKET")
setupPublicBucket(ctx, minioClient, bucketName)
@@ -128,7 +116,6 @@ func MinioConnection() (*minio.Client, *minio.Client, error) {
return minioClient, signerClient, nil
}
-// setupPublicBucket creates and configures the main public bucket
func setupPublicBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {
err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
if err != nil {
@@ -164,7 +151,6 @@ func setupPublicBucket(ctx context.Context, minioClient *minio.Client, bucketNam
logger.Success("s3", "Successfully set public bucket policy for "+bucketName)
}
-// setupPrivateBackupBucket creates and configures the private backup bucket
func setupPrivateBackupBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {
err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
if err != nil {
@@ -179,9 +165,6 @@ func setupPrivateBackupBucket(ctx context.Context, minioClient *minio.Client, bu
logger.Success("s3", "Successfully created private backup bucket: "+bucketName)
}
- // No public policy - bucket remains private
- // Backups are only accessible via presigned URLs
-
// Configure lifecycle rule to auto-delete backup files after 1 day
lifecycleConfig := lifecycle.NewConfiguration()
lifecycleConfig.Rules = []lifecycle.Rule{
@@ -189,7 +172,7 @@ func setupPrivateBackupBucket(ctx context.Context, minioClient *minio.Client, bu
ID: "auto-delete-backups",
Status: "Enabled",
RuleFilter: lifecycle.Filter{
- Prefix: "", // Apply to all objects in the bucket
+ Prefix: "",
},
Expiration: lifecycle.Expiration{
Days: 1,
diff --git a/backend/controllers/README.md b/backend/controllers/README.md
deleted file mode 100644
index e8f818ef..00000000
--- a/backend/controllers/README.md
+++ /dev/null
@@ -1,228 +0,0 @@
-# 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
-- **`resources.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/main.go b/backend/main.go
index 48eb2dfd..0e60b314 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -33,7 +33,7 @@ func main() {
}
func loadEnv() {
- _ = godotenv.Load() // facultatif : pas d’erreur si absent
+ _ = godotenv.Load()
port := os.Getenv("BACKEND_PORT")
if port == "" {
diff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.go
index 5f50d772..f21133db 100644
--- a/backend/middlewares/authentification.go
+++ b/backend/middlewares/authentification.go
@@ -22,13 +22,12 @@ func Auth() gin.HandlerFunc {
tokenString, err := c.Cookie("Authorization")
if err != nil {
c.JSON(http.StatusUnauthorized, utils.Error("Bad access token."))
- c.Abort() // Stop further processing if unauthorized
+ c.Abort()
return
}
- // Parse the token
claims := AuthClaims{}
- token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
+ token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, http.ErrAbortHandler
}
@@ -37,26 +36,25 @@ func Auth() gin.HandlerFunc {
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, utils.Error("Bad access token."))
- c.Abort() // Stop further processing if unauthorized
+ c.Abort()
return
}
- // Set the token claims to the context
user_id, err := strconv.ParseUint(claims.Subject, 10, 64)
if err != nil {
c.JSON(http.StatusUnauthorized, utils.Error("Invalid user ID"))
- c.Abort() // Stop further processing if unauthorized
+ c.Abort()
return
}
user_role, err := strconv.Atoi(claims.Role)
if err != nil {
c.JSON(http.StatusUnauthorized, utils.Error("Invalid user role"))
- c.Abort() // Stop further processing if unauthorized
+ c.Abort()
return
}
- c.Set("user_id", types.Snowflake(user_id)) // Set user ID in context
+ c.Set("user_id", types.Snowflake(user_id))
c.Set("user_role", permissions.UserRole(user_role))
//c.Set("claims", claims)
- c.Next() // Proceed to the next handler if authorized
+ c.Next()
}
}
diff --git a/backend/models/README.md b/backend/models/README.md
index 90c87886..3863d86d 100644
--- a/backend/models/README.md
+++ b/backend/models/README.md
@@ -126,7 +126,7 @@ type Node struct {
// Correct
type Node struct {
- Metadata interface{} // Use json.RawMessage or map[string]interface{}
+ Metadata any // Use json.RawMessage or map[string]any
}
```
diff --git a/backend/models/node.model.go b/backend/models/node.model.go
index a4202359..b85ee11b 100644
--- a/backend/models/node.model.go
+++ b/backend/models/node.model.go
@@ -3,7 +3,6 @@ package models
import "alexandrie/types"
type Node struct {
- // Node
Id types.Snowflake `json:"id" form:"id" binding:"omitempty" db:"id"`
UserId types.Snowflake `json:"user_id" form:"user_id" binding:"omitempty" db:"user_id"`
ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty" db:"parent_id"`
diff --git a/backend/models/oidc_provider.model.go b/backend/models/oidc_provider.model.go
index 22053ff4..ba8b2850 100644
--- a/backend/models/oidc_provider.model.go
+++ b/backend/models/oidc_provider.model.go
@@ -2,7 +2,6 @@ package models
import "alexandrie/types"
-// UserOIDCProvider represents a link between a user and an external OIDC provider
type UserOIDCProvider struct {
Id types.Snowflake `json:"id" db:"id"`
UserId types.Snowflake `json:"user_id" db:"user_id"`
diff --git a/backend/oidc/config.go b/backend/oidc/config.go
index 6345e904..32dad999 100644
--- a/backend/oidc/config.go
+++ b/backend/oidc/config.go
@@ -14,7 +14,6 @@ import (
"alexandrie/pkg/logger"
)
-// Provider represents an OIDC provider configuration
type Provider struct {
Name string `json:"name"`
ConfigURL string `json:"config_url"`
@@ -29,13 +28,11 @@ type Provider struct {
Scopes []string `json:"scopes,omitempty"` // Minimal: openid - optional: profile, email
}
-// PublicProvider is the public-facing provider info (without secrets)
type PublicProvider struct {
Name string `json:"name"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
}
-// OIDCDiscovery represents the OpenID Connect discovery document
type OIDCDiscovery struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
@@ -45,7 +42,6 @@ type OIDCDiscovery struct {
ScopesSupported []string `json:"scopes_supported"`
}
-// TokenResponse represents the OIDC token response
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
@@ -55,7 +51,6 @@ type TokenResponse struct {
Scope string `json:"scope,omitempty"`
}
-// UserInfo represents the OIDC userinfo response
type UserInfo struct {
Sub string `json:"sub"`
Email *string `json:"email"`
@@ -67,7 +62,6 @@ type UserInfo struct {
Picture *string `json:"picture"`
}
-// Manager manages multiple OIDC providers
type Manager struct {
providers map[string]*Provider
mu sync.RWMutex
@@ -79,7 +73,6 @@ var (
once sync.Once
)
-// GetManager returns the global OIDC manager instance
func GetManager() *Manager {
once.Do(func() {
globalManager = &Manager{
@@ -93,11 +86,6 @@ func GetManager() *Manager {
return globalManager
}
-// loadFromEnv loads OIDC providers from environment variables
-// Supports multiple providers via indexed env vars:
-//
-// OIDC_1_CONFIG_URL, OIDC_1_CLIENT_ID, OIDC_1_CLIENT_SECRET, OIDC_1_PROVIDER_NAME
-// OIDC_2_CONFIG_URL, OIDC_2_CLIENT_ID, OIDC_2_CLIENT_SECRET, OIDC_2_PROVIDER_NAME
func (m *Manager) loadFromEnv() {
// Try indexed providers (OIDC_1_*, OIDC_2_*, etc.)
@@ -130,7 +118,6 @@ func (m *Manager) loadFromEnv() {
}
}
-// AddProvider adds a new OIDC provider and discovers its endpoints
func (m *Manager) AddProvider(provider *Provider) error {
if provider.ConfigURL == "" {
return fmt.Errorf("provider config URL is required")
@@ -142,10 +129,8 @@ func (m *Manager) AddProvider(provider *Provider) error {
return fmt.Errorf("provider client secret is required")
}
- // Normalize provider name to lowercase
- providerName := strings.ToLower(provider.Name)
+ providerName := strings.ToLower(provider.Name) // To normalize provider names
- // Discover OIDC endpoints
discovery, err := m.discoverEndpoints(provider.ConfigURL)
if err != nil {
return fmt.Errorf("failed to discover OIDC endpoints: %w", err)
@@ -174,7 +159,6 @@ func (m *Manager) AddProvider(provider *Provider) error {
return nil
}
-// discoverEndpoints fetches the OIDC discovery document
func (m *Manager) discoverEndpoints(configURL string) (*OIDCDiscovery, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -202,7 +186,6 @@ func (m *Manager) discoverEndpoints(configURL string) (*OIDCDiscovery, error) {
return &discovery, nil
}
-// GetProvider returns a provider by name
func (m *Manager) GetProvider(name string) (*Provider, error) {
m.mu.RLock()
defer m.mu.RUnlock()
@@ -214,7 +197,6 @@ func (m *Manager) GetProvider(name string) (*Provider, error) {
return provider, nil
}
-// GetProviders returns all configured providers (public info only)
func (m *Manager) GetProviders() []PublicProvider {
m.mu.RLock()
defer m.mu.RUnlock()
@@ -229,14 +211,12 @@ func (m *Manager) GetProviders() []PublicProvider {
return providers
}
-// HasProviders returns true if at least one OIDC provider is configured
func (m *Manager) HasProviders() bool {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.providers) > 0
}
-// IsEnabled returns true if OIDC is enabled (at least one provider configured)
func IsEnabled() bool {
return GetManager().HasProviders()
}
diff --git a/backend/permissions/service.go b/backend/permissions/service.go
index 70763891..a1e2c30e 100644
--- a/backend/permissions/service.go
+++ b/backend/permissions/service.go
@@ -21,7 +21,6 @@ func NewAuthorizer(permRepo repositories.PermissionRepository) Authorizer {
return &DefaultAuthorizer{permRepo: permRepo}
}
-// Check access to a node resource
func (a *DefaultAuthorizer) CanAccessNode(userID types.Snowflake, userRole UserRole, node *models.Node, action NodeAction) (bool, NodePermissionLevel, error) {
// Case 1: Owner of the node
if userID == node.UserId {
@@ -39,13 +38,11 @@ func (a *DefaultAuthorizer) CanAccessNode(userID types.Snowflake, userRole UserR
return false, PermNone, errors.New("unauthorized")
}
-// Check access to a user resource
func (a *DefaultAuthorizer) CanAccessUser(connectedID, targetID types.Snowflake, userRole UserRole) (bool, error) {
if connectedID == targetID {
return true, nil
}
- // Here we need to check the global role from the context (via middleware or db)
if a.IsAppAdmin(userRole) {
return true, nil
}
diff --git a/backend/pkg/logger/logger.go b/backend/pkg/logger/logger.go
index fff55541..77a50956 100644
--- a/backend/pkg/logger/logger.go
+++ b/backend/pkg/logger/logger.go
@@ -43,7 +43,6 @@ func Success(title, msg string) {
baseLogger.Println(format(title+" |", green, msg))
}
-// Optionnel : activer/dΓ©sactiver les couleurs globalement
func UseColor(b bool) {
useColor = b
}
diff --git a/backend/pkg/snowflake/snowflake.go b/backend/pkg/snowflake/snowflake.go
index 25e9d8a8..47566ecb 100644
--- a/backend/pkg/snowflake/snowflake.go
+++ b/backend/pkg/snowflake/snowflake.go
@@ -1,7 +1,5 @@
package snowflake
-// Utility functions for Snowflake ID generation and management
-
import (
"alexandrie/types"
"os"
@@ -30,7 +28,6 @@ type Snowflake struct {
mutex sync.Mutex
}
-// NewSnowflake creates a new Snowflake generator with automatically determined worker and process IDs
func NewSnowflake(epoch int64) *Snowflake {
workerID := int64(os.Getpid() & maxWorkerID)
processID := int64(os.Getppid() & maxProcessID)
@@ -43,7 +40,6 @@ func NewSnowflake(epoch int64) *Snowflake {
}
}
-// Generate creates a new unique snowflake ID
func (s *Snowflake) Generate() types.Snowflake {
timestamp := time.Now().UnixMilli()
s.mutex.Lock()
@@ -67,7 +63,6 @@ func (s *Snowflake) Generate() types.Snowflake {
s.increment)
}
-// Deconstruct splits a snowflake ID into its components
func (s *Snowflake) Deconstruct(id int64) map[string]int64 {
return map[string]int64{
"id": id,
diff --git a/backend/repositories/README.md b/backend/repositories/README.md
deleted file mode 100644
index 0824895a..00000000
--- a/backend/repositories/README.md
+++ /dev/null
@@ -1,286 +0,0 @@
-# Repository Pattern Implementation
-
-## Overview
-
-This directory contains the repository layer implementation for the Alexandrie application. The repository pattern provides a clean abstraction between the business logic (services) and data access layer (database), with optimized prepared statements for better performance and security.
-
-## Architecture
-
-```
-β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
-β”‚ Controllers β”‚ ← HTTP Request Handlers
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
- β”‚
- β–Ό
-β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
-β”‚ Services β”‚ ← Business Logic Layer
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
- β”‚
- β–Ό
-β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
-β”‚ Repositories β”‚ ← Data Access Layer (This layer)
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
- β”‚
- β–Ό
-β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
-β”‚ Database β”‚ ← MySQL
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
-```
-
-## Key Components
-
-### 1. Repository Manager (`manager.go`)
-
-The central component that manages all repositories and their prepared statements:
-
-- **Lifecycle Management**: Initializes and closes all prepared statements
-- **Statement Caching**: Reuses prepared statements across requests
-- **Thread-Safe**: Uses mutex for concurrent access
-- **Resource Cleanup**: Properly closes all statements on shutdown
-
-```go
-// Initialize repository manager
-repoMgr, err := repositories.NewRepositoryManager(db)
-
-// Get prepared statement count for monitoring
-count := repoMgr.GetStatementCount()
-
-// Graceful shutdown
-repoMgr.Close()
-```
-
-### 2. Repository Interfaces (`interfaces.go`)
-
-Defines contracts for all data access operations:
-
-- `UserRepository` - User data operations
-- `NodeRepository` - Note/document operations
-- `SessionRepository` - Authentication session management
-- `PermissionRepository` - Access control operations
-- `LogRepository` - Connection and activity logging
-
-### 3. Repository Implementations
-
-Each repository implementation provides:
-
-- **Prepared Statements**: All queries are prepared once at startup
-- **Type Safety**: Strong typing with Go models
-- **Error Handling**: Consistent error wrapping with context
-- **Performance**: Optimized queries with proper indexing support
-
-## Usage Example
-
-### Application Initialization
-
-```go
-// Initialize with repository pattern
-app, err := app.InitApp(config)
-if err != nil {
- log.Fatal(err)
-}
-defer app.Close() // Properly cleanup prepared statements
-
-// Services now use optimized repositories
-user, err := app.Services.User.GetUserById(userId)
-```
-
-## Database Indexing
-
-For optimal performance with prepared statements, ensure these indexes exist:
-
-```sql
--- User table
-CREATE INDEX idx_users_username ON users(username);
-CREATE INDEX idx_users_email ON users(email);
-
--- Nodes table
-CREATE INDEX idx_nodes_user_id ON nodes(user_id);
-CREATE INDEX idx_nodes_parent_id ON nodes(parent_id);
-CREATE INDEX idx_nodes_accessibility ON nodes(accessibility);
-CREATE INDEX idx_nodes_created ON nodes(created_timestamp);
-CREATE INDEX idx_nodes_updated ON nodes(updated_timestamp);
-
--- Permissions table
-CREATE INDEX idx_permissions_node_id ON permissions(node_id);
-CREATE INDEX idx_permissions_user_id ON permissions(user_id);
-CREATE INDEX idx_permissions_node_user ON permissions(node_id, user_id);
-
-```
-
-## Testing
-
-Example test structure for repositories:
-
-```go
-func TestUserRepository_GetByID(t *testing.T) {
- // Setup test database
- db := setupTestDB()
- defer db.Close()
-
- // Initialize repository manager
- mgr, err := repositories.NewRepositoryManager(db)
- require.NoError(t, err)
- defer mgr.Close()
-
- // Test the repository
- user, err := mgr.User.GetByID(testUserID)
- assert.NoError(t, err)
- assert.Equal(t, "testuser", user.Username)
-}
-```
-
-## Troubleshooting
-
-### Issue: "prepared statement not found"
-
-**Cause**: Repository manager not initialized or closed prematurely
-
-**Solution**: Ensure repository manager is initialized before use and closed only on shutdown
-
-```go
-app, err := app.InitApp(config)
-defer app.Close() // Defer cleanup to end of main()
-```
-
-### Issue: High memory usage
-
-**Cause**: Prepared statements hold memory for execution plans
-
-**Solution**: This is expected and optimal. Each prepared statement uses ~1-5KB. Monitor with:
-
-```go
-log.Printf("Prepared statements: %d", app.GetStatementCount())
-```
-
-## Mermaid Diagram
-
-```mermaid
-classDiagram
-direction BT
-class city_ipv4_complete {
- bigint network_start_integer
- bigint network_last_integer
- int geoname_id
- int registered_country_geoname_id
- text represented_country_geoname_id
- int is_anonymous_proxy
- int is_satellite_provider
- text postal_code
- double latitude
- double longitude
- int accuracy_radius
- text is_anycast
-}
-class city_ipv6_complete {
- double network_start_integer
- double network_last_integer
- int geoname_id
- int registered_country_geoname_id
- text represented_country_geoname_id
- int is_anonymous_proxy
- int is_satellite_provider
- text postal_code
- double latitude
- text longitude
- text accuracy_radius
- text is_anycast
-}
-class city_locations_fr {
- text locale_code
- text continent_code
- text continent_name
- text country_iso_code
- text country_name
- text subdivision_1_iso_code
- text subdivision_1_name
- text subdivision_2_iso_code
- text subdivision_2_name
- text city_name
- text metro_code
- text time_zone
- text is_in_european_union
- int geoname_id
-}
-class connections_logs {
- bigint unsigned user_id
- varchar(50) ip_adress
- varchar(200) user_agent
- varchar(100) location
- varchar(10) type
- bigint timestamp
- bigint unsigned id
-}
-class nodes {
- bigint unsigned user_id
- bigint unsigned parent_id
- varchar(50) name
- varchar(255) description
- varchar(200) tags
- tinyint role /* 1=workspace, 2=category, 3=document, 4=resource */
- int color
- text icon
- text thumbnail
- varchar(30) theme
- tinyint(1) accessibility /* 1=private, 2=public */
- int access
- tinyint display
- int order
- longtext content
- longtext content_compiled
- int size
- json metadata
- bigint created_timestamp
- bigint updated_timestamp
- bigint unsigned id
-}
-class permissions {
- bigint unsigned node_id
- bigint unsigned user_id
- tinyint permission
- bigint created_timestamp
- bigint unsigned id
-}
-class schema_migrations {
- tinyint(1) dirty
- bigint version
-}
-class sessions {
- bigint unsigned user_id
- varchar(255) refresh_token
- bigint expire_token
- bigint last_refresh_timestamp
- int active
- bigint login_timestamp
- bigint logout_timestamp
- bigint unsigned id
-}
-class users {
- varchar(25) username
- varchar(25) firstname
- varchar(25) lastname
- int role
- varchar(75) avatar
- varchar(50) email
- varchar(255) password
- varchar(255) password_reset_token
- bigint created_timestamp
- bigint updated_timestamp
- bigint unsigned id
-}
-
-city_ipv4_complete --> city_locations_fr : geoname_id
-
-city_ipv6_complete --> city_locations_fr : geoname_id
-
-connections_logs --> users : user_id-id
-
-nodes --> nodes : parent_id-id
-
-nodes --> users : user_id-id
-
-permissions --> nodes : node_id-id
-
-permissions --> users : user_id-id
-
-sessions --> users : user_id-id
-```
diff --git a/backend/repositories/log.repository.go b/backend/repositories/log.repository.go
index 275967f8..e862682e 100644
--- a/backend/repositories/log.repository.go
+++ b/backend/repositories/log.repository.go
@@ -22,7 +22,6 @@ func NewLogRepository(db *sqlx.DB) LogRepository {
return &LogRepositoryImpl{db: db}
}
-// GetLocationFromIP returns the location string from an IP address
func (r *LogRepositoryImpl) GetLocationFromIP(ip string) string {
geonameId, err := r.getLocationIdFromIP(ip)
if err != nil {
@@ -46,7 +45,6 @@ func (r *LogRepositoryImpl) GetLocationFromIP(ip string) string {
return strings.Join(parts, ", ")
}
-// getLocationIdFromIP returns the geoname ID for an IP address
func (r *LogRepositoryImpl) getLocationIdFromIP(ip string) (int64, error) {
ipInt, db, err := ipToDecimal(ip)
if err != nil {
@@ -72,7 +70,6 @@ func (r *LogRepositoryImpl) getLocationIdFromIP(ip string) (int64, error) {
return locationId, nil
}
-// ipToDecimal converts an IP address to its decimal representation
func ipToDecimal(ipStr string) (string, string, error) {
ip := net.ParseIP(ipStr)
if ip == nil {
diff --git a/backend/repositories/node.repository.go b/backend/repositories/node.repository.go
index 617740bb..efe20cf5 100644
--- a/backend/repositories/node.repository.go
+++ b/backend/repositories/node.repository.go
@@ -106,7 +106,7 @@ func (r *NodeRepositoryImpl) loadPermissionsForNodes(userId types.Snowflake, nod
}
// Build the IN clause
- nodeIDs := make([]interface{}, 0, len(nodeMap))
+ nodeIDs := make([]any, 0, len(nodeMap))
placeholders := make([]string, 0, len(nodeMap))
for nodeId := range nodeMap {
nodeIDs = append(nodeIDs, nodeId)
@@ -119,7 +119,7 @@ func (r *NodeRepositoryImpl) loadPermissionsForNodes(userId types.Snowflake, nod
WHERE user_id = ? AND node_id IN (%s)`,
strings.Join(placeholders, ","))
- args := append([]interface{}{userId}, nodeIDs...)
+ args := append([]any{userId}, nodeIDs...)
rows, err := r.db.Query(query, args...)
if err != nil {
return fmt.Errorf("failed to query permissions: %w", err)
diff --git a/backend/repositories/oidc_provider.repository.go b/backend/repositories/oidc_provider.repository.go
index 0dc06eb7..5e3d7de4 100644
--- a/backend/repositories/oidc_provider.repository.go
+++ b/backend/repositories/oidc_provider.repository.go
@@ -25,7 +25,6 @@ func NewOIDCProviderRepository(db *sqlx.DB) OIDCProviderRepository {
return &OIDCProviderRepositoryImpl{db: db}
}
-// GetByUserID retrieves all OIDC provider links for a user
func (r *OIDCProviderRepositoryImpl) GetByUserID(userID types.Snowflake) ([]*models.UserOIDCProvider, error) {
var links []*models.UserOIDCProvider
err := r.db.Select(&links, `
@@ -38,7 +37,6 @@ func (r *OIDCProviderRepositoryImpl) GetByUserID(userID types.Snowflake) ([]*mod
return links, nil
}
-// GetByProviderAndSubject finds a link by provider name and provider user ID
func (r *OIDCProviderRepositoryImpl) GetByProviderAndSubject(providerName, providerUserID string) (*models.UserOIDCProvider, error) {
var link models.UserOIDCProvider
err := r.db.Get(&link, `
@@ -54,7 +52,6 @@ func (r *OIDCProviderRepositoryImpl) GetByProviderAndSubject(providerName, provi
return &link, nil
}
-// Create creates a new user-OIDC provider link
func (r *OIDCProviderRepositoryImpl) Create(link *models.UserOIDCProvider) (*models.UserOIDCProvider, error) {
_, err := r.db.NamedExec(`
INSERT INTO user_oidc_providers (id, user_id, provider_name, provider_user_id, created_timestamp, updated_timestamp)
@@ -65,7 +62,6 @@ func (r *OIDCProviderRepositoryImpl) Create(link *models.UserOIDCProvider) (*mod
return link, nil
}
-// Delete removes a user-OIDC provider link
func (r *OIDCProviderRepositoryImpl) Delete(id types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM user_oidc_providers WHERE id = ?`, id)
if err != nil {
@@ -74,7 +70,6 @@ func (r *OIDCProviderRepositoryImpl) Delete(id types.Snowflake) error {
return nil
}
-// DeleteByUserID removes all OIDC provider links for a user
func (r *OIDCProviderRepositoryImpl) DeleteByUserID(userID types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM user_oidc_providers WHERE user_id = ?`, userID)
if err != nil {
diff --git a/backend/repositories/permission.repository.go b/backend/repositories/permission.repository.go
index 9ba35416..4c1783d4 100644
--- a/backend/repositories/permission.repository.go
+++ b/backend/repositories/permission.repository.go
@@ -27,7 +27,6 @@ func NewPermissionRepository(db *sqlx.DB) PermissionRepository {
return &PermissionRepositoryImpl{db: db}
}
-// GetByID retrieves a permission by ID
func (r *PermissionRepositoryImpl) GetByID(permissionId types.Snowflake) (*models.Permission, error) {
var perm models.Permission
err := r.db.Get(&perm, `
@@ -40,7 +39,6 @@ func (r *PermissionRepositoryImpl) GetByID(permissionId types.Snowflake) (*model
return &perm, nil
}
-// GetByNode retrieves all permissions for a node
func (r *PermissionRepositoryImpl) GetByNode(nodeId types.Snowflake) ([]*models.Permission, error) {
var permissions []*models.Permission
err := r.db.Select(&permissions, `
@@ -53,7 +51,6 @@ func (r *PermissionRepositoryImpl) GetByNode(nodeId types.Snowflake) ([]*models.
return permissions, nil
}
-// GetByNodeAndUser retrieves a specific permission for a node and user
func (r *PermissionRepositoryImpl) GetByNodeAndUser(nodeId types.Snowflake, userId types.Snowflake) (*models.Permission, error) {
var perm models.Permission
err := r.db.Get(&perm, `
@@ -66,7 +63,6 @@ func (r *PermissionRepositoryImpl) GetByNodeAndUser(nodeId types.Snowflake, user
return &perm, nil
}
-// Create creates a new permission
func (r *PermissionRepositoryImpl) Create(permission *models.Permission) (*models.Permission, error) {
_, err := r.db.NamedExec(`
INSERT INTO permissions (id, node_id, user_id, permission, created_timestamp)
@@ -77,7 +73,6 @@ func (r *PermissionRepositoryImpl) Create(permission *models.Permission) (*model
return permission, nil
}
-// Update updates an existing permission
func (r *PermissionRepositoryImpl) Update(permission *models.Permission) error {
_, err := r.db.Exec(`
UPDATE permissions
@@ -89,7 +84,6 @@ func (r *PermissionRepositoryImpl) Update(permission *models.Permission) error {
return nil
}
-// Delete deletes a permission
func (r *PermissionRepositoryImpl) Delete(permissionId types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM permissions WHERE id = ?`, permissionId)
if err != nil {
@@ -98,7 +92,6 @@ func (r *PermissionRepositoryImpl) Delete(permissionId types.Snowflake) error {
return nil
}
-// HasPermission checks if a user has required permission on a node
func (r *PermissionRepositoryImpl) HasPermission(userId, nodeId types.Snowflake, required int) (bool, int) {
var perm sql.NullInt32
r.db.QueryRow(`
diff --git a/backend/repositories/session.repository.go b/backend/repositories/session.repository.go
index 79f5c4b2..29eba8b1 100644
--- a/backend/repositories/session.repository.go
+++ b/backend/repositories/session.repository.go
@@ -27,7 +27,6 @@ func NewSessionRepository(db *sqlx.DB) SessionRepository {
return &SessionRepositoryImpl{db: db}
}
-// GetByUserId retrieves all sessions for a given user ID
func (r *SessionRepositoryImpl) GetByUserId(userId types.Snowflake) ([]models.Session, error) {
var sessions []models.Session
err := r.db.Select(&sessions, `
@@ -42,7 +41,6 @@ func (r *SessionRepositoryImpl) GetByUserId(userId types.Snowflake) ([]models.Se
return sessions, nil
}
-// GetByRefreshToken retrieves a session by refresh token
func (r *SessionRepositoryImpl) GetByRefreshToken(refreshToken string) (*models.Session, error) {
var session models.Session
err := r.db.Get(&session, `
@@ -57,7 +55,6 @@ func (r *SessionRepositoryImpl) GetByRefreshToken(refreshToken string) (*models.
return &session, nil
}
-// Create creates a new session
func (r *SessionRepositoryImpl) Create(session *models.Session) (*models.Session, error) {
_, err := r.db.NamedExec(`
INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, ip_adress, user_agent, location, type, login_timestamp, logout_timestamp)
@@ -70,7 +67,6 @@ func (r *SessionRepositoryImpl) Create(session *models.Session) (*models.Session
return session, nil
}
-// Update updates an existing session (only refresh token and expiry)
func (r *SessionRepositoryImpl) Update(session *models.Session) (*models.Session, error) {
_, err := r.db.Exec(`
UPDATE sessions
@@ -83,7 +79,6 @@ func (r *SessionRepositoryImpl) Update(session *models.Session) (*models.Session
return session, nil
}
-// Delete deletes a session
func (r *SessionRepositoryImpl) Delete(sessionId types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM sessions WHERE id = ?`, sessionId)
if err != nil {
@@ -93,7 +88,6 @@ func (r *SessionRepositoryImpl) Delete(sessionId types.Snowflake) error {
return nil
}
-// DeleteAllByUser deletes all sessions for a user
func (r *SessionRepositoryImpl) DeleteAllByUser(userId types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM sessions WHERE user_id = ?`, userId)
if err != nil {
@@ -102,7 +96,6 @@ func (r *SessionRepositoryImpl) DeleteAllByUser(userId types.Snowflake) error {
return nil
}
-// DeleteOld deletes expired sessions
func (r *SessionRepositoryImpl) DeleteOld() error {
currentTime := time.Now().UnixMilli()
_, err := r.db.Exec(`DELETE FROM sessions WHERE expire_token < ?`, currentTime)
diff --git a/backend/repositories/user.repository.go b/backend/repositories/user.repository.go
index 4af861cf..4b1a41aa 100644
--- a/backend/repositories/user.repository.go
+++ b/backend/repositories/user.repository.go
@@ -17,7 +17,6 @@ type UserRepository interface {
GetAll() ([]*models.User, error)
GetByID(id types.Snowflake) (*models.User, error)
GetByUsername(username string) (*models.User, error)
- GetByEmail(email string) (*models.User, error)
HasPassword(id types.Snowflake) (bool, error)
SearchPublic(query string) ([]*models.User, error)
CheckUsernameExists(username string) (bool, error)
@@ -32,7 +31,6 @@ func NewUserRepository(db *sqlx.DB) UserRepository {
return &UserRepositoryImpl{db: db}
}
-// GetAll retrieves all users
func (r *UserRepositoryImpl) GetAll() ([]*models.User, error) {
var users []*models.User
err := r.db.Select(&users, `
@@ -45,7 +43,6 @@ func (r *UserRepositoryImpl) GetAll() ([]*models.User, error) {
return users, nil
}
-// GetByID retrieves a user by ID
func (r *UserRepositoryImpl) GetByID(id types.Snowflake) (*models.User, error) {
var user models.User
err := r.db.Get(&user, `
@@ -61,7 +58,6 @@ func (r *UserRepositoryImpl) GetByID(id types.Snowflake) (*models.User, error) {
return &user, nil
}
-// GetByUsername retrieves a user by username (includes password for authentication)
func (r *UserRepositoryImpl) GetByUsername(username string) (*models.User, error) {
var user models.User
err := r.db.Get(&user, `
@@ -77,23 +73,6 @@ func (r *UserRepositoryImpl) GetByUsername(username string) (*models.User, error
return &user, nil
}
-// GetByEmail retrieves a user by email
-func (r *UserRepositoryImpl) GetByEmail(email string) (*models.User, error) {
- var user models.User
- err := r.db.Get(&user, `
- SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp
- FROM users
- WHERE email = ?`, email)
- if err == sql.ErrNoRows {
- return nil, nil
- }
- if err != nil {
- return nil, fmt.Errorf("failed to get user by email: %w", err)
- }
- return &user, nil
-}
-
-// HasPassword checks if a user has a password set
func (r *UserRepositoryImpl) HasPassword(id types.Snowflake) (bool, error) {
var count int
err := r.db.Get(&count, `SELECT COUNT(*) FROM users WHERE id = ? AND password IS NOT NULL`, id)
@@ -103,7 +82,6 @@ func (r *UserRepositoryImpl) HasPassword(id types.Snowflake) (bool, error) {
return count > 0, nil
}
-// SearchPublic searches for public user profiles
func (r *UserRepositoryImpl) SearchPublic(query string) ([]*models.User, error) {
var users []*models.User
err := r.db.Select(&users, `
@@ -117,7 +95,6 @@ func (r *UserRepositoryImpl) SearchPublic(query string) ([]*models.User, error)
return users, nil
}
-// CheckUsernameExists checks if a username already exists
func (r *UserRepositoryImpl) CheckUsernameExists(username string) (bool, error) {
var count int
err := r.db.Get(&count, `SELECT COUNT(*) FROM users WHERE username = ?`, username)
@@ -127,7 +104,6 @@ func (r *UserRepositoryImpl) CheckUsernameExists(username string) (bool, error)
return count > 0, nil
}
-// Create creates a new user
func (r *UserRepositoryImpl) Create(user *models.User) (*models.User, error) {
_, err := r.db.NamedExec(`
INSERT INTO users (id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp)
@@ -139,7 +115,6 @@ func (r *UserRepositoryImpl) Create(user *models.User) (*models.User, error) {
return user, nil
}
-// Update updates an existing user
func (r *UserRepositoryImpl) Update(id types.Snowflake, user *models.User) (*models.User, error) {
_, err := r.db.Exec(`
UPDATE users
@@ -152,7 +127,6 @@ func (r *UserRepositoryImpl) Update(id types.Snowflake, user *models.User) (*mod
return user, nil
}
-// UpdatePassword updates a user's password
func (r *UserRepositoryImpl) UpdatePassword(id types.Snowflake, password string) error {
_, err := r.db.Exec(`UPDATE users SET password=?, password_reset_token=NULL WHERE id=?`, password, id)
if err != nil {
@@ -161,7 +135,6 @@ func (r *UserRepositoryImpl) UpdatePassword(id types.Snowflake, password string)
return nil
}
-// UpdatePasswordResetToken updates a user's password reset token
func (r *UserRepositoryImpl) UpdatePasswordResetToken(id types.Snowflake, resetToken string) error {
_, err := r.db.Exec(`UPDATE users SET password_reset_token=? WHERE id=?`, resetToken, id)
if err != nil {
@@ -170,7 +143,6 @@ func (r *UserRepositoryImpl) UpdatePasswordResetToken(id types.Snowflake, resetT
return nil
}
-// Delete deletes a user
func (r *UserRepositoryImpl) Delete(id types.Snowflake) error {
_, err := r.db.Exec(`DELETE FROM users WHERE id=?`, id)
if err != nil {
diff --git a/backend/repositories/user_settings.repository.go b/backend/repositories/user_settings.repository.go
index 923be747..7a365378 100644
--- a/backend/repositories/user_settings.repository.go
+++ b/backend/repositories/user_settings.repository.go
@@ -22,7 +22,6 @@ func NewUserSettingsRepository(db *sqlx.DB) UserSettingsRepository {
return &UserSettingsRepositoryImpl{db: db}
}
-// GetByUserID retrieves the settings for a given user, or nil if none exist
func (r *UserSettingsRepositoryImpl) GetByUserID(userID types.Snowflake) (*models.UserSettings, error) {
var settings models.UserSettings
err := r.db.Get(&settings, `SELECT user_id, general, editor, advanced FROM user_settings WHERE user_id = ?`, userID)
@@ -35,7 +34,6 @@ func (r *UserSettingsRepositoryImpl) GetByUserID(userID types.Snowflake) (*model
return &settings, nil
}
-// Upsert inserts or updates user settings (MySQL ON DUPLICATE KEY UPDATE)
func (r *UserSettingsRepositoryImpl) Upsert(settings *models.UserSettings) error {
_, err := r.db.NamedExec(`
INSERT INTO user_settings (user_id, general, editor, advanced)
diff --git a/backend/router/router.go b/backend/router/router.go
index f36bca72..ab1bca8d 100644
--- a/backend/router/router.go
+++ b/backend/router/router.go
@@ -9,19 +9,22 @@ import (
"github.com/gin-gonic/gin"
)
-// Fake delay for dev to test reactivity
+// For development only - fake delay for dev to test reactivity
-// func DelayMiddleware(delay time.Duration) gin.HandlerFunc {
-// return func(c *gin.Context) {
-// time.Sleep(delay)
-// c.Next()
-// }
-// }
+/*
+ func DelayMiddleware(delay time.Duration) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ time.Sleep(delay)
+ c.Next()
+ }
+ }
+*/
func InitRouter(app *app.App) *gin.Engine {
router := gin.New()
router.Use(gin.Recovery())
//router.Use(DelayMiddleware(250 * time.Millisecond))
+
// Config proxy and CORS
router.SetTrustedProxies([]string{"127.0.0.1", "localhost"})
router.Use(cors.New(cors.Config{
@@ -34,11 +37,8 @@ func InitRouter(app *app.App) *gin.Engine {
}
// Allow all sub domains (www, api, etc.)
- // simple example for mondomaine.com
- // remove the protocol for comparison
originHost := origin
if len(originHost) > 0 {
- // remove the protocol
if idx := len("http://"); len(originHost) > idx && originHost[:7] == "http://" {
originHost = originHost[7:]
} else if idx := len("https://"); len(originHost) > idx && originHost[:8] == "https://" {
diff --git a/backend/services/auth.service.go b/backend/services/auth.service.go
index cc22dd42..0a26d0bd 100644
--- a/backend/services/auth.service.go
+++ b/backend/services/auth.service.go
@@ -162,7 +162,7 @@ func (s *authService) RequestPasswordReset(username string, mailClient *mail.Cli
func (s *authService) ResetPassword(token, newPassword string) error {
claims := jwt.RegisteredClaims{}
- parsedToken, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
+ parsedToken, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("invalid signing method")
}
diff --git a/backend/services/backup.service.go b/backend/services/backup.service.go
index e4d6dffa..98ed8678 100644
--- a/backend/services/backup.service.go
+++ b/backend/services/backup.service.go
@@ -23,19 +23,15 @@ import (
const (
backupVersion = "1.1.0"
- backupExpiryHours = 24 // Backup files expire after 24 hours
- maxConcurrentFiles = 5 // Max concurrent file downloads for backup
+ backupExpiryHours = 24
+ maxConcurrentFiles = 5
)
// BackupService handles backup creation and management
type BackupService interface {
- // CreateBackupAsync starts an async backup job and returns the job ID
CreateBackupAsync(userId types.Snowflake, options types.BackupOptions, minioClient *minio.Client, signerClient *minio.Client) (string, error)
- // GetBackupStatus returns the current status of a backup job
GetBackupStatus(userId types.Snowflake, jobId string) (*types.BackupJob, error)
- // CancelBackup cancels an ongoing backup job
CancelBackup(userId types.Snowflake, jobId string) error
- // CleanupExpiredBackups removes expired backup files
CleanupExpiredBackups(minioClient *minio.Client) error
}
@@ -43,12 +39,11 @@ type backupService struct {
nodeRepo repositories.NodeRepository
userSettingsRepo repositories.UserSettingsRepository
jobs map[string]*types.BackupJob
- userJobs map[types.Snowflake]string // Maps userId to current jobId
+ userJobs map[types.Snowflake]string
jobMutex sync.RWMutex
cancel map[string]context.CancelFunc
}
-// NewBackupService creates a new backup service instance
func NewBackupService(nodeRepo repositories.NodeRepository, userSettingsRepo repositories.UserSettingsRepository) BackupService {
return &backupService{
nodeRepo: nodeRepo,
@@ -59,16 +54,13 @@ func NewBackupService(nodeRepo repositories.NodeRepository, userSettingsRepo rep
}
}
-// CreateBackupAsync starts an asynchronous backup job
func (s *backupService) CreateBackupAsync(userId types.Snowflake, options types.BackupOptions, minioClient *minio.Client, signerClient *minio.Client) (string, error) {
if minioClient == nil {
return "", errors.New("minio client not initialized")
}
- // Cancel any existing backup for this user
s.cancelExistingBackup(userId, minioClient)
- // Use a fixed job ID per user so backups are replaced
jobId := fmt.Sprintf("user-%d-backup", userId)
// Create job entry
@@ -89,24 +81,21 @@ func (s *backupService) CreateBackupAsync(userId types.Snowflake, options types.
s.userJobs[userId] = jobId
s.jobMutex.Unlock()
- // Create cancellation context
+ // Cancellation context
ctx, cancel := context.WithCancel(context.Background())
s.jobMutex.Lock()
s.cancel[jobId] = cancel
s.jobMutex.Unlock()
- // Start async processing
go s.processBackup(ctx, job, minioClient, signerClient)
return jobId, nil
}
-// cancelExistingBackup cancels any ongoing backup and removes the old backup file
func (s *backupService) cancelExistingBackup(userId types.Snowflake, minioClient *minio.Client) {
s.jobMutex.Lock()
defer s.jobMutex.Unlock()
- // Check if user has an existing job
existingJobId, exists := s.userJobs[userId]
if !exists {
return
@@ -118,7 +107,6 @@ func (s *backupService) cancelExistingBackup(userId types.Snowflake, minioClient
return
}
- // Cancel if still running
if existingJob.Status == types.BackupStatusPending || existingJob.Status == types.BackupStatusProcessing {
if cancel, ok := s.cancel[existingJobId]; ok {
cancel()
@@ -126,18 +114,15 @@ func (s *backupService) cancelExistingBackup(userId types.Snowflake, minioClient
}
}
- // Delete the old backup file from MinIO (private backup bucket)
if minioClient != nil {
objectName := fmt.Sprintf("%d/backup.zip", userId)
backupBucket := utils.GetBackupBucketName()
_ = minioClient.RemoveObject(context.Background(), backupBucket, objectName, minio.RemoveObjectOptions{})
}
- // Remove old job
delete(s.jobs, existingJobId)
}
-// GetBackupStatus returns the current status of a backup job
func (s *backupService) GetBackupStatus(userId types.Snowflake, jobId string) (*types.BackupJob, error) {
s.jobMutex.RLock()
defer s.jobMutex.RUnlock()
@@ -155,7 +140,6 @@ func (s *backupService) GetBackupStatus(userId types.Snowflake, jobId string) (*
return job, nil
}
-// CancelBackup cancels an ongoing backup job
func (s *backupService) CancelBackup(userId types.Snowflake, jobId string) error {
s.jobMutex.Lock()
defer s.jobMutex.Unlock()
@@ -173,7 +157,6 @@ func (s *backupService) CancelBackup(userId types.Snowflake, jobId string) error
return errors.New("backup job already finished")
}
- // Cancel the context
if cancel, ok := s.cancel[jobId]; ok {
cancel()
delete(s.cancel, jobId)
@@ -186,7 +169,6 @@ func (s *backupService) CancelBackup(userId types.Snowflake, jobId string) error
return nil
}
-// CleanupExpiredBackups cleans up expired job entries from memory.
// Note: The actual backup files are automatically deleted by MinIO lifecycle policy after 24h.
// This function only cleans up the in-memory job tracking.
func (s *backupService) CleanupExpiredBackups(minioClient *minio.Client) error {
@@ -206,7 +188,6 @@ func (s *backupService) CleanupExpiredBackups(minioClient *minio.Client) error {
return nil
}
-// processBackup is the main backup processing goroutine
func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob, minioClient *minio.Client, signerClient *minio.Client) {
defer func() {
if r := recover(); r != nil {
@@ -216,14 +197,12 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
s.updateJobStatus(job, types.BackupStatusProcessing, 5, "Fetching data...", "")
- // Check for cancellation
select {
case <-ctx.Done():
return
default:
}
- // Fetch all nodes for backup
nodes, err := s.nodeRepo.GetAllForBackup(job.UserID)
if err != nil {
s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to fetch nodes: %v", err))
@@ -232,21 +211,18 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
s.updateJobStatus(job, types.BackupStatusProcessing, 15, "Preparing backup archive...", "")
- // Create ZIP archive in memory
var buf bytes.Buffer
zipWriter := zip.NewWriter(&buf)
- // Prepare backup statistics
stats := types.BackupStats{
TotalNodes: len(nodes),
}
- // Filter and categorize nodes
var documents []*models.Node
var files []*models.Node
for _, node := range nodes {
- if node.Role == 4 { // Role 4 is file/resource
+ if node.Role == 4 {
files = append(files, node)
stats.TotalFiles++
} else {
@@ -283,21 +259,19 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
if job.Options.IncludeFiles && len(files) > 0 {
if err := s.addFilesToZip(ctx, zipWriter, files, job, minioClient, &stats); err != nil {
if ctx.Err() != nil {
- return // Cancelled
+ return
}
s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to add files to archive: %v", err))
return
}
}
- // Check for cancellation
select {
case <-ctx.Done():
return
default:
}
- // Fetch user settings if requested
if job.Options.IncludeSettings {
s.updateJobStatus(job, types.BackupStatusProcessing, 75, "Fetching user settings...", "")
@@ -313,7 +287,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
}
}
- // Check for cancellation
select {
case <-ctx.Done():
return
@@ -322,7 +295,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
s.updateJobStatus(job, types.BackupStatusProcessing, 85, "Creating manifest...", "")
- // Create and add manifest
manifest := types.BackupManifest{
Version: backupVersion,
CreatedAt: time.Now(),
@@ -341,7 +313,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
return
}
- // Add file index for easier restoration
if job.Options.IncludeFiles && len(files) > 0 {
fileIndex := s.createFileIndex(files)
if err := s.addJSONToZip(zipWriter, "files_index.json", fileIndex); err != nil {
@@ -350,7 +321,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
}
}
- // Close ZIP writer
if err := zipWriter.Close(); err != nil {
s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to finalize archive: %v", err))
return
@@ -378,7 +348,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
stats.TotalSize = int64(buf.Len())
// Generate presigned URL for download (valid for 24 hours)
- // This is the ONLY way to access the backup since the bucket is private
reqParams := make(url.Values)
reqParams.Set(
"response-content-disposition",
@@ -399,7 +368,6 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
return
}
- // Update job with completion status
s.jobMutex.Lock()
job.Status = types.BackupStatusCompleted
job.Progress = 100
@@ -410,14 +378,12 @@ func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob,
s.jobMutex.Unlock()
}
-// updateJobStatus safely updates the job status
func (s *backupService) updateJobStatus(job *types.BackupJob, status types.BackupStatus, progress int, message string, errorMsg string) {
s.jobMutex.Lock()
defer s.jobMutex.Unlock()
job.Status = status
- // Handle failed status: update message to reflect failure
if status == types.BackupStatusFailed {
job.Message = "Backup failed"
if errorMsg != "" {
@@ -435,13 +401,11 @@ func (s *backupService) updateJobStatus(job *types.BackupJob, status types.Backu
job.UpdatedAt = time.Now()
}
-// prepareDocumentsData prepares document nodes for backup
-func (s *backupService) prepareDocumentsData(documents []*models.Node, includeMetadata bool) (interface{}, error) {
+func (s *backupService) prepareDocumentsData(documents []*models.Node, includeMetadata bool) (any, error) {
if !includeMetadata {
- // Strip metadata from documents
- stripped := make([]map[string]interface{}, len(documents))
+ stripped := make([]map[string]any, len(documents))
for i, doc := range documents {
- stripped[i] = map[string]interface{}{
+ stripped[i] = map[string]any{
"id": doc.Id,
"parent_id": doc.ParentId,
"name": doc.Name,
@@ -465,8 +429,7 @@ func (s *backupService) prepareDocumentsData(documents []*models.Node, includeMe
return documents, nil
}
-// addJSONToZip adds a JSON file to the ZIP archive
-func (s *backupService) addJSONToZip(zipWriter *zip.Writer, filename string, data interface{}) error {
+func (s *backupService) addJSONToZip(zipWriter *zip.Writer, filename string, data any) error {
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
@@ -481,11 +444,9 @@ func (s *backupService) addJSONToZip(zipWriter *zip.Writer, filename string, dat
return err
}
-// addFilesToZip downloads and adds files to the ZIP archive
func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer, files []*models.Node, job *types.BackupJob, minioClient *minio.Client, stats *types.BackupStats) error {
bucket := os.Getenv("MINIO_BUCKET")
- // Process files with a semaphore for concurrency control
sem := make(chan struct{}, maxConcurrentFiles)
var wg sync.WaitGroup
var mu sync.Mutex
@@ -507,7 +468,6 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
defer wg.Done()
defer func() { <-sem }() // Release semaphore
- // Get file path from metadata
var objectPath string
if f.Metadata != nil {
if transformedPath, ok := (*f.Metadata)["transformed_path"].(string); ok {
@@ -516,7 +476,6 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
}
if objectPath == "" {
- // Fallback: try to construct path from content_compiled
if f.ContentCompiled != nil {
objectPath = fmt.Sprintf("%d/%s", job.UserID, *f.ContentCompiled)
}
@@ -530,10 +489,9 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
Reason: "no path found in metadata",
})
mu.Unlock()
- return // Skip file because we can't determine its path
+ return
}
- // Download file from MinIO
obj, err := minioClient.GetObject(ctx, bucket, objectPath, minio.GetObjectOptions{})
if err != nil {
mu.Lock()
@@ -543,11 +501,10 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
Reason: fmt.Sprintf("failed to get object: %v", err),
})
mu.Unlock()
- return // Skip file on error
+ return
}
defer obj.Close()
- // Check if object exists by reading stat
_, err = obj.Stat()
if err != nil {
mu.Lock()
@@ -557,10 +514,9 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
Reason: "file not found in storage",
})
mu.Unlock()
- return // Skip file if not found
+ return
}
- // Read file content
content, err := io.ReadAll(obj)
if err != nil {
mu.Lock()
@@ -574,7 +530,6 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
return
}
- // Determine filename for archive
archivePath := fmt.Sprintf("files/%d%s", f.Id, filepath.Ext(f.Name))
if f.Metadata != nil {
if originalPath, ok := (*f.Metadata)["original_path"].(string); ok {
@@ -582,7 +537,6 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
}
}
- // Add to ZIP (synchronized to avoid concurrent writes)
mu.Lock()
writer, err := zipWriter.Create(archivePath)
if err != nil {
@@ -612,7 +566,6 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
stats.TotalSize += int64(len(content))
mu.Unlock()
- // Update progress
progress := 40 + int(float64(processedFiles)/float64(totalFiles)*40)
s.updateJobStatus(job, types.BackupStatusProcessing, progress, fmt.Sprintf("Processing files (%d/%d)...", processedFiles, totalFiles), "")
@@ -624,9 +577,8 @@ func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer
return nil
}
-// createFileIndex creates an index mapping file IDs to their archive paths
-func (s *backupService) createFileIndex(files []*models.Node) []map[string]interface{} {
- index := make([]map[string]interface{}, len(files))
+func (s *backupService) createFileIndex(files []*models.Node) []map[string]any {
+ index := make([]map[string]any, len(files))
for i, f := range files {
archivePath := fmt.Sprintf("files/%d%s", f.Id, filepath.Ext(f.Name))
if f.Metadata != nil {
@@ -635,7 +587,7 @@ func (s *backupService) createFileIndex(files []*models.Node) []map[string]inter
}
}
- entry := map[string]interface{}{
+ entry := map[string]any{
"id": f.Id,
"name": f.Name,
"archive_path": archivePath,
diff --git a/backend/services/manager.go b/backend/services/manager.go
index 7c2ca940..6ad7799c 100644
--- a/backend/services/manager.go
+++ b/backend/services/manager.go
@@ -9,7 +9,6 @@ import (
"github.com/minio/minio-go/v7"
)
-// ServiceManager manages all services and their dependencies
type ServiceManager struct {
Auth AuthService
User UserService
@@ -24,7 +23,6 @@ type ServiceManager struct {
initialized bool
}
-// NewServiceManager creates a new service manager and initializes all services
func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, resourceConfig ResourceConfig) (*ServiceManager, error) {
sm := &ServiceManager{}
@@ -37,42 +35,20 @@ func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowfla
return sm, nil
}
-// initializeServices creates and initializes all service instances
func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, resourceConfig ResourceConfig) error {
- // Initialize Auth Service
sm.Auth = NewAuthService(repos.User, repos.Session, repos.Log, snowflake)
-
- // Initialize User Service
sm.User = NewUserService(repos.User, repos.Log, snowflake)
-
- // Initialize Minio Service (must be initialized before NodeService)
sm.Minio = NewMinioService(minioClient)
-
- // Initialize Node Service (depends on MinioService for file cleanup)
sm.Node = NewNodeService(repos.Node, repos.Permission, sm.Minio, snowflake)
-
- // Initialize Permission Service
sm.Permission = NewPermissionService(repos.Permission, repos.Node, snowflake)
-
- // Initialize Session Service
sm.Session = NewSessionService(repos.Session)
-
- // Initialize Resource Service
sm.Resource = NewResourceService(repos.Node, snowflake, minioClient, resourceConfig)
-
- // Initialize Backup Service
sm.Backup = NewBackupService(repos.Node, repos.UserSettings)
-
- // Initialize OIDC Service
sm.OIDC = NewOIDCService(repos.OIDCProvider, repos.User, sm.User, repos.Session, repos.Log, snowflake)
-
- // Initialize UserSettings Service
sm.UserSettings = NewUserSettingsService(repos.UserSettings)
-
return nil
}
-// IsInitialized returns whether the service manager is initialized
func (sm *ServiceManager) IsInitialized() bool {
return sm.initialized
}
diff --git a/backend/services/minio.service.go b/backend/services/minio.service.go
index 8b56a184..f52e1d8b 100644
--- a/backend/services/minio.service.go
+++ b/backend/services/minio.service.go
@@ -68,7 +68,7 @@ func (s *minioService) DeleteNodeFiles(resources []*models.NodeResourceInfo) err
for _, res := range resources {
if err := s.DeleteSingleResource(res.UserId, res.Id, res.Metadata); err != nil {
- // Log error but continue deleting other files
+ // Error but continue deleting other files
// logger.Warn(fmt.Sprintf("Failed to delete MinIO file for node %d: %v", res.Id, err))
lastErr = err
}
diff --git a/backend/services/node.service.go b/backend/services/node.service.go
index 7b7c889b..8b88685c 100644
--- a/backend/services/node.service.go
+++ b/backend/services/node.service.go
@@ -17,7 +17,7 @@ type NodeService interface {
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]interface{}, 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
@@ -88,7 +88,7 @@ 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]interface{}, error) {
+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)
if err != nil {
return nil, err
@@ -111,7 +111,7 @@ func (s *nodeService) GetNode(nodeId types.Snowflake, connectedUserId types.Snow
}
}
- return map[string]interface{}{
+ return map[string]any{
"node": dbNode,
"permissions": filteredPerms,
}, nil
diff --git a/backend/services/oidc.service.go b/backend/services/oidc.service.go
index 88538ad0..ed37db24 100644
--- a/backend/services/oidc.service.go
+++ b/backend/services/oidc.service.go
@@ -23,13 +23,13 @@ import (
type StateData struct {
Expiry time.Time
- IsLink bool // true if this is a link flow, false if login flow
- UserID types.Snowflake // user ID to link to (only set if IsLink is true)
+ IsLink bool
+ UserID types.Snowflake
}
type OIDCService interface {
- GetProviders() []oidc.PublicProvider
IsEnabled() bool
+ GetProviders() []oidc.PublicProvider
GenerateAuthURL(providerName, redirectURI string, linkUserID *types.Snowflake) (string, string, error)
ExchangeCodeForUser(providerName, code, redirectURI string) (*oidc.UserInfo, error)
LoginOrCreate(providerName string, userInfo *oidc.UserInfo, ip, userAgent string) (*models.User, *models.Session, bool, error)
@@ -52,7 +52,6 @@ type oidcService struct {
statesMu sync.RWMutex
}
-// NewOIDCService creates a new OIDC service
func NewOIDCService(
oidcRepo repositories.OIDCProviderRepository,
userRepo repositories.UserRepository,
@@ -75,13 +74,11 @@ func NewOIDCService(
states: make(map[string]*StateData),
}
- // Start cleanup goroutine for expired states
go svc.cleanupExpiredStates()
return svc
}
-// cleanupExpiredStates periodically removes expired state tokens
func (s *oidcService) cleanupExpiredStates() {
ticker := time.NewTicker(5 * time.Minute)
for range ticker.C {
@@ -96,33 +93,26 @@ func (s *oidcService) cleanupExpiredStates() {
}
}
-// GetProviders returns all available OIDC providers
-func (s *oidcService) GetProviders() []oidc.PublicProvider {
- return s.manager.GetProviders()
-}
-
-// IsEnabled returns true if OIDC is enabled
func (s *oidcService) IsEnabled() bool {
return s.manager.HasProviders()
}
-// GenerateAuthURL generates an authorization URL for a provider.
-// If linkUserID is provided, this is a link flow (linking provider to existing user).
-// If linkUserID is nil, this is a login flow.
+func (s *oidcService) GetProviders() []oidc.PublicProvider {
+ return s.manager.GetProviders()
+}
+
func (s *oidcService) GenerateAuthURL(providerName, redirectURI string, linkUserID *types.Snowflake) (string, string, error) {
provider, err := s.manager.GetProvider(providerName)
if err != nil {
return "", "", err
}
- // Generate a secure random state
stateBytes := make([]byte, 32)
if _, err := rand.Read(stateBytes); err != nil {
return "", "", fmt.Errorf("failed to generate state: %w", err)
}
state := base64.URLEncoding.EncodeToString(stateBytes)
- // Store state with metadata
stateData := &StateData{
Expiry: time.Now().Add(10 * time.Minute),
IsLink: linkUserID != nil,
@@ -135,7 +125,6 @@ func (s *oidcService) GenerateAuthURL(providerName, redirectURI string, linkUser
s.states[state] = stateData
s.statesMu.Unlock()
- // Build authorization URL
authURL, err := url.Parse(provider.AuthorizationEndpoint)
if err != nil {
return "", "", fmt.Errorf("invalid authorization endpoint: %w", err)
@@ -152,8 +141,6 @@ func (s *oidcService) GenerateAuthURL(providerName, redirectURI string, linkUser
return authURL.String(), state, nil
}
-// ValidateState validates and consumes an OIDC state token.
-// Returns the state data if valid, or an error if invalid/expired.
func (s *oidcService) ValidateState(state string) (*StateData, error) {
s.statesMu.Lock()
defer s.statesMu.Unlock()
@@ -163,10 +150,8 @@ func (s *oidcService) ValidateState(state string) (*StateData, error) {
return nil, errors.New("invalid state")
}
- // Remove state (one-time use)
delete(s.states, state)
- // Check if expired
if time.Now().After(data.Expiry) {
return nil, errors.New("state expired")
}
@@ -174,20 +159,17 @@ func (s *oidcService) ValidateState(state string) (*StateData, error) {
return data, nil
}
-// ExchangeCodeForUser exchanges an authorization code for user info
func (s *oidcService) ExchangeCodeForUser(providerName, code, redirectURI string) (*oidc.UserInfo, error) {
provider, err := s.manager.GetProvider(providerName)
if err != nil {
return nil, err
}
- // Exchange code for tokens
tokenResp, err := s.exchangeCode(provider, code, redirectURI)
if err != nil {
return nil, fmt.Errorf("failed to exchange code: %w", err)
}
- // Get user info
userInfo, err := s.getUserInfo(provider, tokenResp.AccessToken)
if err != nil {
return nil, fmt.Errorf("failed to get user info: %w", err)
@@ -196,7 +178,6 @@ func (s *oidcService) ExchangeCodeForUser(providerName, code, redirectURI string
return userInfo, nil
}
-// exchangeCode exchanges an authorization code for tokens
func (s *oidcService) exchangeCode(provider *oidc.Provider, code, redirectURI string) (*oidc.TokenResponse, error) {
data := url.Values{}
data.Set("grant_type", "authorization_code")
@@ -234,7 +215,6 @@ func (s *oidcService) exchangeCode(provider *oidc.Provider, code, redirectURI st
return &tokenResp, nil
}
-// getUserInfo fetches user info from the OIDC provider
func (s *oidcService) getUserInfo(provider *oidc.Provider, accessToken string) (*oidc.UserInfo, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -265,13 +245,10 @@ func (s *oidcService) getUserInfo(provider *oidc.Provider, accessToken string) (
return &userInfo, nil
}
-// LoginOrCreate attempts to login via OIDC or creates a new user
-// Returns: user, session, isNewLink (true if this is a new provider link), error
func (s *oidcService) LoginOrCreate(providerName string, userInfo *oidc.UserInfo, ip, userAgent string) (*models.User, *models.Session, bool, error) {
providerName = strings.ToLower(providerName)
- // Check if this OIDC identity is already linked to a user
link, err := s.oidcRepo.GetByProviderAndSubject(providerName, userInfo.Sub)
if err != nil {
return nil, nil, false, fmt.Errorf("failed to check OIDC link: %w", err)
@@ -283,7 +260,6 @@ func (s *oidcService) LoginOrCreate(providerName string, userInfo *oidc.UserInfo
return nil, nil, false, errors.New("linked user not found")
}
- // Create session
session, err := s.createSession(user, ip, userAgent)
if err != nil {
return nil, nil, false, err
@@ -299,12 +275,10 @@ func (s *oidcService) LoginOrCreate(providerName string, userInfo *oidc.UserInfo
return nil, nil, false, fmt.Errorf("failed to create user: %w", err)
}
- // Link the OIDC provider to the user
if err := s.LinkProvider(user.Id, providerName, userInfo.Sub); err != nil {
return nil, nil, false, fmt.Errorf("failed to link provider: %w", err)
}
- // Create session
session, err := s.createSession(user, ip, userAgent)
if err != nil {
return nil, nil, false, err
@@ -313,7 +287,6 @@ func (s *oidcService) LoginOrCreate(providerName string, userInfo *oidc.UserInfo
return user, session, true, nil
}
-// createSession creates a new session for a user
func (s *oidcService) createSession(user *models.User, ip, userAgent string) (*models.Session, error) {
session := &models.Session{
@@ -338,9 +311,8 @@ func (s *oidcService) createSession(user *models.User, ip, userAgent string) (*m
return session, nil
}
-// createUserFromOIDC creates a new user from OIDC user info
func (s *oidcService) createUserFromOIDC(userInfo *oidc.UserInfo) (*models.User, error) {
- // User object
+
userID := s.snowflake.Generate()
username := s.userService.GenerateUniqueUsername(userInfo.PreferredUsername, userID)
now := time.Now().UnixMilli()
@@ -348,7 +320,7 @@ func (s *oidcService) createUserFromOIDC(userInfo *oidc.UserInfo) (*models.User,
Id: userID,
Username: username,
Email: userInfo.Email,
- Role: 1, // Default user role
+ Role: 1,
CreatedTimestamp: now,
UpdatedTimestamp: now,
}
@@ -371,11 +343,9 @@ func (s *oidcService) createUserFromOIDC(userInfo *oidc.UserInfo) (*models.User,
return createdUser, nil
}
-// LinkProvider links an OIDC provider to an existing user
func (s *oidcService) LinkProvider(userID types.Snowflake, providerName, providerUserID string) error {
providerName = strings.ToLower(providerName)
- // Check if already linked
existing, err := s.oidcRepo.GetByProviderAndSubject(providerName, providerUserID)
if err != nil {
return fmt.Errorf("failed to check existing link: %w", err)
@@ -401,7 +371,6 @@ func (s *oidcService) LinkProvider(userID types.Snowflake, providerName, provide
return err
}
-// UnlinkProvider removes an OIDC provider link from a user
func (s *oidcService) UnlinkProvider(userID types.Snowflake, providerName string) error {
providerName = strings.ToLower(providerName)
@@ -409,7 +378,6 @@ func (s *oidcService) UnlinkProvider(userID types.Snowflake, providerName string
if err != nil {
return fmt.Errorf("failed to get user OIDC links: %w", err)
}
- // Check if user has another login method available before unlinking
userPassword, err := s.userRepo.HasPassword(userID)
if err != nil {
return errors.New("failed to get user password status")
@@ -427,7 +395,6 @@ func (s *oidcService) UnlinkProvider(userID types.Snowflake, providerName string
return errors.New("provider link not found")
}
-// GetUserProviders returns all OIDC providers linked to a user
func (s *oidcService) GetUserProviders(userID types.Snowflake) ([]*models.UserOIDCProvider, error) {
return s.oidcRepo.GetByUserID(userID)
}
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index 78a54d04..cd9de03d 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -155,7 +155,6 @@ var usernameAdjectives = []string{
}
var reg = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
-// sanitizeUsername removes or replaces invalid characters from a username
func sanitizeUsername(name string) string {
name = strings.ReplaceAll(name, " ", "_")
name = reg.ReplaceAllString(name, "")
@@ -165,7 +164,6 @@ func sanitizeUsername(name string) string {
return name
}
-// generateRandomBase generates a random username base like "Alex-Brave-1234"
func generateRandomBase() string {
randBytes := make([]byte, 2)
rand.Read(randBytes)
@@ -173,10 +171,6 @@ func generateRandomBase() string {
return fmt.Sprintf("Alex-%s", adj)
}
-// GenerateUniqueUsername generates a unique username based on a given name and user ID.
-// If givenName is nil or empty, a random username base is generated.
-// Uniqueness is guaranteed by appending the last 6 digits of the user's Snowflake ID,
-// which is already guaranteed to be unique.
func (s *userService) GenerateUniqueUsername(givenName *string, userID types.Snowflake) string {
var baseUsername string
diff --git a/backend/services/user_settings.service.go b/backend/services/user_settings.service.go
index 8ad9b9dd..9eb97baa 100644
--- a/backend/services/user_settings.service.go
+++ b/backend/services/user_settings.service.go
@@ -21,14 +21,12 @@ func NewUserSettingsService(settingsRepo repositories.UserSettingsRepository) Us
}
}
-// GetSettings returns the user settings, or an empty shell if none exist yet
func (s *userSettingsService) GetSettings(userID types.Snowflake) (*models.UserSettings, error) {
settings, err := s.settingsRepo.GetByUserID(userID)
if err != nil {
return nil, err
}
if settings == nil {
- // Return empty settings β€” the frontend will merge with its defaults
return &models.UserSettings{
UserID: userID,
General: types.JSONB{},
@@ -39,7 +37,6 @@ func (s *userSettingsService) GetSettings(userID types.Snowflake) (*models.UserS
return settings, nil
}
-// SaveSettings persists user settings (upsert)
func (s *userSettingsService) SaveSettings(settings *models.UserSettings) error {
return s.settingsRepo.Upsert(settings)
}
diff --git a/backend/types/JSON.go b/backend/types/JSON.go
index 9841bab8..eeb744e3 100644
--- a/backend/types/JSON.go
+++ b/backend/types/JSON.go
@@ -6,9 +6,9 @@ import (
"errors"
)
-type JSONB map[string]interface{}
+type JSONB map[string]any
-func (j *JSONB) Scan(value interface{}) error {
+func (j *JSONB) Scan(value any) error {
if value == nil {
*j = nil
return nil