登录状态记录

This commit is contained in:
ryan
2026-06-12 10:08:02 +08:00
parent 62fcd245f2
commit 1fe5118029
9 changed files with 185 additions and 12 deletions
@@ -23,6 +23,8 @@ import (
"github.com/gin-gonic/gin"
)
const expectedDefaultConfigsCount = 28
func setupTestRouter(authUser *model.User) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
@@ -137,9 +139,9 @@ func TestListSystemConfigs(t *testing.T) {
var configs []model.SystemConfig
_ = json.Unmarshal(dataBytes, &configs)
// Defaults seed 27 configurations
if len(configs) != 27 {
t.Errorf("expected 27 default configs, got %d", len(configs))
// Defaults seed configurations
if len(configs) != expectedDefaultConfigsCount {
t.Errorf("expected %d default configs, got %d", expectedDefaultConfigsCount, len(configs))
}
})
+16 -2
View File
@@ -165,10 +165,24 @@ func containsScope(scopes []string, scope string) bool {
return false
}
func setLoginSession(c *gin.Context, user *model.User) error {
func setLoginSession(ctx context.Context, c *gin.Context, user *model.User) error {
session := sessions.Default(c)
session.Set(UserIDKey, user.ID)
session.Set(UserNameKey, user.Username)
// 根据系统配置动态设置 Session 过期时间
maxAge := 0
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
if err == nil {
if ttlHours == -1 {
// 永不过期,设置为 10 年
maxAge = 10 * 365 * 24 * 3600
} else if ttlHours > 0 {
maxAge = ttlHours * 3600
}
}
session.Options(util.GetSessionOptions(maxAge))
return session.Save()
}
@@ -508,7 +522,7 @@ func handleCallbackLogin(ctx context.Context, c *gin.Context, source *model.Auth
user.LastLoginAt = time.Now()
_ = db.DB(ctx).Model(&user).Update("last_login_at", user.LastLoginAt).Error
if err := setLoginSession(c, &user); err != nil {
if err := setLoginSession(ctx, c, &user); err != nil {
c.JSON(http.StatusInternalServerError, util.Err(err.Error()))
return
}
+17 -3
View File
@@ -58,10 +58,24 @@ func isRegistrationEnabled() bool {
return enabled
}
func setLoginSession(c *gin.Context, user *model.User) error {
func setLoginSession(ctx context.Context, c *gin.Context, user *model.User) error {
session := sessions.Default(c)
session.Set(oauth.UserIDKey, user.ID)
session.Set(oauth.UserNameKey, user.Username)
// 根据系统配置动态设置 Session 过期时间
maxAge := 0
ttlHours, err := model.GetIntByKey(ctx, model.ConfigKeyLoginSessionTTLHours)
if err == nil {
if ttlHours == -1 {
// 永不过期,设置为 10 年
maxAge = 10 * 365 * 24 * 3600
} else if ttlHours > 0 {
maxAge = ttlHours * 3600
}
}
session.Options(util.GetSessionOptions(maxAge))
if err := session.Save(); err != nil {
return err
}
@@ -134,7 +148,7 @@ func Login(c *gin.Context) {
c.JSON(http.StatusOK, util.Err(err.Error()))
return
}
if err := setLoginSession(c, &user); err != nil {
if err := setLoginSession(ctx, c, &user); err != nil {
c.JSON(http.StatusOK, util.Err(errSaveSessionFailed))
return
}
@@ -218,7 +232,7 @@ func Register(c *gin.Context) {
return
}
if err := setLoginSession(c, &user); err != nil {
if err := setLoginSession(ctx, c, &user); err != nil {
c.JSON(http.StatusOK, util.Err(errSaveSessionFailed))
return
}
@@ -0,0 +1,8 @@
-- +goose Up
INSERT INTO w_system_configs (key, value, type, visibility, description, created_at, updated_at)
VALUES
('login_session_ttl_hours', '0', 'system', 0, '登录会话过期时间 (小时,0表示浏览器关闭后自动退出,-1表示永不过期)', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT (key) DO NOTHING;
-- +goose Down
DELETE FROM w_system_configs WHERE key = 'login_session_ttl_hours';
@@ -0,0 +1,8 @@
-- +goose Up
INSERT INTO w_system_configs (key, value, type, visibility, description, created_at, updated_at)
VALUES
('login_session_ttl_hours', '0', 'system', 0, '登录会话过期时间 (小时,0表示浏览器关闭后自动退出,-1表示永不过期)', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
ON CONFLICT (key) DO NOTHING;
-- +goose Down
DELETE FROM w_system_configs WHERE key = 'login_session_ttl_hours';
+4 -2
View File
@@ -16,6 +16,8 @@ import (
"gorm.io/gorm"
)
const expectedMigratedSystemConfigCount = 28
func TestMigrateInitializesSQLiteDatabase(t *testing.T) {
sqliteDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
@@ -38,8 +40,8 @@ func TestMigrateInitializesSQLiteDatabase(t *testing.T) {
if err := sqliteDB.Table("w_system_configs").Count(&systemConfigCount).Error; err != nil {
t.Fatalf("Migrate() count w_system_configs error = %v", err)
}
if systemConfigCount != 27 {
t.Errorf("Migrate() w_system_configs count = %d, want %d", systemConfigCount, 27)
if systemConfigCount != expectedMigratedSystemConfigCount {
t.Errorf("Migrate() w_system_configs count = %d, want %d", systemConfigCount, expectedMigratedSystemConfigCount)
}
var adminCount int64
+1
View File
@@ -47,6 +47,7 @@ const (
ConfigKeyDiskCacheMaxSizeMB = "disk_cache_max_size_mb" // 磁盘缓存最大空间大小 (MB)
ConfigKeyDiskCacheTTLMinutes = "disk_cache_ttl_minutes" // 磁盘缓存默认有效期 (分钟)
ConfigKeyDiskCacheLRUEnabled = "disk_cache_lru_enabled" // 是否启用 LRU 淘汰机制
ConfigKeyLoginSessionTTLHours = "login_session_ttl_hours" // 登录会话过期时间 (小时,0表示浏览器关闭后自动退出登录,-1表示永不过期)
)
const (
+6
View File
@@ -249,6 +249,12 @@ func getSeedConfigsPart2() []model.SystemConfig {
Type: configTypeSystem,
Description: "是否启用 LRU 淘汰机制",
},
{
Key: model.ConfigKeyLoginSessionTTLHours,
Value: "0",
Type: configTypeSystem,
Description: "登录会话过期时间 (小时,0表示浏览器关闭后自动退出,-1表示永不过期)",
},
}
}