📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
User creation & validation
Smaug#673997ec1267b2db
diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.goindex 72bfefb4..81f77d6b 100644--- a/backend/controllers/users.controller.go+++ b/backend/controllers/users.controller.go@@ -5,8 +5,10 @@ import ("Smaug6739/Alexandrie/utils""net/http""strconv"+ "time""github.com/gin-gonic/gin"+ "golang.org/x/crypto/bcrypt")func (ctr *Controller) GetUsers(c *gin.Context) {@@ -22,7 +24,7 @@ func (ctr *Controller) GetUsers(c *gin.Context) {func (ctr *Controller) GetMe(c *gin.Context) {userId, exists := c.Get("user_id")if !exists {- c.JSON(http.StatusUnauthorized, gin.H{"error": "User ID not found in context"})+ c.JSON(http.StatusUnauthorized, utils.Error("User ID not found in context"))return}user, err := ctr.model.GetUserById(userId.(int64))@@ -36,7 +38,7 @@ func (ctr *Controller) GetMe(c *gin.Context) {func (ctr *Controller) GetUserById(c *gin.Context) {id, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})+ c.JSON(http.StatusBadRequest, utils.Error("Invalid user ID"))return}user, err := ctr.model.GetUserById(id)@@ -45,7 +47,7 @@ func (ctr *Controller) GetUserById(c *gin.Context) {return}if user == nil {- c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})+ c.JSON(http.StatusNotFound, utils.Error("User not found"))return}c.JSON(http.StatusOK, utils.Success(user))@@ -53,28 +55,51 @@ func (ctr *Controller) GetUserById(c *gin.Context) {func (ctr *Controller) CreateUser(c *gin.Context) {var user models.User- if err := c.ShouldBindJSON(&user); err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})+ if err := c.ShouldBind(&user); err != nil {+ c.JSON(http.StatusBadRequest, utils.Error(err.Error()))+ return+ }++ // Specific validation for username and password+ if len(user.Password) == 0 {+ c.JSON(http.StatusBadRequest, utils.Error("Password must be provided."))+ return+ }+ exists := ctr.model.CheckUsernameExists(user.Username)+ if exists {+ c.JSON(http.StatusBadRequest, utils.Error("Username already exists."))+ 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()))return}+ createdUser.Password = "" // Remove password from responsec.JSON(http.StatusCreated, createdUser)}func (ctr *Controller) UpdateUser(c *gin.Context) {id, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})+ c.JSON(http.StatusBadRequest, utils.Error("Invalid user ID"))return}var user models.Userif err := c.ShouldBindJSON(&user); err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})+ c.JSON(http.StatusBadRequest, utils.Error("Invalid request payload"))return}@@ -89,7 +114,7 @@ func (ctr *Controller) UpdateUser(c *gin.Context) {func (ctr *Controller) UpdatePassword(c *gin.Context) {id, err := strconv.ParseInt(c.Param("id"), 10, 64)if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})+ c.JSON(http.StatusBadRequest, utils.Error("Invalid user ID"))return}var payload struct {@@ -97,12 +122,12 @@ func (ctr *Controller) UpdatePassword(c *gin.Context) {}if err := c.ShouldBindJSON(&payload); err != nil {- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request payload"})+ c.JSON(http.StatusBadRequest, utils.Error("Invalid request payload"))return}if payload.Password == "" {- c.JSON(http.StatusBadRequest, gin.H{"error": "Password must be provided"})+ c.JSON(http.StatusBadRequest, utils.Error("Password must be provided"))return}diff --git a/backend/go.mod b/backend/go.modindex 5cf13178..ff48a3bc 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -4,6 +4,11 @@ go 1.23.1require github.com/minio/minio-go v6.0.14+incompatible+require (+ github.com/davecgh/go-spew v1.1.1 // indirect+ github.com/pmezard/go-difflib v1.0.0 // indirect+)+require (filippo.io/edwards25519 v1.1.0 // indirectgithub.com/BurntSushi/toml v1.5.0 // indirect@@ -38,6 +43,7 @@ require (github.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/pelletier/go-toml/v2 v2.2.3 // indirectgithub.com/rs/xid v1.6.0 // indirect+ github.com/stretchr/testify v1.10.0github.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.12 // indirectgolang.org/x/arch v0.15.0 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 02d0ac62..ece4c644 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -12,6 +12,7 @@ github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgithub.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=@@ -72,6 +73,7 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Ggithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=@@ -85,6 +87,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=diff --git a/backend/main.go b/backend/main.goindex e2ef72c7..861955be 100644--- a/backend/main.go+++ b/backend/main.go@@ -13,30 +13,41 @@ import ("github.com/joho/godotenv")-func main() {+func SetupServer() (*gin.Engine, *app.App) {godotenv.Load()- config := app.Config{}+ // 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)}- app := app.InitApp(config)- defer app.DB.Close()- app_router := router.InitRouter(app)- // Recovery middleware recovers from any panics and writes a 500 if there was one.- app_router.Use(gin.Recovery())+ // Initialiser l'application+ application := app.InitApp(config)- app_router.SetTrustedProxies([]string{"127.0.0.1", "localhost"})+ // Créer le routeur+ appRouter := router.InitRouter(application)+ appRouter.Use(gin.Recovery())- app_router.Use(cors.New(cors.Config{+ // 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,}))- app_router.Run("localhost:8080")+ return appRouter, application+}++// main démarre le serveur en mode production+func main() {+ server, application := SetupServer()+ defer application.DB.Close()++ // Démarrer le serveur sur le port 8080+ server.Run("localhost:8080")}diff --git a/backend/models/user.model.go b/backend/models/user.model.goindex c47ff1fe..39993b8c 100644--- a/backend/models/user.model.go+++ b/backend/models/user.model.go@@ -6,16 +6,16 @@ import ()type User struct {- Id int64 `json:"id"`- Username string `json:"username"`- Firstname *string `json:"firstname"`- Lastname *string `json:"lastname"`- Role int `json:"role"` // 1: user, 2: admin- Avatar *string `json:"avatar"`- Email *string `json:"email"`- Password string `json:"password,omitempty"`- CreatedTimestamp *int64 `json:"created_timestamp"`- UpdatedTimestamp *int64 `json:"updated_timestamp"`+ Id int64 `form:"id" binding:"omitempty"`+ Username string `form:"username" binding:"required,min=5,max=30"`+ Firstname *string `form:"firstname" binding:"omitempty"`+ Lastname *string `form:"lastname" binding:"omitempty"`+ Role int `form:"role" binding:"omitempty"` // 1: user, 2: admin+ Avatar *string `form:"avatar" binding:"omitempty"`+ Email string `form:"email" binding:"required,email"`+ Password string `form:"password" json:"password,omitempty" binding:"omitempty,min=4,max=50"`+ CreatedTimestamp int64 `form:"created_timestamp" binding:"omitempty"`+ UpdatedTimestamp int64 `form:"updated_timestamp" binding:"omitempty"`}func (m *Model) GetAllUsers() ([]User, error) {@@ -62,6 +62,15 @@ func (m *Model) GetUser(id int64) (*User, error) {return &user, nil}+func (m *Model) CheckUsernameExists(username string) bool {+ var count int+ err := m.DB.QueryRow("SELECT COUNT(*) FROM users WHERE username = ?", username).Scan(&count)+ if err != nil {+ return false+ }+ return count > 0+}+func (m *Model) GetUserByUsername(username string) (*User, error) {var user Usererr := m.DB.QueryRow("SELECT id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp FROM users WHERE username = ?", username).Scan(diff --git a/backend/tests.go b/backend/tests.gonew file mode 100644index 00000000..26eee834--- /dev/null+++ b/backend/tests.go@@ -0,0 +1,57 @@+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)+}