package auth import ( "context" "math/rand" "time" "github.com/redis/go-redis/v9" ) var ctx context.Context var rdb *redis.Client func generateToken(length int) string { validRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789") token := make([]rune, length) for i := range token { token[i] = validRunes[rand.Intn(len(validRunes))] } return string(token) } func Connect(options *redis.Options) { ctx = context.Background() rdb = redis.NewClient(options) if err := rdb.Ping(ctx).Err(); err != nil { panic(err) } } func Close() { rdb.Close() } func SetCookie(timeout int) string { cookie := generateToken(32) err := rdb.Set(ctx, cookie, cookie, time.Duration(timeout)*time.Second).Err() if err != nil { panic(err) } return cookie } func GetCookie(cookie string) bool { resp := rdb.Exists(ctx, cookie) if resp.Err() != nil { panic(resp.Err()) } return resp.Val() == 1 }