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.

Change id from uint to snowflake (return string)

Smaug6739a9347ae2c12c
diff --git a/backend/controllers/authentication.controller.go b/backend/controllers/authentication.controller.go
index 3798e0b3..3088fb9d 100644
--- a/backend/controllers/authentication.controller.go
+++ b/backend/controllers/authentication.controller.go
@@ -171,7 +171,7 @@ func (ctr *Controller) Logout(c *gin.Context) (int, any) {
func (ctr *Controller) signAccessToken(user *models.User) (string, error) {
claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
- "sub": strconv.FormatUint(user.Id, 10), // Subject (user identifier)
+ "sub": strconv.FormatUint(uint64(user.Id), 10), // Subject (user identifier)
"iss": "alexandrie", // Issuer
"exp": time.Now().Add(time.Duration(time.Second * time.Duration(ctr.app.Config.Auth.RefreshTokenExpiry))).Unix(), // Expiration time
"iat": time.Now().Unix(), // Issued at
diff --git a/backend/controllers/uploads.controller.go b/backend/controllers/uploads.controller.go
index 9a84bbe6..026e44de 100644
--- a/backend/controllers/uploads.controller.go
+++ b/backend/controllers/uploads.controller.go
@@ -10,7 +10,6 @@ import (
"net/http"
"os"
"path/filepath"
- "strconv"
"time"
"slices"
@@ -124,7 +123,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
- id, err := strconv.ParseUint(c.Param("id"), 10, 64)
+ id, err := utils.GetIdParam(c, c.Param("id"))
if err != nil {
return http.StatusBadRequest, errors.New("invalid id format")
}
diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.go
index c65e6fe2..2926577a 100644
--- a/backend/controllers/users.controller.go
+++ b/backend/controllers/users.controller.go
@@ -64,7 +64,15 @@ func (ctr *Controller) GetUserById(c *gin.Context) (int, any) {
if user == nil {
return http.StatusNotFound, errors.New("user not found")
}
- return http.StatusOK, user
+ last_connection, err := ctr.app.Services.Log.GetLastConnection(id)
+ if err != nil {
+ last_connection = nil
+ }
+
+ return http.StatusOK, gin.H{
+ "user": user,
+ "last_connection": last_connection,
+ }
}
// Create User
diff --git a/backend/models/category.model.go b/backend/models/category.model.go
index f85c7595..6083df47 100644
--- a/backend/models/category.model.go
+++ b/backend/models/category.model.go
@@ -1,12 +1,14 @@
package models
+import "alexandrie/types"
+
type Category struct {
- Id uint64 `json:"id" form:"id" binding:"omitempty"`
- Name string `json:"name" form:"name" binding:"required,max=50"`
- Icon string `json:"icon" form:"icon" binding:"omitempty,max=30000"`
- Order int `json:"order" form:"order" binding:"omitempty"`
- Role int `json:"role" form:"role" binding:"omitempty"` // 0 category; 1 workspace;
- WorkspaceId *uint64 `json:"workspace_id" form:"workspace_id" binding:"omitempty"`
- ParentId *uint64 `json:"parent_id" form:"parent_id" binding:"omitempty"`
- AuthorId uint64 `json:"author_id" form:"author_id" binding:"omitempty"`
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ Name string `json:"name" form:"name" binding:"required,max=50"`
+ Icon string `json:"icon" form:"icon" binding:"omitempty,max=30000"`
+ Order int `json:"order" form:"order" binding:"omitempty"`
+ Role int `json:"role" form:"role" binding:"omitempty"` // 0 category; 1 workspace;
+ WorkspaceId *types.Snowflake `json:"workspace_id" form:"workspace_id" binding:"omitempty"`
+ ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
+ AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
}
diff --git a/backend/models/document.model.go b/backend/models/document.model.go
index 923a6f02..47931db5 100644
--- a/backend/models/document.model.go
+++ b/backend/models/document.model.go
@@ -1,16 +1,18 @@
package models
+import "alexandrie/types"
+
type Document struct {
- Id uint64 `json:"id" form:"id" binding:"omitempty"`
- Name string `json:"name" form:"name" binding:"required,max=50"`
- Description *string `json:"description" form:"description" binding:"omitempty,max=250"`
- Tags *string `json:"tags" form:"tags" binding:"omitempty,max=250"`
- Category *uint64 `json:"category" form:"category" binding:"omitempty"`
- ParentId *uint64 `json:"parent_id" form:"parent_id" binding:"omitempty"`
- Accessibility int `json:"accessibility" form:"accessibility" binding:"required"` // 0: Public; 1: Private; 2: Unlisted;
- ContentMarkdown *string `json:"content_markdown" form:"content_markdown"`
- ContentHtml *string `json:"content_html" form:"content_html"`
- AuthorId uint64 `json:"author_id" form:"author_id" binding:"omitempty"`
- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
- UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ Name string `json:"name" form:"name" binding:"required,max=50"`
+ Description *string `json:"description" form:"description" binding:"omitempty,max=250"`
+ Tags *string `json:"tags" form:"tags" binding:"omitempty,max=250"`
+ Category *types.Snowflake `json:"category" form:"category" binding:"omitempty"`
+ ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
+ Accessibility int `json:"accessibility" form:"accessibility" binding:"required"` // 0: Public; 1: Private; 2: Unlisted;
+ ContentMarkdown *string `json:"content_markdown" form:"content_markdown"`
+ ContentHtml *string `json:"content_html" form:"content_html"`
+ AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
+ UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
}
diff --git a/backend/models/log.model.go b/backend/models/log.model.go
index 0c5f68ce..2f937eab 100644
--- a/backend/models/log.model.go
+++ b/backend/models/log.model.go
@@ -1,11 +1,13 @@
package models
+import "alexandrie/types"
+
type Log struct {
- Id uint64 `json:"id"`
- UserId uint64 `json:"user_id"`
- IpAddr string `json:"ip_address"`
- UserAgent string `json:"user_agent"`
- Location string `json:"location"`
- Type string `json:"type"`
- Timestamp int64 `json:"timestamp"`
+ Id types.Snowflake `json:"id"`
+ UserId types.Snowflake `json:"user_id"`
+ IpAddr string `json:"ip_address"`
+ UserAgent string `json:"user_agent"`
+ Location string `json:"location"`
+ Type string `json:"type"`
+ Timestamp int64 `json:"timestamp"`
}
diff --git a/backend/models/ressource.model.go b/backend/models/ressource.model.go
index 8da18e1e..d1c13822 100644
--- a/backend/models/ressource.model.go
+++ b/backend/models/ressource.model.go
@@ -1,12 +1,14 @@
package models
+import "alexandrie/types"
+
type Ressource struct {
- Id uint64 `json:"id" form:"id" binding:"omitempty"`
- Filename string `json:"filename" form:"filename" binding:"required,max=50"`
- Filesize int64 `json:"filesize" form:"filesize" binding:"omitempty"`
- Filetype string `json:"filetype" form:"filetype" binding:"omitempty"`
- OriginalPath string `json:"original_path" form:"original_path" binding:"omitempty"`
- TransformedPath string `json:"transformed_path" form:"transformed_path" binding:"omitempty"`
- AuthorId uint64 `json:"author_id" form:"author_id" binding:"omitempty"`
- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ Filename string `json:"filename" form:"filename" binding:"required,max=50"`
+ Filesize int64 `json:"filesize" form:"filesize" binding:"omitempty"`
+ Filetype string `json:"filetype" form:"filetype" binding:"omitempty"`
+ OriginalPath string `json:"original_path" form:"original_path" binding:"omitempty"`
+ TransformedPath string `json:"transformed_path" form:"transformed_path" binding:"omitempty"`
+ AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
}
diff --git a/backend/models/session.model.go b/backend/models/session.model.go
index f8fda101..9d21027f 100644
--- a/backend/models/session.model.go
+++ b/backend/models/session.model.go
@@ -1,12 +1,14 @@
package models
+import "alexandrie/types"
+
type Session struct {
- Id uint64 `json:"id"`
- UserId uint64 `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"`
+ Id types.Snowflake `json:"id"`
+ UserId types.Snowflake `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"`
}
diff --git a/backend/models/user.model.go b/backend/models/user.model.go
index 002e6a96..81b542df 100644
--- a/backend/models/user.model.go
+++ b/backend/models/user.model.go
@@ -1,14 +1,16 @@
package models
+import "alexandrie/types"
+
type User struct {
- Id uint64 `json:"id" form:"id" binding:"omitempty"`
- Username string `json:"username" form:"username" binding:"required,min=5,max=30"`
- Firstname *string `json:"firstname" form:"firstname" binding:"omitempty"`
- Lastname *string `json:"lastname" form:"lastname" binding:"omitempty"`
- Role int `json:"role" form:"role" binding:"omitempty"` // 1: user, 2: admin
- Avatar *string `json:"avatar" form:"avatar" binding:"omitempty"`
- Email string `json:"email" form:"email" binding:"required,email"`
- Password string `json:"password,omitempty" form:"password" binding:"omitempty,min=4,max=50"`
- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
- UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ Username string `json:"username" form:"username" binding:"required,min=5,max=30"`
+ Firstname *string `json:"firstname" form:"firstname" binding:"omitempty"`
+ Lastname *string `json:"lastname" form:"lastname" binding:"omitempty"`
+ Role int `json:"role" form:"role" binding:"omitempty"` // 1: user, 2: admin
+ Avatar *string `json:"avatar" form:"avatar" binding:"omitempty"`
+ Email string `json:"email" form:"email" binding:"required,email"`
+ Password string `json:"password,omitempty" form:"password" binding:"omitempty,min=4,max=50"`
+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
+ UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
}
diff --git a/backend/router/router.go b/backend/router/router.go
index f7637b87..945de454 100644
--- a/backend/router/router.go
+++ b/backend/router/router.go
@@ -3,12 +3,27 @@ package router
import (
"alexandrie/app"
"alexandrie/router/routes"
+ "os"
+ "github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func InitRouter(app *app.App) *gin.Engine {
router := gin.New()
+
+ router.Use(gin.Recovery())
+
+ // Configurer les proxys et CORS
+ router.SetTrustedProxies([]string{"127.0.0.1", "localhost"})
+ router.Use(cors.New(cors.Config{
+ AllowOrigins: []string{os.Getenv("DOMAIN_CLIENT")},
+ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
+ ExposeHeaders: []string{"Content-Length"},
+ AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
+ AllowCredentials: true,
+ }))
+
mainGroup := router.Group("/api")
routes.Users(app, mainGroup)
routes.Auth(app, mainGroup)
diff --git a/backend/server/server.go b/backend/server/server.go
index 2253f027..24080b78 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -7,7 +7,6 @@ import (
"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"
@@ -29,16 +28,6 @@ func SetupServer() (*gin.Engine, *app.App) {
// 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/category.service.go b/backend/services/category.service.go
index d6240d9a..acea6965 100644
--- a/backend/services/category.service.go
+++ b/backend/services/category.service.go
@@ -2,22 +2,23 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
)
type CategoryService interface {
- GetAllCategories(userId uint64) ([]*models.Category, error)
- GetCategory(categoryId uint64) (*models.Category, error)
+ GetAllCategories(userId types.Snowflake) ([]*models.Category, error)
+ GetCategory(categoryId types.Snowflake) (*models.Category, error)
CreateCategory(category *models.Category) error
UpdateCategory(category *models.Category) error
- DeleteCategory(categoryId uint64) error
+ DeleteCategory(categoryId types.Snowflake) error
}
func NewCategoryService(db *sql.DB) CategoryService {
return &Service{db: db}
}
-func (s *Service) GetAllCategories(userId uint64) ([]*models.Category, error) {
+func (s *Service) GetAllCategories(userId types.Snowflake) ([]*models.Category, error) {
var categories []*models.Category
rows, err := s.db.Query("SELECT * FROM categories WHERE author_id = ? ORDER BY `order`", userId)
if err != nil {
@@ -35,7 +36,7 @@ func (s *Service) GetAllCategories(userId uint64) ([]*models.Category, error) {
return categories, nil
}
-func (s *Service) GetCategory(categoryId uint64) (*models.Category, error) {
+func (s *Service) GetCategory(categoryId types.Snowflake) (*models.Category, error) {
var category models.Category
err := s.db.QueryRow("SELECT * FROM categories WHERE id = ?", categoryId).Scan(
&category.Id,
@@ -77,7 +78,7 @@ func (s *Service) UpdateCategory(category *models.Category) error {
return err
}
-func (s *Service) DeleteCategory(categoryId uint64) error {
+func (s *Service) DeleteCategory(categoryId types.Snowflake) error {
_, err := s.db.Exec("DELETE FROM categories WHERE id = ?", categoryId)
return err
}
diff --git a/backend/services/document.service.go b/backend/services/document.service.go
index c4bc09ad..560dea42 100644
--- a/backend/services/document.service.go
+++ b/backend/services/document.service.go
@@ -2,22 +2,23 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
)
type DocumentService interface {
- GetAllDocuments(userId uint64) ([]*models.Document, error)
- GetDocument(documentId uint64) (*models.Document, error)
+ GetAllDocuments(userId types.Snowflake) ([]*models.Document, error)
+ GetDocument(documentId types.Snowflake) (*models.Document, error)
CreateDocument(document *models.Document) error
UpdateDocument(document *models.Document) error
- DeleteDocument(documentId uint64) error
+ DeleteDocument(documentId types.Snowflake) error
}
func NewDocumentService(db *sql.DB) DocumentService {
return &Service{db: db}
}
-func (s *Service) GetAllDocuments(userId uint64) ([]*models.Document, error) {
+func (s *Service) GetAllDocuments(userId types.Snowflake) ([]*models.Document, error) {
var documents []*models.Document
rows, err := s.db.Query("SELECT id, name, description, tags, category, parent_id, accessibility, author_id, created_timestamp, updated_timestamp FROM documents WHERE author_id = ? ORDER BY name", userId)
if err != nil {
@@ -45,7 +46,7 @@ func (s *Service) GetAllDocuments(userId uint64) ([]*models.Document, error) {
return documents, nil
}
-func (s *Service) GetDocument(documentId uint64) (*models.Document, error) {
+func (s *Service) GetDocument(documentId types.Snowflake) (*models.Document, error) {
var document models.Document
err := s.db.QueryRow("SELECT id, name, description, tags, category, parent_id, accessibility, content_markdown, content_html, author_id, created_timestamp, updated_timestamp FROM documents WHERE id = ?", documentId).Scan(
&document.Id,
@@ -97,7 +98,7 @@ func (s *Service) UpdateDocument(document *models.Document) error {
return err
}
-func (s *Service) DeleteDocument(documentId uint64) error {
+func (s *Service) DeleteDocument(documentId types.Snowflake) error {
_, err := s.db.Exec("DELETE FROM documents WHERE id = ?", documentId)
return err
}
diff --git a/backend/services/log.service.go b/backend/services/log.service.go
index 0b404a9a..8bbdfca4 100644
--- a/backend/services/log.service.go
+++ b/backend/services/log.service.go
@@ -2,6 +2,7 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
"errors"
"fmt"
@@ -12,8 +13,8 @@ import (
)
type LogService interface {
- GetConnections(userId uint64) ([]*models.Log, error)
- GetLastConnection(userId uint64) (*models.Log, error)
+ GetConnections(userId types.Snowflake) ([]*models.Log, error)
+ GetLastConnection(userId types.Snowflake) (*models.Log, error)
GetLocationFromIp(ip string) string
CreateConnectionLog(log *models.Log) (*models.Log, error)
DeleteOldLogs() error
@@ -25,7 +26,7 @@ func NewLogService(db *sql.DB) LogService {
return &Service{db: db}
}
-func (s *Service) GetConnections(userId uint64) ([]*models.Log, error) {
+func (s *Service) GetConnections(userId types.Snowflake) ([]*models.Log, error) {
var logs []*models.Log
rows, err := s.db.Query("SELECT * FROM connections_logs WHERE user_id = ?", userId)
if err != nil {
@@ -42,7 +43,7 @@ func (s *Service) GetConnections(userId uint64) ([]*models.Log, error) {
return logs, nil
}
-func (s *Service) GetLastConnection(userId uint64) (*models.Log, error) {
+func (s *Service) GetLastConnection(userId types.Snowflake) (*models.Log, error) {
var log models.Log
err := s.db.QueryRow("SELECT * FROM connections_logs WHERE user_id = ? ORDER BY timestamp DESC LIMIT 1", userId).Scan(&log.Id, &log.IpAddr, &log.Location, &log.Timestamp, &log.Type, &log.UserAgent, &log.UserId)
if err != nil {
diff --git a/backend/services/ressource.service.go b/backend/services/ressource.service.go
index 3ff21ee8..4b056a92 100644
--- a/backend/services/ressource.service.go
+++ b/backend/services/ressource.service.go
@@ -2,22 +2,23 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
)
type RessourceService interface {
- GetAllUploadsByUserId(userId uint64) ([]*models.Ressource, error)
- GetRessourceById(id uint64) (*models.Ressource, error)
- GetUserUploadsSize(userId uint64) (int64, error)
+ GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressource, error)
+ GetRessourceById(id types.Snowflake) (*models.Ressource, error)
+ GetUserUploadsSize(userId types.Snowflake) (int64, error)
CreateRessource(ressource *models.Ressource) (*models.Ressource, error)
- DeleteRessource(id uint64) error
+ DeleteRessource(id types.Snowflake) error
}
func NewRessourceService(db *sql.DB) RessourceService {
return &Service{db: db}
}
-func (s *Service) GetAllUploadsByUserId(userId uint64) ([]*models.Ressource, error) {
+func (s *Service) GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressource, error) {
var ressources []*models.Ressource
rows, err := s.db.Query("SELECT * from ressources WHERE author_id = ?", userId)
if err != nil {
@@ -35,7 +36,7 @@ func (s *Service) GetAllUploadsByUserId(userId uint64) ([]*models.Ressource, err
return ressources, nil
}
-func (s *Service) GetRessourceById(id uint64) (*models.Ressource, error) {
+func (s *Service) GetRessourceById(id types.Snowflake) (*models.Ressource, error) {
var ressource models.Ressource
err := s.db.QueryRow("SELECT * FROM ressources WHERE id = ?", id).Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.AuthorId, &ressource.CreatedTimestamp)
if err != nil {
@@ -44,7 +45,7 @@ func (s *Service) GetRessourceById(id uint64) (*models.Ressource, error) {
return &ressource, nil
}
-func (s *Service) GetUserUploadsSize(userId uint64) (int64, error) {
+func (s *Service) GetUserUploadsSize(userId types.Snowflake) (int64, error) {
var totalSize *int64
err := s.db.QueryRow("SELECT SUM(file_size) FROM ressources WHERE author_id = ?", userId).Scan(&totalSize)
if err != nil {
@@ -64,7 +65,7 @@ func (s *Service) CreateRessource(ressource *models.Ressource) (*models.Ressourc
return ressource, nil
}
-func (s *Service) DeleteRessource(id uint64) error {
+func (s *Service) DeleteRessource(id types.Snowflake) error {
_, err := s.db.Exec("DELETE FROM ressources WHERE id = ?", id)
return err
}
diff --git a/backend/services/session.service.go b/backend/services/session.service.go
index eb89c74a..5cfab443 100644
--- a/backend/services/session.service.go
+++ b/backend/services/session.service.go
@@ -2,6 +2,7 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
"time"
)
@@ -10,7 +11,7 @@ type AuthService interface {
CreateSession(session *models.Session) (*models.Session, error)
GetSession(refreshToken string) (models.Session, error)
UpdateSession(session *models.Session) (*models.Session, error)
- DeleteSession(id uint64) error
+ DeleteSession(id types.Snowflake) error
DeleteOldSessions() error
}
@@ -44,7 +45,7 @@ func (s *Service) UpdateSession(session *models.Session) (*models.Session, error
return session, nil
}
-func (s *Service) DeleteSession(id uint64) error {
+func (s *Service) DeleteSession(id types.Snowflake) error {
_, err := s.db.Exec("DELETE FROM sessions WHERE id = ?", id)
if err != nil {
return err
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index fa0e146e..735c5a10 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -2,18 +2,19 @@ package services
import (
"alexandrie/models"
+ "alexandrie/types"
"database/sql"
)
type UserService interface {
GetAllUsers() ([]*models.User, error)
- GetUserById(id uint64) (*models.User, error)
+ GetUserById(id types.Snowflake) (*models.User, error)
GetUserByUsername(username string) (*models.User, error)
CheckUsernameExists(username string) bool
CreateUser(user *models.User) (*models.User, error)
- UpdateUser(id uint64, user *models.User) (*models.User, error)
- UpdatePassword(id uint64, password string) error
- DeleteUser(id uint64) error
+ UpdateUser(id types.Snowflake, user *models.User) (*models.User, error)
+ UpdatePassword(id types.Snowflake, password string) error
+ DeleteUser(id types.Snowflake) error
}
func NewUserService(db *sql.DB) UserService {
@@ -72,7 +73,7 @@ func (s *Service) GetUserByUsername(username string) (*models.User, error) {
return &user, nil
}
-func (s *Service) GetUserById(id uint64) (*models.User, error) {
+func (s *Service) GetUserById(id types.Snowflake) (*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,
@@ -86,7 +87,7 @@ func (s *Service) GetUserById(id uint64) (*models.User, error) {
return &user, nil
}
-func (s *Service) UpdateUser(id uint64, user *models.User) (*models.User, error) {
+func (s *Service) UpdateUser(id types.Snowflake, 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, id)
if err != nil {
@@ -95,12 +96,12 @@ func (s *Service) UpdateUser(id uint64, user *models.User) (*models.User, error)
return user, nil
}
-func (s *Service) UpdatePassword(id uint64, password string) error {
+func (s *Service) UpdatePassword(id types.Snowflake, password string) error {
_, err := s.db.Exec("UPDATE users SET password=? WHERE id=?", password, id)
return err
}
-func (s *Service) DeleteUser(id uint64) error {
+func (s *Service) DeleteUser(id types.Snowflake) error {
_, err := s.db.Exec("DELETE FROM users WHERE id=?", id)
return err
}
diff --git a/backend/tests/helpers.go b/backend/tests/helpers.go
index 20b6a8a7..87e2a395 100644
--- a/backend/tests/helpers.go
+++ b/backend/tests/helpers.go
@@ -1,6 +1,7 @@
package tests
import (
+ "alexandrie/types"
"bytes"
"encoding/json"
"io"
@@ -17,10 +18,10 @@ const USER_PASSWORD = "10082005"
const USER_ID = "543"
type APIResponse struct {
- Status string `json:"status"`
- Timestamp uint64 `json:"timestamp"`
- Message string `json:"message,omitempty"`
- Result any `json:"result,omitempty"`
+ Status string `json:"status"`
+ Timestamp types.Snowflake `json:"timestamp"`
+ Message string `json:"message,omitempty"`
+ Result any `json:"result,omitempty"`
StatusCode int
}
diff --git a/backend/types/Snowflake.go b/backend/types/Snowflake.go
new file mode 100644
index 00000000..20559fd2
--- /dev/null
+++ b/backend/types/Snowflake.go
@@ -0,0 +1,13 @@
+package types
+
+import (
+ "encoding/json"
+ "strconv"
+)
+
+type Snowflake uint64
+
+func (s Snowflake) MarshalJSON() ([]byte, error) {
+ // Renvoie l'ID entre guillemets, pour JSON
+ return json.Marshal(strconv.FormatUint(uint64(s), 10))
+}
diff --git a/backend/utils/permissions.go b/backend/utils/permissions.go
index a1e3465e..899ad700 100644
--- a/backend/utils/permissions.go
+++ b/backend/utils/permissions.go
@@ -1,6 +1,7 @@
package utils
import (
+ "alexandrie/types"
"errors"
"strconv"
@@ -32,7 +33,7 @@ func CheckUserRequestPermission(ctx *gin.Context, requiredRole int) bool {
return false
}
-func GetIdParam(ctx *gin.Context, param string) (uint64, error) {
+func GetIdParam(ctx *gin.Context, param string) (types.Snowflake, error) {
if param == "" {
return 0, errors.New("parameter is empty")
}
@@ -41,12 +42,12 @@ func GetIdParam(ctx *gin.Context, param string) (uint64, error) {
if err != nil {
return 0, errors.New("invalid parameter")
}
- return id_param, nil
+ return types.Snowflake(id_param), nil
}
return GetUserIdCtx(ctx)
}
-func GetUserIdCtx(ctx *gin.Context) (uint64, error) {
+func GetUserIdCtx(ctx *gin.Context) (types.Snowflake, error) {
userId, exists := ctx.Get("user_id")
if !exists {
return 0, errors.New("user ID not found in context")
@@ -55,10 +56,10 @@ func GetUserIdCtx(ctx *gin.Context) (uint64, error) {
if !ok {
return 0, errors.ErrUnsupported
}
- return id, nil
+ return types.Snowflake(id), nil
}
-func SelfOrPermission(ctx *gin.Context, allowed int, key ...string) (uint64, error) {
+func SelfOrPermission(ctx *gin.Context, allowed int, key ...string) (types.Snowflake, error) {
// Check if the c.Param("id") is "@me" or c.Param("id") is the same as the user ID in the context
// If not, check if the user has the required permission
// If one of the above is true, return the user ID from the context
@@ -88,7 +89,7 @@ func SelfOrPermission(ctx *gin.Context, allowed int, key ...string) (uint64, err
return 0, errors.New("unauthorized")
}
-func RessourceAccess(ctx *gin.Context, targetId uint64) error {
+func RessourceAccess(ctx *gin.Context, targetId types.Snowflake) error {
// Check if the connected user has access to the resource (userId == targetId) or if the user has the required permission (ADMINISTRATOR)
userId, err := GetUserIdCtx(ctx)
if err != nil {
diff --git a/backend/utils/snowflake.go b/backend/utils/snowflake.go
index 191c98fc..dd70852b 100644
--- a/backend/utils/snowflake.go
+++ b/backend/utils/snowflake.go
@@ -1,6 +1,7 @@
package utils
import (
+ "alexandrie/types"
"os"
"sync"
"time"
@@ -41,7 +42,7 @@ func NewSnowflake(epoch int64) *Snowflake {
}
// Generate creates a new unique snowflake ID
-func (s *Snowflake) Generate() uint64 {
+func (s *Snowflake) Generate() types.Snowflake {
timestamp := time.Now().UnixMilli()
s.mutex.Lock()
defer s.mutex.Unlock()
@@ -58,7 +59,7 @@ func (s *Snowflake) Generate() uint64 {
}
}
- return uint64(((timestamp - s.epoch) << timestampShift) |
+ return types.Snowflake(((timestamp - s.epoch) << timestampShift) |
(s.workerID << workerIDShift) |
(s.processID << processIDShift) |
s.increment)