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.

Remove connections logs object and move important properties to sessions Create new routes /auth/sessions to get user sessions

Smaug673981aefe434699
diff --git a/backend/controllers/authentication.controller.go b/backend/controllers/authentication.controller.go
index ebfd9f75..71c05cfe 100644
--- a/backend/controllers/authentication.controller.go
+++ b/backend/controllers/authentication.controller.go
@@ -13,6 +13,7 @@ import (
)
type AuthController interface {
+ GetSessions(c *gin.Context) (int, any)
Login(c *gin.Context) (int, any)
RefreshSession(c *gin.Context) (int, any)
RequestResetPassword(c *gin.Context) (int, any)
@@ -24,13 +25,34 @@ type AuthController interface {
func NewAuthController(app *app.App) AuthController {
go func() {
for {
- deleteOldSessionsAndLogs(app)
+ deleteOldSessions(app)
time.Sleep(1 * time.Hour) // Sleep for 1 hour
}
}()
return &Controller{app: app}
}
+// GetSessions
+// @Summary Get sessions of the logged-in user
+// @Method GET
+// @Router /auth/sessions [get]
+// @Security Session validation
+// @Success 200 {object} Success([]models.Session)
+// @Failure 400 {object} Error
+func (ctr *Controller) GetSessions(c *gin.Context) (int, any) {
+ userId, err := utils.GetUserIdCtx(c)
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+
+ sessions, err := ctr.app.Services.Session.GetSessionsByUserId(userId)
+ if err != nil {
+ return http.StatusInternalServerError, errors.New("failed to retrieve sessions")
+ }
+
+ return http.StatusOK, sessions
+}
+
// Login
// @Summary Login
// @Method GET
@@ -108,14 +130,8 @@ func (ctr *Controller) RefreshSession(c *gin.Context) (int, any) {
// @Success 200 {object} Success(string)
// @Failure 400 {object} Error
func (ctr *Controller) Logout(c *gin.Context) (int, any) {
- refreshToken, err := c.Cookie("RefreshToken")
- if err != nil {
- return http.StatusUnauthorized, errors.New("no refresh token provided")
- }
-
- if err := ctr.app.Services.Auth.Logout(refreshToken); err != nil {
- return http.StatusUnauthorized, err
- }
+ refreshToken, _ := c.Cookie("RefreshToken")
+ ctr.app.Services.Auth.Logout(refreshToken)
secure := shouldUseSecureCookies()
domain := getCookieDomain()
@@ -193,18 +209,12 @@ func (ctr *Controller) ResetPassword(c *gin.Context) (int, any) {
return http.StatusOK, "Password reset successfully."
}
-func deleteOldSessionsAndLogs(app *app.App) {
- err := app.Services.Log.DeleteOldLogs()
- if err != nil {
- logger.Error("Error deleting old logs: " + err.Error())
- } else {
- logger.Success("Old logs deleted successfully.")
- }
- err = app.Services.Session.DeleteOldSessions()
+func deleteOldSessions(app *app.App) {
+ err := app.Services.Session.DeleteOldSessions()
if err != nil {
- logger.Error("Error deleting old sessions: " + err.Error())
+ logger.Error("Sessions: Error during automatic deletion: " + err.Error())
} else {
- logger.Success("Old sessions deleted successfully.")
+ logger.Success("Sessions: Old sessions deleted successfully.")
}
}
diff --git a/backend/migrations/000015_oidc_session_refactor.up.sql b/backend/migrations/000015_oidc_session_refactor.up.sql
new file mode 100644
index 00000000..c010a7b0
--- /dev/null
+++ b/backend/migrations/000015_oidc_session_refactor.up.sql
@@ -0,0 +1,9 @@
+DROP TABLE connections_logs;
+
+ALTER TABLE `sessions` ADD `ip_adress` varchar(40) NULL AFTER `active`;
+
+ALTER TABLE `sessions` ADD `location` varchar(200) NULL AFTER `ip_adress`;
+
+ALTER TABLE `sessions` ADD `user_agent` varchar(250) NULL AFTER `location`;
+
+ALTER TABLE `sessions` ADD `type` varchar(15) NULL AFTER `user_agent`;
diff --git a/backend/models/log.model.go b/backend/models/log.model.go
deleted file mode 100644
index 01e21fac..00000000
--- a/backend/models/log.model.go
+++ /dev/null
@@ -1,13 +0,0 @@
-package models
-
-import "alexandrie/types"
-
-type Log struct {
- Id types.Snowflake `json:"id" db:"id"`
- UserId types.Snowflake `json:"user_id" db:"user_id"`
- IpAddr string `json:"ip_address" db:"ip_adress"`
- UserAgent string `json:"user_agent" db:"user_agent"`
- Location string `json:"location" db:"location"`
- Type string `json:"type" db:"type"`
- Timestamp int64 `json:"timestamp" db:"timestamp"`
-}
diff --git a/backend/models/session.model.go b/backend/models/session.model.go
index 051341ed..263d3f04 100644
--- a/backend/models/session.model.go
+++ b/backend/models/session.model.go
@@ -9,6 +9,10 @@ type Session struct {
ExpireToken int64 `json:"expire_token" db:"expire_token"`
LastRefreshTimestamp int64 `json:"last_refresh_timestamp" db:"last_refresh_timestamp"`
Active int `json:"active" db:"active"` // 0: No; 1: Yes;
+ IpAddr *string `json:"ip_adress" db:"ip_adress"`
+ UserAgent *string `json:"user_agent" db:"user_agent"`
+ Location *string `json:"location" db:"location"`
+ Type *string `json:"type" db:"type"`
LoginTimestamp int64 `json:"login_timestamp" db:"login_timestamp"`
LogoutTimestamp int64 `json:"logout_timestamp" db:"logout_timestamp"`
}
diff --git a/backend/repositories/log.repository.go b/backend/repositories/log.repository.go
index df3b929f..275967f8 100644
--- a/backend/repositories/log.repository.go
+++ b/backend/repositories/log.repository.go
@@ -1,15 +1,10 @@
package repositories
import (
- "alexandrie/models"
- "alexandrie/types"
- "database/sql"
"errors"
- "fmt"
"math/big"
"net"
"strings"
- "time"
"github.com/jmoiron/sqlx"
)
@@ -19,10 +14,6 @@ type LogRepositoryImpl struct {
}
type LogRepository interface {
- GetByUserID(userId types.Snowflake) ([]*models.Log, error)
- GetLastByUserID(userId types.Snowflake) (*models.Log, error)
- Create(log *models.Log) error
- DeleteOld() error
GetLocationFromIP(ip string) string
getLocationIdFromIP(ip string) (int64, error)
}
@@ -31,60 +22,6 @@ func NewLogRepository(db *sqlx.DB) LogRepository {
return &LogRepositoryImpl{db: db}
}
-// GetByUserID retrieves all logs for a user
-func (r *LogRepositoryImpl) GetByUserID(userId types.Snowflake) ([]*models.Log, error) {
- var logs []*models.Log
- err := r.db.Select(&logs, `
- SELECT id, user_id, ip_adress, timestamp, type, location, user_agent
- FROM connections_logs
- WHERE user_id = ?
- ORDER BY timestamp DESC`, userId)
- if err != nil {
- return nil, fmt.Errorf("failed to query logs: %w", err)
- }
- return logs, nil
-}
-
-// GetLastByUserID retrieves the last login connection for a user
-func (r *LogRepositoryImpl) GetLastByUserID(userId types.Snowflake) (*models.Log, error) {
- var log models.Log
- err := r.db.Get(&log, `
- SELECT id, user_id, ip_adress, timestamp, type, location, user_agent
- FROM connections_logs
- WHERE user_id = ?
- ORDER BY timestamp DESC
- LIMIT 1`, userId)
- if err == sql.ErrNoRows {
- return nil, nil
- }
- if err != nil {
- return nil, fmt.Errorf("failed to get last connection: %w", err)
- }
- return &log, nil
-}
-
-// Create creates a new connection log
-func (r *LogRepositoryImpl) Create(log *models.Log) error {
- _, err := r.db.Exec(`
- INSERT INTO connections_logs (id, user_id, ip_adress, timestamp, type, location, user_agent)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- log.Id, log.UserId, log.IpAddr, log.Timestamp, log.Type, log.Location, log.UserAgent)
- if err != nil {
- return fmt.Errorf("failed to create connection log: %w", err)
- }
- return nil
-}
-
-// DeleteOld deletes logs older than 90 days
-func (r *LogRepositoryImpl) DeleteOld() error {
- ninetyDaysAgo := time.Now().AddDate(0, 0, -90).UnixMilli()
- _, err := r.db.Exec(`DELETE FROM connections_logs WHERE timestamp < ?`, ninetyDaysAgo)
- if err != nil {
- return fmt.Errorf("failed to delete old logs: %w", err)
- }
- return nil
-}
-
// GetLocationFromIP returns the location string from an IP address
func (r *LogRepositoryImpl) GetLocationFromIP(ip string) string {
geonameId, err := r.getLocationIdFromIP(ip)
diff --git a/backend/repositories/session.repository.go b/backend/repositories/session.repository.go
index 102825f2..79f5c4b2 100644
--- a/backend/repositories/session.repository.go
+++ b/backend/repositories/session.repository.go
@@ -14,6 +14,7 @@ type SessionRepositoryImpl struct {
}
type SessionRepository interface {
+ GetByUserId(userId types.Snowflake) ([]models.Session, error)
GetByRefreshToken(refreshToken string) (*models.Session, error)
Create(session *models.Session) (*models.Session, error)
Update(session *models.Session) (*models.Session, error)
@@ -26,11 +27,26 @@ func NewSessionRepository(db *sqlx.DB) SessionRepository {
return &SessionRepositoryImpl{db: db}
}
+// GetByUserId retrieves all sessions for a given user ID
+func (r *SessionRepositoryImpl) GetByUserId(userId types.Snowflake) ([]models.Session, error) {
+ var sessions []models.Session
+ err := r.db.Select(&sessions, `
+ SELECT id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, ip_adress, user_agent, location, type, login_timestamp, logout_timestamp
+ FROM sessions
+ WHERE user_id = ?`, userId)
+
+ if err != nil {
+ return nil, fmt.Errorf("failed to get sessions by user ID: %w", err)
+ }
+
+ return sessions, nil
+}
+
// GetByRefreshToken retrieves a session by refresh token
func (r *SessionRepositoryImpl) GetByRefreshToken(refreshToken string) (*models.Session, error) {
var session models.Session
err := r.db.Get(&session, `
- SELECT id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, login_timestamp, logout_timestamp
+ SELECT id, user_id, expire_token, last_refresh_timestamp, active, ip_adress, user_agent, location, type, login_timestamp, logout_timestamp
FROM sessions
WHERE refresh_token = ? AND active = 1`, refreshToken)
@@ -44,8 +60,8 @@ func (r *SessionRepositoryImpl) GetByRefreshToken(refreshToken string) (*models.
// Create creates a new session
func (r *SessionRepositoryImpl) Create(session *models.Session) (*models.Session, error) {
_, err := r.db.NamedExec(`
- INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, login_timestamp, logout_timestamp)
- VALUES (:id, :user_id, :refresh_token, :expire_token, :last_refresh_timestamp, :active, :login_timestamp, :logout_timestamp)`, session)
+ INSERT INTO sessions (id, user_id, refresh_token, expire_token, last_refresh_timestamp, active, ip_adress, user_agent, location, type, login_timestamp, logout_timestamp)
+ VALUES (:id, :user_id, :refresh_token, :expire_token, :last_refresh_timestamp, :active, :ip_adress, :user_agent, :location, :type, :login_timestamp, :logout_timestamp)`, session)
if err != nil {
return nil, fmt.Errorf("failed to create session: %w", err)
@@ -54,7 +70,7 @@ func (r *SessionRepositoryImpl) Create(session *models.Session) (*models.Session
return session, nil
}
-// Update updates an existing session
+// Update updates an existing session (only refresh token and expiry)
func (r *SessionRepositoryImpl) Update(session *models.Session) (*models.Session, error) {
_, err := r.db.Exec(`
UPDATE sessions
diff --git a/backend/router/routes/auth.go b/backend/router/routes/auth.go
index bea01994..95d7befb 100644
--- a/backend/router/routes/auth.go
+++ b/backend/router/routes/auth.go
@@ -20,6 +20,9 @@ func Auth(app *app.App, router *gin.RouterGroup) {
auth.POST("/logout", utils.WP(authCtrl.Logout))
auth.POST("/logout/all", middlewares.Auth(), utils.WP(authCtrl.LogoutAllDevices))
+ // Sessions route
+ auth.GET("/sessions", middlewares.Auth(), utils.WP(authCtrl.GetSessions))
+
// OIDC routes
oidcCtrl := controllers.NewOIDCController(app)
// Public routes
diff --git a/backend/services/auth.service.go b/backend/services/auth.service.go
index 6f8cc85c..cc22dd42 100644
--- a/backend/services/auth.service.go
+++ b/backend/services/auth.service.go
@@ -5,6 +5,7 @@ import (
"alexandrie/pkg/snowflake"
"alexandrie/repositories"
"alexandrie/types"
+ "alexandrie/utils"
"crypto/rand"
"errors"
"fmt"
@@ -71,6 +72,10 @@ func (s *authService) Login(username, password, ip, userAgent string) (*models.U
ExpireToken: time.Now().Add(time.Duration(30 * 24 * time.Hour)).UnixMilli(),
LastRefreshTimestamp: time.Now().UnixMilli(),
Active: 1,
+ IpAddr: &ip,
+ UserAgent: &userAgent,
+ Location: utils.PtrString(s.logRepo.GetLocationFromIP(ip)),
+ Type: utils.PtrString("login"),
LoginTimestamp: time.Now().UnixMilli(),
LogoutTimestamp: 0,
}
@@ -79,18 +84,6 @@ func (s *authService) Login(username, password, ip, userAgent string) (*models.U
return 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 = nil
return user, session, nil
}
diff --git a/backend/services/log.service.go b/backend/services/log.service.go
deleted file mode 100644
index faeecc1f..00000000
--- a/backend/services/log.service.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package services
-
-import (
- "alexandrie/models"
- "alexandrie/pkg/snowflake"
- "alexandrie/repositories"
- "alexandrie/types"
- "time"
-)
-
-type LogService interface {
- GetConnections(userId types.Snowflake) ([]*models.Log, error)
- GetLastConnection(userId types.Snowflake) (*models.Log, error)
- CreateConnectionLog(userId types.Snowflake, ipAddr, userAgent, location, logType string) error
- DeleteOldLogs() error
-}
-
-type logService struct {
- logRepo repositories.LogRepository
- snowflake *snowflake.Snowflake
-}
-
-func NewLogService(logRepo repositories.LogRepository, snowflake *snowflake.Snowflake) LogService {
- return &logService{
- logRepo: logRepo,
- snowflake: snowflake,
- }
-}
-
-func (s *logService) GetConnections(userId types.Snowflake) ([]*models.Log, error) {
- return s.logRepo.GetByUserID(userId)
-}
-
-func (s *logService) GetLastConnection(userId types.Snowflake) (*models.Log, error) {
- return s.logRepo.GetLastByUserID(userId)
-}
-
-func (s *logService) CreateConnectionLog(userId types.Snowflake, ipAddr, userAgent, location, logType string) error {
- log := &models.Log{
- Id: s.snowflake.Generate(),
- UserId: userId,
- IpAddr: ipAddr,
- UserAgent: userAgent,
- Location: location,
- Type: logType,
- Timestamp: time.Now().UnixMilli(),
- }
- return s.logRepo.Create(log)
-}
-
-func (s *logService) DeleteOldLogs() error {
- return s.logRepo.DeleteOld()
-}
diff --git a/backend/services/manager.go b/backend/services/manager.go
index 31157fef..2be4d8e2 100644
--- a/backend/services/manager.go
+++ b/backend/services/manager.go
@@ -15,7 +15,6 @@ type ServiceManager struct {
User UserService
Node NodeService
Permission PermissionService
- Log LogService
Session SessionService
Minio MinioService
Resource ResourceService
@@ -54,9 +53,6 @@ func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManag
// 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)
diff --git a/backend/services/oidc.service.go b/backend/services/oidc.service.go
index edce0f3f..88538ad0 100644
--- a/backend/services/oidc.service.go
+++ b/backend/services/oidc.service.go
@@ -6,6 +6,7 @@ import (
"alexandrie/pkg/snowflake"
"alexandrie/repositories"
"alexandrie/types"
+ "alexandrie/utils"
"context"
"crypto/rand"
"encoding/base64"
@@ -20,7 +21,6 @@ import (
"time"
)
-// StateData contains information about an OIDC flow state
type StateData struct {
Expiry time.Time
IsLink bool // true if this is a link flow, false if login flow
@@ -315,6 +315,7 @@ func (s *oidcService) LoginOrCreate(providerName string, userInfo *oidc.UserInfo
// createSession creates a new session for a user
func (s *oidcService) createSession(user *models.User, ip, userAgent string) (*models.Session, error) {
+
session := &models.Session{
Id: s.snowflake.Generate(),
UserId: user.Id,
@@ -322,6 +323,10 @@ func (s *oidcService) createSession(user *models.User, ip, userAgent string) (*m
ExpireToken: time.Now().Add(30 * 24 * time.Hour).UnixMilli(),
LastRefreshTimestamp: time.Now().UnixMilli(),
Active: 1,
+ IpAddr: &ip,
+ UserAgent: &userAgent,
+ Location: utils.PtrString(s.logRepo.GetLocationFromIP(ip)),
+ Type: utils.PtrString("login_oidc"),
LoginTimestamp: time.Now().UnixMilli(),
LogoutTimestamp: 0,
}
@@ -330,19 +335,6 @@ func (s *oidcService) createSession(user *models.User, ip, userAgent string) (*m
return nil, fmt.Errorf("failed to create session: %w", err)
}
- // Log the login asynchronously
- go func() {
- s.logRepo.Create(&models.Log{
- Id: s.snowflake.Generate(),
- UserId: user.Id,
- IpAddr: ip,
- Timestamp: time.Now().UnixMilli(),
- Type: "login_oidc",
- Location: s.logRepo.GetLocationFromIP(ip),
- UserAgent: userAgent,
- })
- }()
-
return session, nil
}
@@ -360,19 +352,16 @@ func (s *oidcService) createUserFromOIDC(userInfo *oidc.UserInfo) (*models.User,
CreatedTimestamp: now,
UpdatedTimestamp: now,
}
- fmt.Println("Generated username:", username)
// Set optional fields
if userInfo.GivenName != nil && *userInfo.GivenName != "" {
user.Firstname = userInfo.GivenName
}
- fmt.Println("ok")
if userInfo.FamilyName != nil && *userInfo.FamilyName != "" {
user.Lastname = userInfo.FamilyName
}
if userInfo.Picture != nil && *userInfo.Picture != "" {
user.Avatar = userInfo.Picture
}
- fmt.Println("ok2")
createdUser, err := s.userRepo.Create(user)
if err != nil {
diff --git a/backend/services/session.service.go b/backend/services/session.service.go
index 59ffa3a4..8c9d4bcf 100644
--- a/backend/services/session.service.go
+++ b/backend/services/session.service.go
@@ -1,10 +1,13 @@
package services
import (
+ "alexandrie/models"
"alexandrie/repositories"
+ "alexandrie/types"
)
type SessionService interface {
+ GetSessionsByUserId(userId types.Snowflake) ([]models.Session, error)
DeleteOldSessions() error
}
@@ -18,6 +21,10 @@ func NewSessionService(sessionRepo repositories.SessionRepository) SessionServic
}
}
+func (s *sessionService) GetSessionsByUserId(userId types.Snowflake) ([]models.Session, error) {
+ return s.sessionRepo.GetByUserId(userId)
+}
+
func (s *sessionService) DeleteOldSessions() error {
return s.sessionRepo.DeleteOld()
}
diff --git a/backend/services/user.service.go b/backend/services/user.service.go
index 518615be..78a54d04 100644
--- a/backend/services/user.service.go
+++ b/backend/services/user.service.go
@@ -18,7 +18,7 @@ import (
type UserService interface {
GetAllUsers() ([]*models.User, error)
- GetUserById(id types.Snowflake) (map[string]interface{}, error)
+ GetUserById(id types.Snowflake) (*models.User, error)
GetUserByUsername(username string) (*models.User, error)
SearchPublicUsers(query string) ([]*models.User, error)
CreateUser(username string, firstname, lastname, avatar, email string, password *string) (*models.User, error)
@@ -46,7 +46,7 @@ func (s *userService) GetAllUsers() ([]*models.User, error) {
return s.userRepo.GetAll()
}
-func (s *userService) GetUserById(id types.Snowflake) (map[string]interface{}, error) {
+func (s *userService) GetUserById(id types.Snowflake) (*models.User, error) {
user, err := s.userRepo.GetByID(id)
if err != nil {
return nil, err
@@ -55,12 +55,7 @@ func (s *userService) GetUserById(id types.Snowflake) (map[string]interface{}, e
return nil, errors.New("user not found")
}
- lastConnection, _ := s.logRepo.GetLastByUserID(id)
-
- return map[string]interface{}{
- "user": user,
- "last_connection": lastConnection,
- }, nil
+ return user, nil
}
func (s *userService) GetUserByUsername(username string) (*models.User, error) {
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 66db1025..55244a35 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -24,3 +24,7 @@ func GetBackupBucketName() string {
baseBucket := os.Getenv("MINIO_BUCKET")
return baseBucket + "-backups"
}
+
+func PtrString(s string) *string {
+ return &s
+}