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
+14
View File
@@ -259,3 +259,17 @@ func DeleteThread(db Queryer, threadId int) error {
return nil
}
func GetAdmin(db *sql.DB, username string) (Admin, error) {
row := db.QueryRow(`
SELECT username, password
FROM admins
WHERE username = ?`, username)
var result Admin
if err := row.Scan(&result.Username, &result.Password); err != nil {
return Admin{}, nil
}
return result, nil
}
+5
View File
@@ -28,3 +28,8 @@ type Post struct {
IpHash string
Number int
}
type Admin struct {
Username string
Password string
}
+9
View File
@@ -33,6 +33,12 @@ CREATE TABLE IF NOT EXISTS posts (
FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS admins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
);
-- ======================
-- Seed data
-- ======================
@@ -42,3 +48,6 @@ CREATE TABLE IF NOT EXISTS posts (
INSERT INTO boards (slug, name, tag) VALUES
('comfy', 'Comfy', 'Be comfy, fren'),
('g', 'Technology', 'Beep boop');
INSERT INTO admins (username, password) VALUES
('admin', '$2a$10$vRP4/9O6SwyUziEUtBLQM.r9C2WujIIZ6yEgqGjhlBaFPvtpfdHPC');
+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
}