summaryrefslogtreecommitdiff
path: root/internal/auth/session.go
blob: 2b5be2aa7a6ef1e6ddccb31e470b439c9d098d8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package auth

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/paul/kiss-media-player/internal/clock"
	"github.com/paul/kiss-media-player/internal/model"
	"github.com/paul/kiss-media-player/internal/repository"
)

// SessionManager handles session lifecycle.
type SessionManager struct {
	repo    repository.SessionRepo
	clock   clock.Clock
	timeout time.Duration
}

// NewSessionManager creates a SessionManager.
func NewSessionManager(repo repository.SessionRepo, clock clock.Clock, timeout time.Duration) *SessionManager {
	return &SessionManager{
		repo:    repo,
		clock:   clock,
		timeout: timeout,
	}
}

func (m *SessionManager) generateID() (string, error) {
	b := make([]byte, 32)
	if _, err := rand.Read(b); err != nil {
		return "", fmt.Errorf("generate session id: %w", err)
	}
	return hex.EncodeToString(b), nil
}

// CreateSession creates a new session for a user and returns the session ID.
func (m *SessionManager) CreateSession(ctx context.Context, userID int64) (string, error) {
	id, err := m.generateID()
	if err != nil {
		return "", err
	}
	now := m.clock.Now()
	sess := &model.Session{
		ID:        id,
		UserID:    userID,
		ExpiresAt: now.Add(m.timeout),
		CreatedAt: now,
	}
	if err := m.repo.CreateSession(ctx, sess); err != nil {
		return "", fmt.Errorf("create session: %w", err)
	}
	return id, nil
}

// ValidateSession checks if a session ID is valid and not expired.
func (m *SessionManager) ValidateSession(ctx context.Context, id string) (*model.Session, error) {
	sess, err := m.repo.GetSessionByID(ctx, id)
	if err != nil {
		return nil, fmt.Errorf("get session: %w", err)
	}
	if sess == nil {
		return nil, nil
	}
	if m.clock.Now().After(sess.ExpiresAt) {
		_ = m.repo.DeleteSession(ctx, id)
		return nil, nil
	}
	return sess, nil
}

// DeleteSession removes a session.
func (m *SessionManager) DeleteSession(ctx context.Context, id string) error {
	return m.repo.DeleteSession(ctx, id)
}

// Cleanup removes expired sessions.
func (m *SessionManager) Cleanup(ctx context.Context) error {
	return m.repo.DeleteExpiredSessions(ctx, m.clock.Now())
}