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.

Update backend

Smaug#67391aeb7ff453d2
diff --git a/backend/controllers/authentification.controller.go b/backend/controllers/authentification.controller.go
index f3dfc6c3..992ae53e 100644
--- a/backend/controllers/authentification.controller.go
+++ b/backend/controllers/authentification.controller.go
@@ -5,6 +5,7 @@ import (
"Smaug6739/Alexandrie/utils"
"crypto/rand"
"fmt"
+ "net/http"
"os"
"strconv"
"time"
@@ -14,21 +15,28 @@ import (
"golang.org/x/crypto/bcrypt"
)
-func (dc *Controller) Login(c *gin.Context) {
- username := c.PostForm("username")
- password := c.PostForm("password")
+type AuthClaims struct {
+ Username string `form:"username"`
+ Password string `form:"password"`
+}
- if username == "" || password == "" {
+func (dc *Controller) Login(c *gin.Context) {
+ var authClaims AuthClaims
+ if err := c.ShouldBind(&authClaims); err != nil {
+ c.JSON(http.StatusBadRequest, utils.Error(err.Error()))
+ return
+ }
+ if authClaims.Username == "" || authClaims.Password == "" {
c.JSON(400, utils.Error("Invalid credentials."))
return
}
- user, err := dc.model.GetUserByUsername(username)
+ user, err := dc.model.GetUserByUsername(authClaims.Username)
if user == nil || err != nil {
c.JSON(401, utils.Error("Invalid credentials."))
return
}
- if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
+ if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authClaims.Password)); err != nil {
c.JSON(401, utils.Error("Invalid credentials."))
return
}
diff --git a/backend/controllers/documents.controller.go b/backend/controllers/documents.controller.go
index 90462784..7d11a445 100644
--- a/backend/controllers/documents.controller.go
+++ b/backend/controllers/documents.controller.go
@@ -9,11 +9,7 @@ import (
)
func (ctr *Controller) GetAllDocuments(c *gin.Context) {
- userId, exists := c.Get("user_id")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
+ userId, _ := c.Get("user_id")
documents, err := ctr.model.GetAllDocuments(userId.(int64))
if err != nil {
@@ -24,11 +20,7 @@ func (ctr *Controller) GetAllDocuments(c *gin.Context) {
}
func (ctr *Controller) GetDocument(c *gin.Context) {
- userId, exists := c.Get("user_id")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
+ userId, _ := c.Get("user_id")
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid document ID"})
@@ -47,11 +39,8 @@ func (ctr *Controller) GetDocument(c *gin.Context) {
}
func (ctr *Controller) AddDocument(c *gin.Context) {
- userId, exists := c.Get("user_id")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
+ userId, _ := c.Get("user_id")
+
var document models.Document
if err := c.ShouldBindJSON(&document); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
@@ -68,13 +57,7 @@ func (ctr *Controller) AddDocument(c *gin.Context) {
}
func (ctr *Controller) UpdateDocument(c *gin.Context) {
- claims, exists := c.Get("claims")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
- return
- }
-
- userId, _ := claims.(map[string]interface{})["user_id"].(float64)
+ userId, _ := c.Get("user_id")
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid document ID"})
@@ -85,7 +68,7 @@ func (ctr *Controller) UpdateDocument(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})
return
}
- dbDoc, err := ctr.model.GetDocument(id, int64(userId))
+ dbDoc, err := ctr.model.GetDocument(id, userId.(int64))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -104,15 +87,13 @@ func (ctr *Controller) UpdateDocument(c *gin.Context) {
}
func (ctr *Controller) DeleteDocument(c *gin.Context) {
- claims, exists := c.Get("claims")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
+ userId, _ := c.Get("user_id")
+ id, err := strconv.ParseInt(c.Param("id"), 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid document ID"})
return
}
-
- userId, _ := claims.(map[string]interface{})["user_id"].(float64)
- id, err := strconv.ParseInt(c.Param("id"), 10, 64)
- dbDoc, err := ctr.model.GetDocument(id, int64(userId))
+ dbDoc, err := ctr.model.GetDocument(id, userId.(int64))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.go
index 81f77d6b..a0535180 100644
--- a/backend/controllers/users.controller.go
+++ b/backend/controllers/users.controller.go
@@ -1,6 +1,7 @@
package controllers
import (
+ "Smaug6739/Alexandrie/app"
"Smaug6739/Alexandrie/models"
"Smaug6739/Alexandrie/utils"
"net/http"
@@ -11,8 +12,31 @@ import (
"golang.org/x/crypto/bcrypt"
)
-func (ctr *Controller) GetUsers(c *gin.Context) {
+type UserController interface {
+ GetUsers(c *gin.Context)
+ GetMe(c *gin.Context)
+ GetUserById(c *gin.Context)
+ CreateUser(c *gin.Context)
+ UpdateUser(c *gin.Context)
+ UpdatePassword(c *gin.Context)
+}
+
+func NewUserController(app *app.App) UserController {
+ return &Controller{
+ app: app,
+ model: models.NewModel(app.DB),
+ }
+}
+// Get Users
+// @Summary Get all users
+// @Method GET
+// @Router /users [get]
+// @Security Authenfification: Auth, Admin
+// @Success 200 {object} Success([]models.User)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) GetUsers(c *gin.Context) {
users, err := ctr.model.GetAllUsers()
if err != nil {
c.JSON(http.StatusInternalServerError, utils.Error(err.Error()))
@@ -21,6 +45,14 @@ func (ctr *Controller) GetUsers(c *gin.Context) {
c.JSON(http.StatusOK, users)
}
+// GetMe
+// @Summary Get current user information
+// @Method GET
+// @Router /users/@me [get]
+// @Security Authenfification: Auth
+// @Success 200 {object} Success(models.User)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
func (ctr *Controller) GetMe(c *gin.Context) {
userId, exists := c.Get("user_id")
if !exists {
@@ -35,6 +67,15 @@ func (ctr *Controller) GetMe(c *gin.Context) {
c.JSON(http.StatusOK, utils.Success(user))
}
+// Get User by ID
+// @Summary Get user by ID
+// @Method GET
+// @Router /users/{id} [get]
+// @Security Authenfification: Auth, Admin
+// @Param id path int true "User ID"
+// @Success 200 {object} Success(models.User)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
func (ctr *Controller) GetUserById(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
@@ -53,13 +94,37 @@ func (ctr *Controller) GetUserById(c *gin.Context) {
c.JSON(http.StatusOK, utils.Success(user))
}
+// Create User
+// @Summary Create a new user
+// @Method POST
+// @Router /users [post]
+// @Security None
+// @Body Username*, Firstname, Lastname, Avatar, Role, Email*, Password*
+// @Success 201 {object} Success(models.User)
+// @Failure 400 {object} Error
func (ctr *Controller) CreateUser(c *gin.Context) {
var user models.User
if err := c.ShouldBind(&user); err != nil {
c.JSON(http.StatusBadRequest, utils.Error(err.Error()))
return
}
-
+ hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, utils.Error("Failed to hash password"))
+ return
+ }
+ user = models.User{
+ Id: ctr.app.Snowflake.Generate(),
+ Username: user.Username,
+ Firstname: user.Firstname,
+ Lastname: user.Lastname,
+ Avatar: user.Avatar,
+ Role: 1,
+ Email: user.Email,
+ Password: string(hash),
+ CreatedTimestamp: time.Now().UnixMilli(),
+ UpdatedTimestamp: time.Now().UnixMilli(),
+ }
// Specific validation for username and password
if len(user.Password) == 0 {
c.JSON(http.StatusBadRequest, utils.Error("Password must be provided."))
@@ -71,17 +136,6 @@ func (ctr *Controller) CreateUser(c *gin.Context) {
return
}
- user.Id = ctr.app.Snowflake.Generate()
- user.CreatedTimestamp = time.Now().UnixMilli()
- user.UpdatedTimestamp = time.Now().UnixMilli()
- user.Role = 1 // Default role
- hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
- if err != nil {
- c.JSON(http.StatusInternalServerError, utils.Error("Failed to hash password"))
- return
- }
- user.Password = string(hash)
-
createdUser, err := ctr.model.CreateUser(user)
if err != nil {
c.JSON(http.StatusInternalServerError, utils.Error(err.Error()))
@@ -91,6 +145,16 @@ func (ctr *Controller) CreateUser(c *gin.Context) {
c.JSON(http.StatusCreated, createdUser)
}
+// Update User
+// @Summary Update user information
+// @Method PATCH
+// @Router /users/{id} [patch]
+// @Security Authenfification: Auth
+// @Param id path int true "User ID"
+// @Body Username, Firstname, Lastname, Avatar, Role, Email
+// @Success 200 {object} Success(models.User)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
func (ctr *Controller) UpdateUser(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
@@ -102,7 +166,6 @@ func (ctr *Controller) UpdateUser(c *gin.Context) {
c.JSON(http.StatusBadRequest, utils.Error("Invalid request payload"))
return
}
-
updatedUser, err := ctr.model.UpdateUser(id, user)
if err != nil {
c.JSON(http.StatusInternalServerError, utils.Error(err.Error()))
@@ -120,17 +183,14 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) {
var payload struct {
Password string `json:"password"`
}
-
if err := c.ShouldBindJSON(&payload); err != nil {
c.JSON(http.StatusBadRequest, utils.Error("Invalid request payload"))
return
}
-
if payload.Password == "" {
c.JSON(http.StatusBadRequest, utils.Error("Password must be provided"))
return
}
-
err = ctr.model.UpdatePassword(id, payload.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, utils.Error(err.Error()))
diff --git a/backend/main.go b/backend/main.go
index 861955be..40e42eab 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -1,51 +1,9 @@
package main
-import (
- "Smaug6739/Alexandrie/app"
- "Smaug6739/Alexandrie/router"
- "fmt"
- "os"
+import "Smaug6739/Alexandrie/server"
- "github.com/BurntSushi/toml"
- "github.com/gin-contrib/cors"
- "github.com/gin-gonic/gin"
- _ "github.com/go-sql-driver/mysql"
- "github.com/joho/godotenv"
-)
-
-func SetupServer() (*gin.Engine, *app.App) {
- godotenv.Load()
-
- // Charger la configuration depuis config.toml
- config := app.Config{}
- _, err := toml.DecodeFile("config.toml", &config)
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
-
- // Initialiser l'application
- application := app.InitApp(config)
-
- // Créer le routeur
- appRouter := router.InitRouter(application)
- appRouter.Use(gin.Recovery())
-
- // Configurer les proxys et CORS
- appRouter.SetTrustedProxies([]string{"127.0.0.1", "localhost"})
- appRouter.Use(cors.New(cors.Config{
- AllowOrigins: []string{os.Getenv("DOMAIN_CLIENT")},
- AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
- ExposeHeaders: []string{"Content-Length"},
- AllowCredentials: true,
- }))
-
- return appRouter, application
-}
-
-// main démarre le serveur en mode production
func main() {
- server, application := SetupServer()
+ server, application := server.SetupServer()
defer application.DB.Close()
// Démarrer le serveur sur le port 8080
diff --git a/backend/main_test.go b/backend/main_test.go
new file mode 100644
index 00000000..961f5f15
--- /dev/null
+++ b/backend/main_test.go
@@ -0,0 +1,78 @@
+package main
+
+import (
+ "Smaug6739/Alexandrie/server"
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "golang.org/x/net/publicsuffix"
+)
+
+// Démarrer le vrai serveur Gin en arrière-plan
+func startTestServer() *httptest.Server {
+ router, _ := server.SetupServer()
+ return httptest.NewServer(router)
+}
+
+func TestFullAuthenticationFlow(t *testing.T) {
+ fmt.Println("Starting test...")
+ // 1. Lancer le serveur de test
+ ts := startTestServer()
+ defer ts.Close()
+
+ // 2. Créer un client HTTP avec un cookiejar pour gérer les cookies comme un navigateur
+ options := &cookiejar.Options{PublicSuffixList: publicsuffix.List}
+ jar, _ := cookiejar.New(options)
+ client := &http.Client{Jar: jar}
+
+ t.Run("Login", func(t *testing.T) {
+ loginURL := ts.URL + "/api/auth"
+ loginData := map[string]string{"username": "Hacker", "password": "10082005"}
+ resp, body := PerformRequest(t, client, "POST", loginURL, loginData)
+ assert.Equal(t, http.StatusOK, resp.StatusCode)
+ assert.Contains(t, body, "\"status\":\"success\"")
+ })
+ t.Run("Protected", func(t *testing.T) {
+ resp, body := PerformRequest(t, client, "GET", ts.URL+"/api/users/@me", nil)
+ assert.Equal(t, http.StatusOK, resp.StatusCode)
+ assert.Contains(t, body, "\"status\":\"success\"")
+ })
+
+}
+
+// CreateTestClient creates an HTTP client with a cookie jar.
+func CreateTestClient() *http.Client {
+ options := &cookiejar.Options{PublicSuffixList: publicsuffix.List}
+ jar, _ := cookiejar.New(options)
+ return &http.Client{Jar: jar}
+}
+
+// PerformRequest performs an HTTP request and returns the response and body.
+func PerformRequest(t *testing.T, client *http.Client, method, url string, body interface{}) (*http.Response, string) {
+ var reqBody io.Reader
+ if body != nil {
+ jsonData, err := json.Marshal(body)
+ assert.NoError(t, err)
+ reqBody = bytes.NewBuffer(jsonData)
+ }
+
+ req, err := http.NewRequest(method, url, reqBody)
+ assert.NoError(t, err)
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := client.Do(req)
+ assert.NoError(t, err)
+
+ respBody, err := io.ReadAll(resp.Body)
+ assert.NoError(t, err)
+ defer resp.Body.Close()
+
+ return resp, string(respBody)
+}
diff --git a/backend/models/user.model.go b/backend/models/user.model.go
index 39993b8c..2b184bab 100644
--- a/backend/models/user.model.go
+++ b/backend/models/user.model.go
@@ -18,6 +18,22 @@ type User struct {
UpdatedTimestamp int64 `form:"updated_timestamp" binding:"omitempty"`
}
+type UserService interface {
+ GetAllUsers() ([]User, error)
+ GetUser(id int64) (*User, error)
+ CheckUsernameExists(username string) bool
+ GetUserByUsername(username string) (*User, error)
+ GetUserById(id int64) (*User, error)
+ CreateUser(user User) (*User, error)
+ UpdateUser(id int64, user User) (*User, error)
+ UpdatePassword(id int64, password string) error
+ DeleteUser(id int64) error
+}
+
+func NewUserService(db *sql.DB) UserService {
+ return &Model{DB: db}
+}
+
func (m *Model) GetAllUsers() ([]User, error) {
var users []User
rows, err := m.DB.Query("SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp FROM users ORDER BY created_timestamp DESC")
diff --git a/backend/router/routes/users.go b/backend/router/routes/users.go
index c43641e4..6dedaff5 100644
--- a/backend/router/routes/users.go
+++ b/backend/router/routes/users.go
@@ -10,14 +10,14 @@ import (
func Users(app *app.App, router *gin.RouterGroup) {
usr := router.Group("/users")
- usrCtrl := controllers.NewController(app)
+ usrCtrl := controllers.NewUserController(app)
- usr.Use(middlewares.Auth())
+ usr.Use()
- usr.GET("/", middlewares.Admin(), usrCtrl.GetUsers)
- usr.GET("/@me", usrCtrl.GetMe)
- usr.GET("/:id", middlewares.Admin(), usrCtrl.GetUserById)
+ usr.GET("/", middlewares.Auth(), middlewares.Admin(), usrCtrl.GetUsers)
+ usr.GET("/@me", middlewares.Auth(), usrCtrl.GetMe)
+ usr.GET("/:id", middlewares.Auth(), middlewares.Admin(), usrCtrl.GetUserById)
usr.POST("/", usrCtrl.CreateUser)
- usr.PATCH("/:id", usrCtrl.UpdateUser)
- usr.PATCH("/:id/password", usrCtrl.UpdatePassword)
+ usr.PATCH("/:id", middlewares.Auth(), usrCtrl.UpdateUser)
+ usr.PATCH("/:id/password", middlewares.Auth(), usrCtrl.UpdatePassword)
}
diff --git a/backend/server/server.go b/backend/server/server.go
new file mode 100644
index 00000000..70dc7b6c
--- /dev/null
+++ b/backend/server/server.go
@@ -0,0 +1,44 @@
+package server
+
+import (
+ "Smaug6739/Alexandrie/app"
+ "Smaug6739/Alexandrie/router"
+ "fmt"
+ "os"
+
+ "github.com/BurntSushi/toml"
+ "github.com/gin-contrib/cors"
+ "github.com/gin-gonic/gin"
+ _ "github.com/go-sql-driver/mysql"
+ "github.com/joho/godotenv"
+)
+
+func SetupServer() (*gin.Engine, *app.App) {
+ godotenv.Load()
+
+ // Charger la configuration depuis config.toml
+ config := app.Config{}
+ _, err := toml.DecodeFile("config.toml", &config)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+
+ // Initialiser l'application
+ application := app.InitApp(config)
+
+ // Créer le routeur
+ appRouter := router.InitRouter(application)
+ appRouter.Use(gin.Recovery())
+
+ // Configurer les proxys et CORS
+ appRouter.SetTrustedProxies([]string{"127.0.0.1", "localhost"})
+ appRouter.Use(cors.New(cors.Config{
+ AllowOrigins: []string{os.Getenv("DOMAIN_CLIENT")},
+ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
+ ExposeHeaders: []string{"Content-Length"},
+ AllowCredentials: true,
+ }))
+
+ return appRouter, application
+}
diff --git a/backend/services/services.go b/backend/services/services.go
new file mode 100644
index 00000000..21b39eac
--- /dev/null
+++ b/backend/services/services.go
@@ -0,0 +1,11 @@
+package service
+
+import "database/sql"
+
+type Service struct {
+ db *sql.DB
+}
+
+func New(db *sql.DB) *Service {
+ return &Service{db: db}
+}
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
new file mode 100644
index 00000000..0b8f142a
--- /dev/null
+++ b/backend/services/user.service.go
@@ -0,0 +1,80 @@
+package service
+
+import (
+ "Smaug6739/Alexandrie/models"
+ "database/sql"
+)
+
+type UserService interface {
+ GetAllUsers() ([]*models.User, error)
+ GetUserById(id int64) (*models.User, error)
+ CreateUser(user *models.User) (*models.User, error)
+ UpdateUser(user *models.User) (*models.User, error)
+ UpdatePassword(id int64, password string) error
+ DeleteUser(id int64) error
+}
+
+func NewUserService(db *sql.DB) UserService {
+ return &Service{db: db}
+}
+
+func (s *Service) GetAllUsers() ([]*models.User, error) {
+ var users []*models.User
+ rows, err := s.db.Query("SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp FROM users")
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var user models.User
+ if err := rows.Scan(&user.Id, &user.Username, &user.Firstname, &user.Lastname,
+ &user.Role, &user.Avatar, &user.Email, &user.CreatedTimestamp, &user.UpdatedTimestamp); err != nil {
+ return nil, err
+ }
+ users = append(users, &user)
+ }
+ return users, nil
+}
+func (s *Service) CreateUser(user *models.User) (*models.User, error) {
+ _, err := s.db.Exec("INSERT INTO users (id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ user.Id, user.Username, user.Firstname, user.Lastname, user.Role, user.Avatar, user.Email, user.Password, user.CreatedTimestamp, user.UpdatedTimestamp)
+ if err != nil {
+ return nil, err
+ }
+
+ return user, nil
+}
+
+func (s *Service) GetUserById(id int64) (*models.User, error) {
+ var user models.User
+ err := s.db.QueryRow("SELECT id, username, firstname, lastname, role, avatar, email, created_timestamp, updated_timestamp FROM users WHERE id = ?", id).Scan(
+ &user.Id, &user.Username, &user.Firstname, &user.Lastname,
+ &user.Role, &user.Avatar, &user.Email, &user.CreatedTimestamp, &user.UpdatedTimestamp,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ return &user, nil
+}
+
+func (s *Service) UpdateUser(user *models.User) (*models.User, error) {
+ _, err := s.db.Exec("UPDATE users SET username=?, firstname=?, lastname=?, role=?, avatar=?, email=?, updated_timestamp=? WHERE id=?",
+ user.Username, user.Firstname, user.Lastname, user.Role, user.Avatar, user.Email, user.UpdatedTimestamp, user.Id)
+ if err != nil {
+ return nil, err
+ }
+ return user, nil
+}
+
+func (s *Service) UpdatePassword(id int64, password string) error {
+ _, err := s.db.Exec("UPDATE users SET password=? WHERE id=?", password, id)
+ return err
+}
+
+func (s *Service) DeleteUser(id int64) error {
+ _, err := s.db.Exec("DELETE FROM users WHERE id=?", id)
+ return err
+}
diff --git a/backend/tests.go b/backend/tests.go
deleted file mode 100644
index 26eee834..00000000
--- a/backend/tests.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package main
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "net/http/cookiejar"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
- "golang.org/x/net/publicsuffix"
-)
-
-// Démarrer le vrai serveur Gin en arrière-plan
-func startTestServer() *httptest.Server {
- router, _ := SetupServer()
- return httptest.NewServer(router)
-}
-
-func TestFullAuthenticationFlow(t *testing.T) {
- // 1. Lancer le serveur de test
- ts := startTestServer()
- defer ts.Close()
-
- // 2. Créer un client HTTP avec un cookiejar pour gérer les cookies comme un navigateur
- options := &cookiejar.Options{PublicSuffixList: publicsuffix.List}
- jar, _ := cookiejar.New(options)
- client := &http.Client{Jar: jar}
-
- // 3. Simuler un utilisateur qui s'inscrit (si besoin)
- loginURL := ts.URL + "/login" // Remplace par ton vrai endpoint
- signupData, _ := json.Marshal(map[string]string{"username": "Hacker", "password": "10082005"})
- loginReq, _ := http.NewRequest("POST", loginURL, bytes.NewBuffer(signupData))
- loginReq.Header.Set("Content-Type", "application/json")
-
- loginResp, _ := client.Do(loginReq)
- assert.Equal(t, http.StatusOK, loginResp.StatusCode)
-
- // 6. Attendre un peu (optionnel, si test d'expiration)
- time.Sleep(1 * time.Second)
-
- // 7. Accéder à une route protégée en utilisant le cookie JWT
- protectedURL := ts.URL + "/users/@me"
- protectedReq, _ := http.NewRequest("GET", protectedURL, nil)
-
- protectedResp, _ := client.Do(protectedReq)
- body, _ := io.ReadAll(protectedResp.Body)
- defer protectedResp.Body.Close()
- fmt.Println(string(body))
-
- // 8. Vérifier que l’accès est autorisé
- assert.Equal(t, http.StatusOK, protectedResp.StatusCode)
-}
diff --git a/backend/utils/responses.go b/backend/utils/responses.go
index 59b1940e..7aa2d101 100644
--- a/backend/utils/responses.go
+++ b/backend/utils/responses.go
@@ -21,3 +21,14 @@ func Error(message string) gin.H {
"message": message,
}
}
+
+func HandleResponse(c *gin.Context, code int, body any) bool {
+ // If it's an error, we need to set the status code and return the error message
+ // body is of type error if it's an error, otherwise it's an interface{}
+ if err, ok := body.(error); ok {
+ c.JSON(code, Error(err.Error()))
+ } else {
+ c.JSON(code, Success(body))
+ }
+ return true
+}