@@ -0,0 +1,65 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const keyPrefix = "omnex:session:"
|
||||
|
||||
// RedisManager : Manager adossé à Redis.
|
||||
type RedisManager struct {
|
||||
rdb *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewRedisManager(rdb *redis.Client, ttl time.Duration) *RedisManager {
|
||||
return &RedisManager{rdb: rdb, ttl: ttl}
|
||||
}
|
||||
|
||||
func (m *RedisManager) TTL() time.Duration { return m.ttl }
|
||||
|
||||
func (m *RedisManager) Create(ctx context.Context, s Session) (string, error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s.CreatedAt = time.Now().UTC()
|
||||
data, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := m.rdb.Set(ctx, keyPrefix+token, data, m.ttl).Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Get(ctx context.Context, token string) (Session, bool, error) {
|
||||
if token == "" {
|
||||
return Session{}, false, nil
|
||||
}
|
||||
data, err := m.rdb.Get(ctx, keyPrefix+token).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return Session{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Session{}, false, err
|
||||
}
|
||||
var s Session
|
||||
if err := json.Unmarshal(data, &s); err != nil {
|
||||
return Session{}, false, err
|
||||
}
|
||||
return s, true, nil
|
||||
}
|
||||
|
||||
func (m *RedisManager) Delete(ctx context.Context, token string) error {
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
return m.rdb.Del(ctx, keyPrefix+token).Err()
|
||||
}
|
||||
Reference in New Issue
Block a user