Implement basic auth

This commit is contained in:
Dominic Ferrando
2025-04-23 14:13:43 -04:00
parent 4018632080
commit a559aaebf4
11 changed files with 242 additions and 6 deletions
+67
View File
@@ -0,0 +1,67 @@
package util
import (
"crypto/rand"
"encoding/hex"
"sync"
"time"
)
type AdminSession struct {
Expiration time.Time
Username string
}
var (
AdminSessions = make(map[string]AdminSession)
AdminMutex = sync.RWMutex{}
)
func GenToken() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func IsAdminSessionValid(token string) bool {
AdminMutex.RLock()
session, exists := AdminSessions[token]
AdminMutex.RUnlock()
if !exists || time.Now().After(session.Expiration) {
AdminMutex.Lock()
delete(AdminSessions, token)
AdminMutex.Unlock()
return false
}
return true
}
func CreateAdminSession(token string, session AdminSession) {
AdminMutex.Lock()
AdminSessions[token] = session
AdminMutex.Unlock()
}
func DeleteAdminSession(token string) {
AdminMutex.Lock()
delete(AdminSessions, token)
AdminMutex.Unlock()
}
func HasExistingAdminSession(username string) bool {
AdminMutex.RLock()
defer AdminMutex.RUnlock()
for _, session := range AdminSessions {
if session.Username == username {
return true
}
}
return false
}
+3 -4
View File
@@ -15,7 +15,7 @@ var (
ThreadCooldowns = make(map[string]time.Time)
)
var CooldownMutex sync.Mutex
var CooldownMutex sync.RWMutex
const POST_COOLDOWN = 15 * time.Second
@@ -26,10 +26,9 @@ const THREAD_COOLDOWN = 2 * time.Minute
// const THREAD_COOLDOWN = 0 * time.Minute
func GetRemainingCooldown(ip string, m map[string]time.Time, duration time.Duration) time.Duration {
CooldownMutex.Lock()
defer CooldownMutex.Unlock()
CooldownMutex.RLock()
last, exists := m[ip]
CooldownMutex.RUnlock()
if !exists {
return 0
}