biblio/auth/jwt/store/store.go

75 lines
1.7 KiB
Go

package store
import (
"context"
"strconv"
"time"
"github.com/go-redis/redis/v8"
)
type ClaimStore interface {
Get(uint64) (string, error)
Set(uint64, string, time.Duration) error
Delete(uint64) error
Close() error
ExpireAt(uint64, time.Time) error
Expire(uint64, time.Duration) error
TTL(uint64) (time.Duration, error)
}
type redisStore struct {
host string
password string
db int
client *redis.Client
}
func NewRedis(host string, password string, db int) (ClaimStore, error) {
r := redisStore{
host: host,
password: password,
db: db,
}
r.client = redis.NewClient(&redis.Options{Addr: host, Password: password, DB: db})
return &r, nil
}
func (r *redisStore) Get(key uint64) (string, error) {
val, err := r.client.Get(context.Background(), r.key(key)).Result()
return val, err
}
func (r *redisStore) Set(key uint64, val string, expiration time.Duration) error {
err := r.client.SetEX(context.Background(), r.key(key), val, expiration).Err()
return err
}
func (r *redisStore) Delete(key uint64) error {
err := r.client.Del(context.Background(), r.key(key)).Err()
return err
}
func (r *redisStore) Close() error {
return r.client.Close()
}
func (r *redisStore) key(key uint64) string {
return "auth_token:" + strconv.FormatUint(key, 10)
}
func (r *redisStore) ExpireAt(key uint64, t time.Time) error {
err := r.client.ExpireAt(context.Background(), r.key(key), t).Err()
return err
}
func (r *redisStore) Expire(key uint64, term time.Duration) error {
err := r.client.Expire(context.Background(), r.key(key), term).Err()
return err
}
func (r *redisStore) TTL(key uint64) (time.Duration, error) {
expire, err := r.client.TTL(context.Background(), r.key(key)).Result()
return expire, err
}