📚 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
Setup auth system
Smaug67399fed9fc04d6a
diff --git a/backend-old/controllers/article.controller.go b/backend-old/controllers/article.controller.godeleted file mode 100644index 6661f733..00000000--- a/backend-old/controllers/article.controller.go+++ /dev/null@@ -1,27 +0,0 @@-package controllers--import (- "net/http"-- "github.com/gin-gonic/gin"-)---type Person struct {- Name string- Age int- City string- Pincode int-}--func GetDocument(c *gin.Context) {- data := Person{- Name: "Mark",- Age: 30,- City: "NY",- Pincode: 777,- }- c.JSON(http.StatusOK, gin.H{- "Data": data,- })-}diff --git a/backend-old/go.mod b/backend-old/go.moddeleted file mode 100644index d8a76cfa..00000000--- a/backend-old/go.mod+++ /dev/null@@ -1,35 +0,0 @@-module Smaug6739/Alexandrie--go 1.23.1--require (- filippo.io/edwards25519 v1.1.0 // indirect- github.com/bytedance/sonic v1.13.1 // indirect- github.com/bytedance/sonic/loader v0.2.4 // indirect- github.com/cloudwego/base64x v0.1.5 // indirect- github.com/cloudwego/iasm v0.2.0 // indirect- github.com/gabriel-vasile/mimetype v1.4.8 // indirect- github.com/gin-contrib/sse v1.0.0 // indirect- github.com/gin-gonic/gin v1.10.0 // indirect- github.com/go-playground/locales v0.14.1 // indirect- github.com/go-playground/universal-translator v0.18.1 // indirect- github.com/go-playground/validator/v10 v10.25.0 // indirect- github.com/go-sql-driver/mysql v1.9.1 // indirect- github.com/goccy/go-json v0.10.5 // indirect- github.com/json-iterator/go v1.1.12 // indirect- github.com/klauspost/cpuid/v2 v2.2.10 // indirect- github.com/leodido/go-urn v1.4.0 // indirect- github.com/mattn/go-isatty v0.0.20 // indirect- github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect- github.com/modern-go/reflect2 v1.0.2 // indirect- github.com/pelletier/go-toml/v2 v2.2.3 // indirect- github.com/twitchyliquid64/golang-asm v0.15.1 // indirect- github.com/ugorji/go/codec v1.2.12 // indirect- golang.org/x/arch v0.15.0 // indirect- golang.org/x/crypto v0.36.0 // indirect- golang.org/x/net v0.37.0 // indirect- golang.org/x/sys v0.31.0 // indirect- golang.org/x/text v0.23.0 // indirect- google.golang.org/protobuf v1.36.5 // indirect- gopkg.in/yaml.v3 v3.0.1 // indirect-)diff --git a/backend-old/go.sum b/backend-old/go.sumdeleted file mode 100644index 8a5584c9..00000000--- a/backend-old/go.sum+++ /dev/null@@ -1,82 +0,0 @@-filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=-filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=-github.com/bytedance/sonic v1.13.1 h1:Jyd5CIvdFnkOWuKXr+wm4Nyk2h0yAFsr8ucJgEasO3g=-github.com/bytedance/sonic v1.13.1/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=-github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=-github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=-github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=-github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=-github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=-github.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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=-github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=-github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=-github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=-github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=-github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=-github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=-github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=-github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=-github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=-github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=-github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=-github.com/go-sql-driver/mysql v1.9.1 h1:FrjNGn/BsJQjVRuSa8CBrM5BWA9BWoXXat3KrtSb/iI=-github.com/go-sql-driver/mysql v1.9.1/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=-github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=-github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=-github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=-github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=-github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=-github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=-github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=-github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=-github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=-github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=-github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=-github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=-github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=-github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=-github.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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=-github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=-github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=-github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=-github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=-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/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=-github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=-github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=-golang.org/x/arch v0.15.0 h1:QtOrQd0bTUnhNVNndMpLHNWrDmYzZ2KDqSrEymqInZw=-golang.org/x/arch v0.15.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE=-golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=-golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=-golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=-golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=-golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=-golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=-golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=-google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=-google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=-gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=-gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=-nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=-rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=diff --git a/backend-old/main.go b/backend-old/main.godeleted file mode 100644index f8d8595b..00000000--- a/backend-old/main.go+++ /dev/null@@ -1,72 +0,0 @@-package main--import (- "database/sql"- "fmt"- "time"-- _ "github.com/go-sql-driver/mysql"-)--func DBConection() (conecction *sql.DB) {- Driver := "mysql"- User := "root"- Password := "root"- Host := "localhost"- Port := "3306"- Database := "alexandrie"-- conection, err := sql.Open(Driver, User+":"+Password+"@tcp("+Host+":"+Port+")/"+Database)-- if err != nil {- panic(err.Error())- }- conection.SetConnMaxLifetime(time.Minute * 3)- conection.SetMaxOpenConns(10)- conection.SetMaxIdleConns(10)- return conection-}-func main() {- db := DBConection()- defer db.Close()--rows, err := db.Query("SELECT * FROM users")- if err != nil {- // handle error- fmt.Println(err)- panic(err)- }- defer rows.Close()-- // process the query results- for rows.Next() {- // scan the row into a variable- var id int- var username string- var firstname string- var lastname string- var role string- var avatar string- var email string- var password string- var created_timestamp string- var updated_timestamp string- err = rows.Scan(&id, &username, &firstname,&lastname,&role,&avatar,&email,&password,&created_timestamp,&updated_timestamp)- if err != nil {- // handle error- }-- // do something with the data- fmt.Printf("id: %d, name: %s\n", id, username)- }-- // check for errors from iterating over rows.Next()- if err = rows.Err(); err != nil {- // handle error- }-- //router.Init()---}-diff --git a/backend-old/router/router.go b/backend-old/router/router.godeleted file mode 100644index 96175006..00000000--- a/backend-old/router/router.go+++ /dev/null@@ -1,19 +0,0 @@-package router--import (- documents "Smaug6739/Alexandrie/router/routes"-- "github.com/gin-gonic/gin"-)--func Init() {- router := NewRouter()- router.Run("localhost:8080")-}--func NewRouter() *gin.Engine {- router := gin.New()- mainGroup := router.Group("/api")- documents.Routes(mainGroup)- return router-}\ No newline at end of filediff --git a/backend-old/router/routes/documents.go b/backend-old/router/routes/documents.godeleted file mode 100644index 8d29f09a..00000000--- a/backend-old/router/routes/documents.go+++ /dev/null@@ -1,14 +0,0 @@-package documents--import (- "Smaug6739/Alexandrie/controllers"-- "github.com/gin-gonic/gin"-)--func Routes(router *gin.RouterGroup) {- documents := router.Group("/documents")-- documents.GET("/", controllers.GetDocument)--}\ No newline at end of filediff --git a/backend-old/utils/responses.go b/backend-old/utils/responses.godeleted file mode 100644index a6fe71bc..00000000--- a/backend-old/utils/responses.go+++ /dev/null@@ -1,35 +0,0 @@-package utils--import (- "time"-)---type internal_success struct {- status string- result any- timestamp int64-}-type internal_error struct {- status string- message string- timestamp int64-}----func Success(data any) internal_success {- return internal_success{- status: "success",- result: data,- timestamp: time.Now().UnixMilli(),- }-}--func Error(message string) internal_error {- return internal_error{- status: "error",- message: message,- timestamp: time.Now().UnixMilli(),- }-}\ No newline at end of filediff --git a/backend/app/app.go b/backend/app/app.gonew file mode 100644index 00000000..37f1f20d--- /dev/null+++ b/backend/app/app.go@@ -0,0 +1,21 @@+package app++import (+ "Smaug6739/Alexandrie/utils"+ "database/sql"++ _ "github.com/go-sql-driver/mysql"+)++type App struct {+ DB *sql.DB+ Snowflake *utils.Snowflake+}++func InitApp() *App {+ var app App+ app.DB = DBConection()+ app.Snowflake = utils.NewSnowflake(1609459200000)++ return &app+}diff --git a/backend/app/database.go b/backend/app/database.gonew file mode 100644index 00000000..0c878e2a--- /dev/null+++ b/backend/app/database.go@@ -0,0 +1,25 @@+package app++import (+ "database/sql"+ "time"+)++func DBConection() (conecction *sql.DB) {+ Driver := "mysql"+ User := "root"+ Password := "root"+ Host := "localhost"+ Port := "3306"+ Database := "alexandrie"++ conection, err := sql.Open(Driver, User+":"+Password+"@tcp("+Host+":"+Port+")/"+Database)++ if err != nil {+ panic(err.Error())+ }+ conection.SetConnMaxLifetime(time.Minute * 3)+ conection.SetMaxOpenConns(10)+ conection.SetMaxIdleConns(10)+ return conection+}diff --git a/backend/app/logger.go b/backend/app/logger.gonew file mode 100644index 00000000..4879f7a4--- /dev/null+++ b/backend/app/logger.go@@ -0,0 +1 @@+package appdiff --git a/backend/controllers/article.controller.go b/backend/controllers/article.controller.godeleted file mode 100644index 6661f733..00000000--- a/backend/controllers/article.controller.go+++ /dev/null@@ -1,27 +0,0 @@-package controllers--import (- "net/http"-- "github.com/gin-gonic/gin"-)---type Person struct {- Name string- Age int- City string- Pincode int-}--func GetDocument(c *gin.Context) {- data := Person{- Name: "Mark",- Age: 30,- City: "NY",- Pincode: 777,- }- c.JSON(http.StatusOK, gin.H{- "Data": data,- })-}diff --git a/backend/controllers/authentification.controller.go b/backend/controllers/authentification.controller.gonew file mode 100644index 00000000..2c4de971--- /dev/null+++ b/backend/controllers/authentification.controller.go@@ -0,0 +1,144 @@+package controllers++import (+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/models"+ "crypto/rand"+ "fmt"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/golang-jwt/jwt/v5"+ "golang.org/x/crypto/bcrypt"+)++type AuthController struct {+ app *app.App+ model *models.Model+}++var refresh_token_expiration = 7 * 24 * 60 * 60 * 1000 // 7 days++func NewAuthController(app *app.App) *AuthController {+ return &AuthController{+ app: app,+ model: models.NewModel(app.DB),+ }+}++// Connexion:+// L'utilisateur fournit son nom d'utilisateur et son mot de passe.+// Si les informations sont correctes, un token JWT est généré et renvoyé à l'utilisateur.+// On signe également un refresh token (chaine aléatoire) et on le stocke en base de données dans une (Session) table.+// On set un cookie avec le refresh token & l'access token.+// On renvoit l'User sans le mot de passe.++func (dc *AuthController) Login(c *gin.Context) {+ username := c.PostForm("username")+ password := c.PostForm("password")++ fmt.Println(username, password)++ if username == "" || password == "" {+ c.JSON(400, gin.H{"error": "Invalid credentials. 1"})+ return+ }+ user := dc.model.GetUserByUsername(username)++ macth_err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))++ if macth_err != nil {+ c.JSON(401, gin.H{"error": "Invalid credentials."})+ return+ }+ tokenString, err := dc.signAccessToken(user)+ if err != nil {+ fmt.Println(err.Error())+ c.JSON(500, gin.H{"error": "Failed to sign token."})++ return+ }++ // Create a new session+ session := models.Session{+ Id: dc.app.Snowflake.Generate(),+ UserId: user.Id,+ RefreshToken: signRefreshToken(),+ ExpireToken: time.Now().Add(time.Duration(refresh_token_expiration * 1000)).UnixMilli(),+ LastRefreshTimestamp: time.Now().UnixMilli(),+ Active: 1,+ LoginTimestamp: time.Now().UnixMilli(),+ LogoutTimestamp: 0,+ }+ _, errs := dc.model.CreateSession(&session)+ if errs != nil {+ c.JSON(500, gin.H{"error": "Failed to create session."})+ return+ }++ c.SetCookie("Authorization", tokenString, 1800, "/", "localhost", false, true) // TODO: Replace with config+ c.SetCookie("RefreshToken", session.RefreshToken, int(time.Duration(refresh_token_expiration).Seconds()), "/", "localhost", false, true)++ c.JSON(200, gin.H{"message": "Login successful"})++}++func (dc *AuthController) RefreshSession(c *gin.Context) {+ // Get the refresh token from the cookie+ refreshToken, err := c.Cookie("RefreshToken")+ if err != nil {+ c.JSON(401, gin.H{"error": "No refresh token provided."})+ return+ }+ session, err := dc.model.GetSession(refreshToken)+ if err != nil {+ c.JSON(401, gin.H{"error": "Invalid refresh token."})+ return+ }+ if session.ExpireToken < time.Now().UnixMilli() {+ c.JSON(401, gin.H{"error": "Refresh token expired."})+ return+ }+ // Generate a new access token+ user := dc.model.GetUserById(session.UserId)+ tokenString, err := dc.signAccessToken(user)+ if err != nil {+ c.JSON(500, gin.H{"error": "Failed to sign token."})+ return+ }+ // Update the session+ session.RefreshToken = signRefreshToken()+ session.ExpireToken = time.Now().Add(time.Duration(refresh_token_expiration)).UnixMilli()+ session.LastRefreshTimestamp = time.Now().UnixMilli()+ _, err = dc.model.UpdateSession(&session)+ if err != nil {+ c.JSON(500, gin.H{"error": "Failed to update session."})+ return+ }+ c.SetCookie("Authorization", tokenString, 1800, "/", "localhost", false, true) // TODO: Replace with config+ c.SetCookie("RefreshToken", session.RefreshToken, int(time.Duration(refresh_token_expiration).Seconds()), "/", "localhost", false, true)+ c.JSON(200, gin.H{"message": "Token refreshed."})++}++func (dc *AuthController) signAccessToken(user models.User) (string, error) {+ claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{+ "sub": user.Username, // Subject (user identifier)+ "iss": "alexandrie", // Issuer+ "aud": user.Role, // Audience (user role)+ "exp": time.Now().Add(time.Hour).Unix(), // Expiration time // TODO: Replace with config+ "iat": time.Now().Unix(), // Issued at+ })+ tokenString, err := claims.SignedString([]byte("secretKey")) // TODO: Replace with config+ if err != nil {+ return "", err+ }+ return tokenString, nil+}++// Crypto create random string hex 64+func signRefreshToken() string {+ randBytes := make([]byte, 45)+ rand.Read(randBytes)+ return fmt.Sprintf("%x", randBytes)+}diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.gonew file mode 100644index 00000000..a1e47abb--- /dev/null+++ b/backend/controllers/users.controller.go@@ -0,0 +1,31 @@+package controllers++import (+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/models"+ "net/http"++ "github.com/gin-gonic/gin"+)++type UserController struct {+ app *app.App+ user_model *models.Model+}++func NewUserController(app *app.App) *UserController {+ return &UserController{+ app: app,+ user_model: models.NewModel(app.DB),+ }+}++func (ctr *UserController) GetUsers(c *gin.Context) {++ users, err := ctr.user_model.GetAllUsers()+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})+ return+ }+ c.JSON(http.StatusOK, users)+}diff --git a/backend/go.mod b/backend/go.modindex 4ed5fa1a..605fe4ae 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -3,6 +3,7 @@ module Smaug6739/Alexandriego 1.23.1require (+ filippo.io/edwards25519 v1.1.0 // indirectgithub.com/bytedance/sonic v1.13.1 // indirectgithub.com/bytedance/sonic/loader v0.2.4 // indirectgithub.com/cloudwego/base64x v0.1.5 // indirect@@ -13,7 +14,9 @@ require (github.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.25.0 // indirect+ github.com/go-sql-driver/mysql v1.9.1 // indirectgithub.com/goccy/go-json v0.10.5 // indirect+ github.com/golang-jwt/jwt/v5 v5.2.2 // indirectgithub.com/json-iterator/go v1.1.12 // indirectgithub.com/klauspost/cpuid/v2 v2.2.10 // indirectgithub.com/leodido/go-urn v1.4.0 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 0e799ee7..fd5a71a8 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -1,3 +1,5 @@+filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=+filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=github.com/bytedance/sonic v1.13.1 h1:Jyd5CIvdFnkOWuKXr+wm4Nyk2h0yAFsr8ucJgEasO3g=github.com/bytedance/sonic v1.13.1/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=@@ -21,8 +23,12 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJngithub.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=+github.com/go-sql-driver/mysql v1.9.1 h1:FrjNGn/BsJQjVRuSa8CBrM5BWA9BWoXXat3KrtSb/iI=+github.com/go-sql-driver/mysql v1.9.1/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=+github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=+github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=diff --git a/backend/main.go b/backend/main.goindex a3a9bf54..100d15e6 100644--- a/backend/main.go+++ b/backend/main.go@@ -1,6 +1,21 @@package main-import "Smaug6739/Alexandrie/router"+import (+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/router"++ "github.com/gin-gonic/gin"+ _ "github.com/go-sql-driver/mysql"+)+func main() {- router.Init()-}\ No newline at end of file+ app := app.InitApp()+ 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())++ app_router.Run(":8080")++}diff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.gonew file mode 100644index 00000000..811ba0b7--- /dev/null+++ b/backend/middlewares/authentification.go@@ -0,0 +1,12 @@+package middlewares++import (+ "github.com/gin-gonic/gin"+)++func Auth() gin.HandlerFunc {+ return func(c *gin.Context) {++ c.Next() // Proceed to the next handler if authorized+ }+}diff --git a/backend/models/index.go b/backend/models/index.gonew file mode 100644index 00000000..665fcc9b--- /dev/null+++ b/backend/models/index.go@@ -0,0 +1,11 @@+package models++import "database/sql"++type Model struct {+ DB *sql.DB+}++func NewModel(db *sql.DB) *Model {+ return &Model{DB: db}+}diff --git a/backend/models/session.model.go b/backend/models/session.model.gonew file mode 100644index 00000000..110a4695--- /dev/null+++ b/backend/models/session.model.go@@ -0,0 +1,38 @@+package models++type Session struct {+ Id int64 `json:"id"`+ UserId int64 `json:"user_id"`+ RefreshToken string `json:"refresh_token"`+ ExpireToken int64 `json:"expire_token"`+ LastRefreshTimestamp int64 `json:"last_refresh_timestamp"`+ Active int `json:"active"` // 0: No; 1: Yes;+ LoginTimestamp int64 `json:"login_timestamp"`+ LogoutTimestamp int64 `json:"logout_timestamp"`+}++func (m *Model) CreateSession(session *Session) (*Session, error) {+ _, err := m.DB.Exec("INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, login_timestamp, logout_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",+ session.Id, session.UserId, session.RefreshToken, session.ExpireToken, session.LastRefreshTimestamp, session.Active, session.LoginTimestamp, session.LogoutTimestamp)+ if err != nil {+ return nil, err+ }+ return session, nil+}++func (m *Model) GetSession(refreshToken string) (Session, error) {+ var session Session+ m.DB.QueryRow("SELECT * FROM sessions WHERE refresh_token = ?", refreshToken).Scan(+ &session.Id, &session.UserId, &session.RefreshToken, &session.ExpireToken, &session.LastRefreshTimestamp, &session.Active, &session.LoginTimestamp, &session.LogoutTimestamp,+ )+ return session, nil+}++func (m *Model) UpdateSession(session *Session) (*Session, error) {+ _, err := m.DB.Exec("UPDATE sessions SET refresh_token = ?, expire_token = ?, last_refresh_timestamp = ?, active = ?, login_timestamp = ?, logout_timestamp = ? WHERE id = ?",+ session.RefreshToken, session.ExpireToken, session.LastRefreshTimestamp, session.Active, session.LoginTimestamp, session.LogoutTimestamp, session.Id)+ if err != nil {+ return nil, err+ }+ return session, nil+}diff --git a/backend/models/user.model.go b/backend/models/user.model.gonew file mode 100644index 00000000..77daa030--- /dev/null+++ b/backend/models/user.model.go@@ -0,0 +1,71 @@+package models++type User struct {+ Id int64 `json:"id"`+ Username string `json:"username"`+ Firstname *string `json:"firstname"`+ Lastname *string `json:"lastname"`+ Role int `json:"role"`+ Avatar *string `json:"avatar"`+ Email *string `json:"email"`+ Password string `json:"password,omitempty"`+ CreatedTimestamp *int64 `json:"created_timestamp"`+ UpdatedTimestamp *int64 `json:"updated_timestamp"`+}++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")+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ for rows.Next() {+ var user User+ err := rows.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+ }+ users = append(users, user)+ }++ if err := rows.Err(); err != nil {+ return nil, err+ }++ return users, nil+}++func (m *Model) GetUser(id int64) (User, error) {+ var user User+ m.DB.QueryRow("SELECT id, username, firstname, lastname, role, avatar, email, password, 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.Password, &user.CreatedTimestamp, &user.UpdatedTimestamp,+ )++ return user, nil+}++func (m *Model) GetUserByUsername(username string) User {+ var user User+ m.DB.QueryRow("SELECT id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp FROM users WHERE username = ?", username).Scan(+ &user.Id, &user.Username, &user.Firstname, &user.Lastname,+ &user.Role, &user.Avatar, &user.Email, &user.Password, &user.CreatedTimestamp, &user.UpdatedTimestamp,+ )++ return user+}++func (m *Model) GetUserById(id int64) User {+ var user User+ m.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,+ )++ return user+}diff --git a/backend/router/router.go b/backend/router/router.goindex e0e2eb11..de4b440a 100644--- a/backend/router/router.go+++ b/backend/router/router.go@@ -1,19 +1,16 @@package routerimport (- documents "Smaug6739/Alexandrie/router/routes"+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/router/routes""github.com/gin-gonic/gin")-func Init() {- router := NewRouter()- router.Run(":8080")-}--func NewRouter() *gin.Engine {+func InitRouter(app *app.App) *gin.Engine {router := gin.New()mainGroup := router.Group("/api")- documents.Routes(mainGroup)+ routes.Users(app, mainGroup)+ routes.Auth(app, mainGroup)return router-}\ No newline at end of file+}diff --git a/backend/router/routes/auth.go b/backend/router/routes/auth.gonew file mode 100644index 00000000..afd823f3--- /dev/null+++ b/backend/router/routes/auth.go@@ -0,0 +1,17 @@+package routes++import (+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/controllers"++ "github.com/gin-gonic/gin"+)++func Auth(app *app.App, router *gin.RouterGroup) {+ auth := router.Group("/auth")++ authCtrl := controllers.NewAuthController(app)+ auth.POST("/", authCtrl.Login)+ auth.POST("/refresh", authCtrl.RefreshSession)++}diff --git a/backend/router/routes/documents.go b/backend/router/routes/documents.godeleted file mode 100644index 8d29f09a..00000000--- a/backend/router/routes/documents.go+++ /dev/null@@ -1,14 +0,0 @@-package documents--import (- "Smaug6739/Alexandrie/controllers"-- "github.com/gin-gonic/gin"-)--func Routes(router *gin.RouterGroup) {- documents := router.Group("/documents")-- documents.GET("/", controllers.GetDocument)--}\ No newline at end of filediff --git a/backend/router/routes/users.go b/backend/router/routes/users.gonew file mode 100644index 00000000..ddc963ec--- /dev/null+++ b/backend/router/routes/users.go@@ -0,0 +1,18 @@+package routes++import (+ "Smaug6739/Alexandrie/app"+ "Smaug6739/Alexandrie/controllers"+ "Smaug6739/Alexandrie/middlewares"++ "github.com/gin-gonic/gin"+)++func Users(app *app.App, router *gin.RouterGroup) {+ documents := router.Group("/users")+ documents.Use(middlewares.Auth())++ documentsCtrl := controllers.NewUserController(app)+ documents.GET("/", documentsCtrl.GetUsers)++}diff --git a/backend/utils/snowflake.go b/backend/utils/snowflake.gonew file mode 100644index 00000000..9bfe6d11--- /dev/null+++ b/backend/utils/snowflake.go@@ -0,0 +1,77 @@+package utils++import (+ "os"+ "sync"+ "time"+)++const (+ workerIDBits = 5+ processIDBits = 5+ incrementBits = 12+ timestampShift = workerIDBits + processIDBits + incrementBits+ workerIDShift = processIDBits + incrementBits+ processIDShift = incrementBits++ maxWorkerID = (1 << workerIDBits) - 1+ maxProcessID = (1 << processIDBits) - 1+ maxIncrement = (1 << incrementBits) - 1+)++type Snowflake struct {+ epoch int64+ workerID int64+ processID int64+ increment int64+ 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)++ return &Snowflake{+ epoch: epoch,+ workerID: workerID,+ processID: processID,+ increment: 0,+ }+}++// Generate creates a new unique snowflake ID+func (s *Snowflake) Generate() int64 {+ timestamp := time.Now().UnixMilli()+ s.mutex.Lock()+ defer s.mutex.Unlock()++ if timestamp < s.epoch {+ panic("timestamp is before epoch")+ }++ s.increment = (s.increment + 1) & maxIncrement+ if s.increment == 0 {+ // Wait for next millisecond to avoid ID collisions+ for timestamp <= time.Now().UnixMilli() {+ timestamp = time.Now().UnixMilli()+ }+ }++ return ((timestamp - s.epoch) << timestampShift) |+ (s.workerID << workerIDShift) |+ (s.processID << processIDShift) |+ 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,+ "timestamp": (id >> timestampShift) + s.epoch,+ "workerID": (id >> workerIDShift) & maxWorkerID,+ "processID": (id >> processIDShift) & maxProcessID,+ "increment": id & maxIncrement,+ "epoch": s.epoch,+ }+}