2 lab
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.local/messenger/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func New(client *redis.Client, ttl time.Duration) *Store {
|
||||
return &Store{client: client, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, userID string) (string, time.Time, error) {
|
||||
var raw [32]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw[:])
|
||||
expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
body, err := json.Marshal(record{UserID: userID, ExpiresAt: expires})
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if err := s.client.Set(ctx, key(token), body, s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, model.ErrUnavailable
|
||||
}
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (string, error) {
|
||||
body, err := s.client.Get(ctx, key(token)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", model.ErrUnavailable
|
||||
}
|
||||
var item record
|
||||
if err := json.Unmarshal(body, &item); err != nil || item.UserID == "" {
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
if !item.ExpiresAt.After(time.Now()) {
|
||||
_ = s.client.Del(ctx, key(token)).Err()
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
return item.UserID, nil
|
||||
}
|
||||
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
if err := s.client.Del(ctx, key(token)).Err(); err != nil {
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
Reference in New Issue
Block a user