- 密码哈希从 MD5+SHA1 升级为 bcrypt - 删除 super_admins/users 表中的 salt 字段 - 删除旧版升级文件(upgrade.php, check_upgrade, execute_upgrade, sql/upgrades/) - 删除 PASSWORD_SALT 配置项 - 清理所有'兼容 Python 版'注释 - 新项目独立,无历史包袱
81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
// ===========================================
|
|
// 多班级版班级管理系统 - Go 后端
|
|
//
|
|
// 开发者: Canglan
|
|
// 联系方式: admin@sea-studio.top
|
|
// 版权归属: Sea Network Technology Studio
|
|
// 许可证: Apache License 2.0
|
|
//
|
|
// 版权所有 © Sea Network Technology Studio
|
|
// ===========================================
|
|
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"hz-gitea.sea-studio.top/canglan/SharedClassManager/internal/config"
|
|
)
|
|
|
|
// RDB 全局 Redis 客户端实例
|
|
var RDB *redis.Client
|
|
|
|
// InitRedis 初始化 Redis 连接
|
|
func InitRedis(cfg *config.Config) (*redis.Client, error) {
|
|
rdb := redis.NewClient(&redis.Options{
|
|
Addr: cfg.RedisAddr(),
|
|
Password: cfg.RedisPassword,
|
|
DB: cfg.RedisDB,
|
|
PoolSize: cfg.RedisMaxConns,
|
|
MinIdleConns: 5,
|
|
DialTimeout: 5 * time.Second,
|
|
ReadTimeout: 3 * time.Second,
|
|
WriteTimeout: 3 * time.Second,
|
|
})
|
|
|
|
// 测试连接
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
|
return nil, fmt.Errorf("连接 Redis 失败: %w", err)
|
|
}
|
|
|
|
RDB = rdb
|
|
return rdb, nil
|
|
}
|
|
|
|
// --- Token 存储操作 ---
|
|
|
|
const (
|
|
tokenKeyPrefix = "user_token:"
|
|
)
|
|
|
|
// SetUserToken 存储用户 Token
|
|
func SetUserToken(ctx context.Context, userID int, token string, expireMinutes int) error {
|
|
key := fmt.Sprintf("%s%d", tokenKeyPrefix, userID)
|
|
return RDB.Set(ctx, key, token, time.Duration(expireMinutes)*time.Minute).Err()
|
|
}
|
|
|
|
// GetUserToken 获取用户 Token
|
|
func GetUserToken(ctx context.Context, userID int) (string, error) {
|
|
key := fmt.Sprintf("%s%d", tokenKeyPrefix, userID)
|
|
return RDB.Get(ctx, key).Result()
|
|
}
|
|
|
|
// DeleteUserToken 删除用户 Token
|
|
func DeleteUserToken(ctx context.Context, userID int) error {
|
|
key := fmt.Sprintf("%s%d", tokenKeyPrefix, userID)
|
|
return RDB.Del(ctx, key).Err()
|
|
}
|
|
|
|
// ExpireToken 刷新 Token 过期时间(参数单位:分钟)
|
|
func ExpireToken(ctx context.Context, userID int, expireMinutes int) error {
|
|
key := fmt.Sprintf("%s%d", tokenKeyPrefix, userID)
|
|
return RDB.Expire(ctx, key, time.Duration(expireMinutes)*time.Minute).Err()
|
|
}
|