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.

Fix authenficiation

Smaug#6739b203f3dafa40
diff --git a/backend/.env b/backend/.env
new file mode 100644
index 00000000..509f2099
--- /dev/null
+++ b/backend/.env
@@ -0,0 +1 @@
+JWT_SECRET=your_secret_key
\ No newline at end of file
diff --git a/backend/controllers/authentification.controller.go b/backend/controllers/authentification.controller.go
index 0688c077..6a2f7408 100644
--- a/backend/controllers/authentification.controller.go
+++ b/backend/controllers/authentification.controller.go
@@ -5,6 +5,7 @@ import (
"Smaug6739/Alexandrie/utils"
"crypto/rand"
"fmt"
+ "os"
"time"
"github.com/gin-gonic/gin"
@@ -12,7 +13,7 @@ import (
"golang.org/x/crypto/bcrypt"
)
-var refresh_token_expiration = 7 * 24 * 60 * 60 * 1000 // 7 days
+var refresh_token_expiration = 1000 * 60 * 1 // 2 minutes
func (dc *Controller) Login(c *gin.Context) {
username := c.PostForm("username")
@@ -44,7 +45,7 @@ func (dc *Controller) Login(c *gin.Context) {
Id: dc.app.Snowflake.Generate(),
UserId: user.Id,
RefreshToken: signRefreshToken(),
- ExpireToken: time.Now().Add(time.Duration(refresh_token_expiration * 1000)).UnixMilli(),
+ ExpireToken: time.Now().Add(time.Duration(refresh_token_expiration * 1000000)).UnixMilli(),
LastRefreshTimestamp: time.Now().UnixMilli(),
Active: 1,
LoginTimestamp: time.Now().UnixMilli(),
@@ -101,19 +102,19 @@ func (dc *Controller) RefreshSession(c *gin.Context) {
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, utils.Error("Token refreshed."))
+ c.JSON(200, utils.Success("Token refreshed."))
}
func (dc *Controller) 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
+ "sub": user.Username, // Subject (user identifier)
+ "iss": "alexandrie", // Issuer
+ "aud": user.Role, // Audience (user role)
+ "exp": time.Now().Add(time.Second * 15).Unix(), // Expiration time // TODO: Replace with config
+ "iat": time.Now().Unix(), // Issued at
})
- tokenString, err := claims.SignedString([]byte("secretKey")) // TODO: Replace with config
+ tokenString, err := claims.SignedString([]byte(os.Getenv("JWT_SECRET"))) // TODO: Replace with config
if err != nil {
return "", err
}
diff --git a/backend/go.mod b/backend/go.mod
index 605fe4ae..596de8a4 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -17,6 +17,7 @@ require (
github.com/go-sql-driver/mysql v1.9.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/golang-jwt/jwt/v5 v5.2.2 // indirect
+ github.com/joho/godotenv v1.5.1 // 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
diff --git a/backend/go.sum b/backend/go.sum
index fd5a71a8..05b2d3d8 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -30,6 +30,8 @@ github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PU
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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
+github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
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=
diff --git a/backend/main.go b/backend/main.go
index 100d15e6..75ce738f 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -6,9 +6,12 @@ import (
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
+ "github.com/joho/godotenv"
)
func main() {
+ godotenv.Load()
+
app := app.InitApp()
defer app.DB.Close()
@@ -16,6 +19,5 @@ func main() {
// Recovery middleware recovers from any panics and writes a 500 if there was one.
app_router.Use(gin.Recovery())
- app_router.Run(":8080")
-
+ app_router.Run("localhost:8080")
}
diff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.go
index 811ba0b7..83fdd814 100644
--- a/backend/middlewares/authentification.go
+++ b/backend/middlewares/authentification.go
@@ -1,11 +1,45 @@
package middlewares
import (
+ "Smaug6739/Alexandrie/utils"
+ "net/http"
+ "os"
+
"github.com/gin-gonic/gin"
+ "github.com/golang-jwt/jwt/v5"
)
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
+ tokenString, err := c.Cookie("Authorization")
+ if err != nil {
+ c.JSON(http.StatusUnauthorized, utils.Error("Unauthorized"))
+ c.Abort() // Stop further processing if unauthorized
+ return
+ }
+
+ // Parse the token
+ token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, http.ErrAbortHandler
+ }
+ return []byte(os.Getenv("JWT_SECRET")), nil
+ })
+
+ if err != nil || !token.Valid {
+ c.JSON(http.StatusUnauthorized, utils.Error("Unauthorized"))
+ c.Abort() // Stop further processing if unauthorized
+ return
+ }
+
+ // Set the token claims to the context
+ if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
+ c.Set("claims", claims)
+ } else {
+ c.JSON(http.StatusUnauthorized, utils.Error("Unauthorized"))
+ c.Abort()
+ return
+ }
c.Next() // Proceed to the next handler if authorized
}
diff --git a/backend/router/routes/users.go b/backend/router/routes/users.go
index 2285e6e7..f56b3698 100644
--- a/backend/router/routes/users.go
+++ b/backend/router/routes/users.go
@@ -9,10 +9,10 @@ import (
)
func Users(app *app.App, router *gin.RouterGroup) {
- documents := router.Group("/users")
- documents.Use(middlewares.Auth())
+ usr := router.Group("/users")
+ usr.Use(middlewares.Auth())
- documentsCtrl := controllers.NewController(app)
- documents.GET("/", documentsCtrl.GetUsers)
+ usrCtrl := controllers.NewController(app)
+ usr.GET("/", usrCtrl.GetUsers)
}