π 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
Moves services in a manager and implement geoid system for security
Smaug6739309c0898977d
diff --git a/backend/app/app.go b/backend/app/app.goindex 20e264a0..d075f1b1 100644--- a/backend/app/app.go+++ b/backend/app/app.go@@ -32,25 +32,13 @@ type Config struct {}}-type Services struct {- Auth services.AuthService- User services.UserService- Node services.NodeService- Permission services.PermissionService- Log services.LogService- Session services.SessionService- Minio services.MinioService- Geolocation services.GeolocationService- Ressource services.RessourceService-}-type App struct {DB *sql.DBSnowflake *utils.SnowflakeConfig ConfigMinioClient *minio.ClientMailClient *mail.Client- Services Services+ Services *services.ServiceManagerRepos *repositories.RepositoryManager}@@ -62,25 +50,19 @@ func InitApp(config Config) *App {app.Snowflake = utils.NewSnowflake(1609459200000)app.Config = config- // Initialize repositories+ // Initialize repository managerrepoManager, err := repositories.NewRepositoryManager(app.DB)if err != nil {log.Fatalf("Failed to initialize repository manager: %v", err)}app.Repos = repoManager- // Initialize services- app.Services = Services{- Auth: services.NewAuthService(repoManager.User, repoManager.Session, app.Snowflake),- User: services.NewUserService(repoManager.User, repoManager.Log, app.Snowflake),- Node: services.NewNodeService(repoManager.Node, repoManager.Permission, app.Snowflake),- Permission: services.NewPermissionService(repoManager.Permission, repoManager.Node, app.Snowflake),- Log: services.NewLogService(repoManager.Log, app.Snowflake),- Session: services.NewSessionService(repoManager.Session),- Minio: services.NewMinioService(app.MinioClient),- Geolocation: services.NewGeolocationService(repoManager.Log),- Ressource: services.NewRessourceService(repoManager.Node, app.Snowflake),+ // Initialize service manager+ serviceManager, err := services.NewServiceManager(repoManager, app.Snowflake, app.MinioClient)+ if err != nil {+ log.Fatalf("Failed to initialize service manager: %v", err)}+ app.Services = serviceManagerMigrate(&config)return &appdiff --git a/backend/controllers/authentication.controller.go b/backend/controllers/authentication.controller.goindex 33162735..8c7023d8 100644--- a/backend/controllers/authentication.controller.go+++ b/backend/controllers/authentication.controller.go@@ -50,7 +50,7 @@ func (ctr *Controller) Login(c *gin.Context) (int, any) {return http.StatusBadRequest, err}- user, session, err := ctr.app.Services.Auth.Login(authClaims.Username, authClaims.Password)+ user, session, err := ctr.app.Services.Auth.Login(authClaims.Username, authClaims.Password, c.ClientIP(), c.Request.UserAgent())if err != nil {return http.StatusUnauthorized, err}@@ -64,11 +64,6 @@ func (ctr *Controller) Login(c *gin.Context) (int, any) {c.SetCookie("Authorization", tokenString, ctr.app.Config.Auth.AccessTokenExpiry, "/", os.Getenv("COOKIE_DOMAIN"), secure, true)c.SetCookie("RefreshToken", session.RefreshToken, ctr.app.Config.Auth.RefreshTokenExpiry, "/", os.Getenv("COOKIE_DOMAIN"), secure, true)- go func() {- location := ctr.app.Services.Geolocation.GetLocationFromIp(c.ClientIP())- ctr.app.Services.Log.CreateConnectionLog(user.Id, c.ClientIP(), c.Request.UserAgent(), location, "login")- }()-return http.StatusOK, user}diff --git a/backend/repositories/log.repository.go b/backend/repositories/log.repository.goindex 482dd85e..488543f0 100644--- a/backend/repositories/log.repository.go+++ b/backend/repositories/log.repository.go@@ -4,7 +4,11 @@ import ("alexandrie/models""alexandrie/types""database/sql"+ "errors""fmt"+ "math/big"+ "net"+ "strings""time")@@ -21,14 +25,18 @@ type LogRepository interface {Create(log *models.Log) errorDeleteOld() errorGetLocationFromIP(ip string) string+ getLocationIdFromIP(ip string) (int64, error)}// Prepared statement keysconst (- stmtLogGetByUserID = "log_get_by_user_id"- stmtLogGetLastConnection = "log_get_last_connection"- stmtLogCreateConnection = "log_create_connection"- stmtLogDeleteOld = "log_delete_old"+ stmtLogGetByUserID = "log_get_by_user_id"+ stmtLogGetLastConnection = "log_get_last_connection"+ stmtLogCreateConnection = "log_create_connection"+ stmtLogDeleteOld = "log_delete_old"+ stmtGetLocationIdFromIpV4 = "log_get_location_id_from_ip_v4"+ stmtGetLocationIdFromIpV6 = "log_get_location_id_from_ip_v6"+ stmtGetLocationFromID = "log_get_location_from_id")// NewLogRepository creates a new log repository with prepared statements@@ -68,6 +76,25 @@ func (r *LogRepositoryImpl) prepareStatements() error {stmtLogDeleteOld: `DELETE FROM connections_logsWHERE timestamp < ?`,++ // Geo IP related statements+ stmtGetLocationIdFromIpV4: `+ SELECT geoname_id+ FROM city_ipv4_complete+ WHERE ? BETWEEN network_start_integer AND network_last_integer+ LIMIT 1`,++ stmtGetLocationIdFromIpV6: `+ SELECT geoname_id+ FROM city_ipv6_complete+ WHERE ? BETWEEN network_start_integer AND network_last_integer+ LIMIT 1`,++ stmtGetLocationFromID: `+ SELECT city_name, subdivision_1_name, subdivision_2_name, country_name+ FROM city_locations_fr+ WHERE geoname_id = ?+ LIMIT 1`,}// Prepare all statements@@ -187,9 +214,62 @@ func (r *LogRepositoryImpl) DeleteOld() error {return nil}-// GetLocationFromIP is a placeholder - implement actual IP location lookup-func (r *LogRepositoryImpl) GetLocationFromIP(ip string) string {- // TODO: Implement actual IP geolocation- // For now, return empty string- return ""+func (s *LogRepositoryImpl) GetLocationFromIP(ip string) string {+ geonameId, err := s.getLocationIdFromIP(ip)+ if err != nil {+ return "Unknown location"+ }+ var res [4]*string+ err = s.db.QueryRow("SELECT city_name, subdivision_1_name, subdivision_2_name, country_name FROM city_Locations_fr WHERE geoname_id = ? LIMIT 1", geonameId).Scan(&res[0], &res[1], &res[2], &res[3])+ if err != nil {+ return "Unknown location"+ }+ parts := []string{}+ for _, part := range res {+ if part != nil && *part != "" {+ parts = append(parts, *part)+ }+ }+ return strings.Join(parts, ", ")+}++func (s *LogRepositoryImpl) getLocationIdFromIP(ip string) (int64, error) {+ ipInt, db, err := ipToDecimal(ip)+ if err != nil {+ return 0, err+ }+ var locationId int64++ stmtKey := ""+ switch db {+ case "ipv4":+ stmtKey = stmtGetLocationIdFromIpV4+ case "ipv6":+ stmtKey = stmtGetLocationIdFromIpV6+ default:+ return 0, errors.New("unsupported IP address type")+ }++ stmt, err := s.manager.GetStatement(stmtKey)+ if err != nil {+ return 0, err+ }++ err = stmt.QueryRow(ipInt).Scan(&locationId)+ return locationId, nil+}++func ipToDecimal(ipStr string) (string, string, error) {+ ip := net.ParseIP(ipStr)+ if ip == nil {+ return "", "", errors.New("invalid IP adress")+ }+ if ip4 := ip.To4(); ip4 != nil {+ return big.NewInt(0).SetBytes(ip4).String(), "ipv4", nil+ }+ ip = ip.To16()+ if ip == nil {+ return "", "", errors.New("invalid or unsupported IP address")+ }+ return big.NewInt(0).SetBytes(ip).String(), "ipv6", nil}diff --git a/backend/services/auth.service.go b/backend/services/auth.service.goindex c65ef47d..c1a47717 100644--- a/backend/services/auth.service.go+++ b/backend/services/auth.service.go@@ -18,7 +18,7 @@ import ()type AuthService interface {- Login(username, password string) (*models.User, *models.Session, error)+ Login(username, password, ip, userAgent string) (*models.User, *models.Session, error)RefreshSession(refreshToken string) (*models.User, *models.Session, error)Logout(refreshToken string) errorLogoutAllDevices(userId types.Snowflake) error@@ -30,19 +30,28 @@ type AuthService interface {type authService struct {userRepo repositories.UserRepositorysessionRepo repositories.SessionRepository+ logRepo repositories.LogRepositorysnowflake *utils.Snowflake}-func NewAuthService(userRepo repositories.UserRepository, sessionRepo repositories.SessionRepository, snowflake *utils.Snowflake) AuthService {+func NewAuthService(userRepo repositories.UserRepository, sessionRepo repositories.SessionRepository, logRepo repositories.LogRepository, snowflake *utils.Snowflake) AuthService {return &authService{userRepo: userRepo,sessionRepo: sessionRepo,+ logRepo: logRepo,snowflake: snowflake,}}-func (s *authService) Login(username, password string) (*models.User, *models.Session, error) {+// Login user+// Find the user by username+// Compare the password with the hashed password+// Create a new session with a refresh token+// Return the user and session+func (s *authService) Login(username, password, ip, userAgent string) (*models.User, *models.Session, error) {+user, err := s.userRepo.GetByUsername(username)+if user == nil || err != nil {return nil, nil, errors.New("invalid credentials")}@@ -66,6 +75,18 @@ func (s *authService) Login(username, password string) (*models.User, *models.Sereturn nil, nil, errors.New("failed to create session")}+ go func() {+ s.logRepo.Create(&models.Log{+ Id: s.snowflake.Generate(),+ UserId: user.Id,+ IpAddr: ip,+ Timestamp: time.Now().UnixMilli(),+ Type: "login",+ Location: s.logRepo.GetLocationFromIP(ip),+ UserAgent: userAgent,+ })+ }()+user.Password = ""return user, session, nil}@@ -131,7 +152,7 @@ func (s *authService) RequestPasswordReset(username string, mailClient *mail.Climessage.To(user.Email)message.Subject("Alexandrie: Password Reset")message.SetBodyString(mail.TypeTextPlain, fmt.Sprintf("Your password reset link is: %s", os.Getenv("DOMAIN_CLIENT")+"/login/reset?token="+resetToken))-+if err := mailClient.DialAndSend(message); err != nil {return nil // Don't reveal errors}diff --git a/backend/services/geolocation.service.go b/backend/services/geolocation.service.godeleted file mode 100644index be4a1e9a..00000000--- a/backend/services/geolocation.service.go+++ /dev/null@@ -1,23 +0,0 @@-package services--import (- "alexandrie/repositories"-)--type GeolocationService interface {- GetLocationFromIp(ip string) string-}--type geolocationService struct {- logRepo repositories.LogRepository-}--func NewGeolocationService(logRepo repositories.LogRepository) GeolocationService {- return &geolocationService{- logRepo: logRepo,- }-}--func (s *geolocationService) GetLocationFromIp(ip string) string {- return s.logRepo.GetLocationFromIP(ip)-}diff --git a/backend/services/manager.go b/backend/services/manager.gonew file mode 100644index 00000000..7c221a85--- /dev/null+++ b/backend/services/manager.go@@ -0,0 +1,70 @@+package services++import (+ "alexandrie/repositories"+ "alexandrie/utils"+ "fmt"+ "log"++ "github.com/minio/minio-go/v7"+)++// ServiceManager manages all services and their dependencies+type ServiceManager struct {+ Auth AuthService+ User UserService+ Node NodeService+ Permission PermissionService+ Log LogService+ Session SessionService+ Minio MinioService+ Ressource RessourceService+ initialized bool+}++// NewServiceManager creates a new service manager and initializes all services+func NewServiceManager(repos *repositories.RepositoryManager, snowflake *utils.Snowflake, minioClient *minio.Client) (*ServiceManager, error) {+ sm := &ServiceManager{}++ if err := sm.initializeServices(repos, snowflake, minioClient); err != nil {+ return nil, fmt.Errorf("failed to initialize services: %w", err)+ }++ sm.initialized = true+ log.Println("β Service manager initialized successfully")+ return sm, nil+}++// initializeServices creates and initializes all service instances+func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManager, snowflake *utils.Snowflake, minioClient *minio.Client) error {+ // Initialize Auth Service+ sm.Auth = NewAuthService(repos.User, repos.Session, repos.Log, snowflake)++ // Initialize User Service+ sm.User = NewUserService(repos.User, repos.Log, snowflake)++ // Initialize Node Service+ sm.Node = NewNodeService(repos.Node, repos.Permission, snowflake)++ // Initialize Permission Service+ sm.Permission = NewPermissionService(repos.Permission, repos.Node, snowflake)++ // Initialize Log Service+ sm.Log = NewLogService(repos.Log, snowflake)++ // Initialize Session Service+ sm.Session = NewSessionService(repos.Session)++ // Initialize Minio Service+ sm.Minio = NewMinioService(minioClient)++ // Initialize Ressource Service+ sm.Ressource = NewRessourceService(repos.Node, snowflake)++ return nil+}++// IsInitialized returns whether the service manager is initialized+func (sm *ServiceManager) IsInitialized() bool {+ return sm.initialized+}