feat(auth): add chatwoot session routes
This commit is contained in:
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
@@ -18,16 +19,24 @@ import (
|
||||
type RefreshTokenStore struct {
|
||||
rdb *redis.Client
|
||||
cfg *config.JWTConfig
|
||||
mu sync.RWMutex
|
||||
mem map[uint]string
|
||||
}
|
||||
|
||||
// NewRefreshTokenStore creates a refresh token store backed by Redis.
|
||||
func NewRefreshTokenStore(rdb *redis.Client, cfg *config.JWTConfig) *RefreshTokenStore {
|
||||
return &RefreshTokenStore{rdb: rdb, cfg: cfg}
|
||||
return &RefreshTokenStore{rdb: rdb, cfg: cfg, mem: map[uint]string{}}
|
||||
}
|
||||
|
||||
// Store saves a refresh token in Redis with TTL.
|
||||
// Key pattern: refresh_token:{user_id}:{token_hash}
|
||||
func (s *RefreshTokenStore) Store(ctx context.Context, userID uint, refreshToken string) error {
|
||||
if s.rdb == nil {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.mem[userID] = refreshToken
|
||||
return nil
|
||||
}
|
||||
key := fmt.Sprintf("gochat:refresh_token:%d", userID)
|
||||
ttl := time.Duration(s.cfg.RefreshExpiryHours) * time.Hour
|
||||
return s.rdb.Set(ctx, key, refreshToken, ttl).Err()
|
||||
@@ -35,6 +44,12 @@ func (s *RefreshTokenStore) Store(ctx context.Context, userID uint, refreshToken
|
||||
|
||||
// Validate checks if a refresh token exists and matches the stored value.
|
||||
func (s *RefreshTokenStore) Validate(ctx context.Context, userID uint, refreshToken string) (bool, error) {
|
||||
if s.rdb == nil {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
stored, ok := s.mem[userID]
|
||||
return ok && stored == refreshToken, nil
|
||||
}
|
||||
key := fmt.Sprintf("gochat:refresh_token:%d", userID)
|
||||
stored, err := s.rdb.Get(ctx, key).Result()
|
||||
if err == redis.Nil {
|
||||
@@ -48,6 +63,12 @@ func (s *RefreshTokenStore) Validate(ctx context.Context, userID uint, refreshTo
|
||||
|
||||
// Revoke removes a refresh token from Redis (logout).
|
||||
func (s *RefreshTokenStore) Revoke(ctx context.Context, userID uint) error {
|
||||
if s.rdb == nil {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.mem, userID)
|
||||
return nil
|
||||
}
|
||||
key := fmt.Sprintf("gochat:refresh_token:%d", userID)
|
||||
return s.rdb.Del(ctx, key).Err()
|
||||
}
|
||||
@@ -56,4 +77,4 @@ func (s *RefreshTokenStore) Revoke(ctx context.Context, userID uint) error {
|
||||
// This ensures each refresh token can only be used once.
|
||||
func (s *RefreshTokenStore) Rotate(ctx context.Context, userID uint, newRefreshToken string) error {
|
||||
return s.Store(ctx, userID, newRefreshToken)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user