57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
var ErrSessionNotFound = errors.New("session not found")
|
|
|
|
type SessionStore struct {
|
|
client *redis.Client
|
|
prefix string
|
|
}
|
|
|
|
func NewRedisClient(address string) *redis.Client {
|
|
return redis.NewClient(&redis.Options{
|
|
Addr: address, PoolSize: 10, MaxRetries: -1,
|
|
DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second,
|
|
})
|
|
}
|
|
|
|
func NewSessionStore(client *redis.Client, prefix string) *SessionStore {
|
|
return &SessionStore{client: client, prefix: prefix}
|
|
}
|
|
|
|
func (s *SessionStore) key(tokenHash []byte) string {
|
|
return s.prefix + hex.EncodeToString(tokenHash)
|
|
}
|
|
|
|
func (s *SessionStore) Create(ctx context.Context, tokenHash []byte, userID string, expires time.Time) error {
|
|
ttl := time.Until(expires)
|
|
if ttl <= 0 {
|
|
return errors.New("session expiry must be in the future")
|
|
}
|
|
return s.client.Set(ctx, s.key(tokenHash), userID, ttl).Err()
|
|
}
|
|
|
|
func (s *SessionStore) UserID(ctx context.Context, tokenHash []byte) (string, error) {
|
|
id, err := s.client.Get(ctx, s.key(tokenHash)).Result()
|
|
if errors.Is(err, redis.Nil) {
|
|
return "", ErrSessionNotFound
|
|
}
|
|
return id, err
|
|
}
|
|
|
|
func (s *SessionStore) Revoke(ctx context.Context, tokenHash []byte) error {
|
|
return s.client.Del(ctx, s.key(tokenHash)).Err()
|
|
}
|
|
|
|
func (s *SessionStore) Ping(ctx context.Context) error {
|
|
return s.client.Ping(ctx).Err()
|
|
}
|