summaryrefslogtreecommitdiffstats
path: root/internal/auth.go
blob: 6caa78530fb50b427aadab4309c3bbe46cf7a62a (plain) (blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package internal

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"sync"
	"time"
)

type Session struct {
	Expires time.Time
}

type SessionManager struct {
	sessions map[string]*Session
	mutex    sync.RWMutex
}

func NewSessionManager() *SessionManager {
	sm := &SessionManager{
		sessions: make(map[string]*Session),
	}
	// Start cleanup goroutine
	go sm.cleanupExpiredSessions()
	return sm
}

// Using the same logic that powers the pi-hole authentication
// GeneratePasswordHash creates a double SHA256 hash from the password param to
// validate against config.PasswordHash
func GeneratePasswordHash(password string) string {
	first := sha256.Sum256([]byte(password))
	firstHex := hex.EncodeToString(first[:])
	second := sha256.Sum256([]byte(firstHex))
	return hex.EncodeToString(second[:])
}

func ValidatePassword(password, hash string) bool {
	return GeneratePasswordHash(password) == hash
}

func (sm *SessionManager) CreateSession() (string, time.Time, error) {
	sm.mutex.Lock()
	defer sm.mutex.Unlock()

	sessionID, err := generateSecureToken()
	if err != nil {
		return "", time.Time{}, fmt.Errorf("failed to generate session ID: %w", err)
	}

	expires := time.Now().Add(1 * time.Hour)
	sm.sessions[sessionID] = &Session{
		Expires: expires,
	}

	return sessionID, expires, nil
}

func (sm *SessionManager) ValidateSession(sessionID string) (*Session, bool) {
	sm.mutex.RLock()
	defer sm.mutex.RUnlock()

	session, exists := sm.sessions[sessionID]
	if !exists {
		return nil, false
	}

	if time.Now().After(session.Expires) {
		return nil, false
	}

	return session, true
}

func (sm *SessionManager) DeleteSession(sessionID string) {
	sm.mutex.Lock()
	defer sm.mutex.Unlock()
	delete(sm.sessions, sessionID)
}

func generateSecureToken() (string, error) {
	bytes := make([]byte, 32)
	_, err := rand.Read(bytes)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

// cleanupExpiredSessions periodically removes expired sessions every 1 hour
func (sm *SessionManager) cleanupExpiredSessions() {
	ticker := time.NewTicker(1 * time.Hour)
	defer ticker.Stop()

	for range ticker.C {
		sm.mutex.Lock()
		now := time.Now()
		for sessionID, session := range sm.sessions {
			if now.After(session.Expires) {
				delete(sm.sessions, sessionID)
			}
		}
		sm.mutex.Unlock()
	}
}