Code cleanup

This commit is contained in:
Dominic Ferrando
2025-04-24 00:14:09 -04:00
parent eb770416d0
commit 27fc9476fa
6 changed files with 85 additions and 78 deletions
+4 -12
View File
@@ -1,8 +1,6 @@
package util package util
import ( import (
"crypto/rand"
"encoding/hex"
"sync" "sync"
"time" "time"
) )
@@ -17,17 +15,11 @@ var (
AdminMutex = sync.RWMutex{} 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 { func IsAdminSessionValid(token string) bool {
if DevMode {
return true
}
AdminMutex.RLock() AdminMutex.RLock()
session, exists := AdminSessions[token] session, exists := AdminSessions[token]
AdminMutex.RUnlock() AdminMutex.RUnlock()
-28
View File
@@ -1,11 +1,6 @@
package util package util
import ( import (
"crypto/sha256"
"encoding/hex"
"net"
"net/http"
"strings"
"sync" "sync"
"time" "time"
) )
@@ -19,12 +14,8 @@ var CooldownMutex sync.RWMutex
const POST_COOLDOWN = 15 * time.Second const POST_COOLDOWN = 15 * time.Second
// const POST_COOLDOWN = 0 * time.Second
const THREAD_COOLDOWN = 2 * time.Minute 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 { func GetRemainingCooldown(ip string, m map[string]time.Time, duration time.Duration) time.Duration {
CooldownMutex.RLock() CooldownMutex.RLock()
last, exists := m[ip] last, exists := m[ip]
@@ -44,22 +35,3 @@ func BeginCooldown(ip string, m map[string]time.Time, duration time.Duration) {
m[ip] = time.Now() m[ip] = time.Now()
} }
} }
func GetIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
parts := strings.Split(xff, ",")
return strings.TrimSpace(parts[0])
}
// Fallback to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
func HashIp(ip string) string {
checksum := sha256.Sum256([]byte(ip))
return hex.EncodeToString(checksum[:])
}
+1 -23
View File
@@ -232,29 +232,7 @@ func GetPostFileInfo(mediaPath string) PostFileInfo {
return result return result
} }
func FormatBytes(bytes int64) string { func FormatPostFileInfo(fileInfo PostFileInfo) string {
const (
KB = 1 << 10 // 1024
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
switch {
case bytes >= TB:
return fmt.Sprintf("%.2f TB", float64(bytes)/float64(TB))
case bytes >= GB:
return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
case bytes >= KB:
return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
default:
return fmt.Sprintf("%d B", bytes)
}
}
func FormatFileInfo(fileInfo PostFileInfo) string {
humanSize := FormatBytes(fileInfo.Size) humanSize := FormatBytes(fileInfo.Size)
if fileInfo.IsVideo { if fileInfo.IsVideo {
return fmt.Sprintf("(%s)", humanSize) return fmt.Sprintf("(%s)", humanSize)
+64
View File
@@ -0,0 +1,64 @@
package util
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"net/http"
"strings"
)
const DevMode = false
func FormatBytes(bytes int64) string {
const (
KB = 1 << 10 // 1024
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
switch {
case bytes >= TB:
return fmt.Sprintf("%.2f TB", float64(bytes)/float64(TB))
case bytes >= GB:
return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
case bytes >= KB:
return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
default:
return fmt.Sprintf("%d B", bytes)
}
}
func GetIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
parts := strings.Split(xff, ",")
return strings.TrimSpace(parts[0])
}
// Fallback to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
func HashIp(ip string) string {
checksum := sha256.Sum256([]byte(ip))
return hex.EncodeToString(checksum[:])
}
func GenToken() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
+15 -14
View File
@@ -4,15 +4,6 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"io"
"log"
"mime/multipart"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/dominicf2001/comfychan/internal/database" "github.com/dominicf2001/comfychan/internal/database"
"github.com/dominicf2001/comfychan/internal/util" "github.com/dominicf2001/comfychan/internal/util"
"github.com/dominicf2001/comfychan/web/views" "github.com/dominicf2001/comfychan/web/views"
@@ -21,10 +12,16 @@ import (
"github.com/go-chi/chi/v5/middleware" "github.com/go-chi/chi/v5/middleware"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"io"
"log"
"mime/multipart"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
) )
var dev = true
func AdminOnlyMiddleware(next http.Handler) http.Handler { func AdminOnlyMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("comfy_admin") c, err := r.Cookie("comfy_admin")
@@ -43,7 +40,7 @@ func AdminOnlyMiddleware(next http.Handler) http.Handler {
} }
func disableCacheInDevMode(next http.Handler) http.Handler { func disableCacheInDevMode(next http.Handler) http.Handler {
if !dev { if !util.DevMode {
return next return next
} }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -61,6 +58,10 @@ func SumUniquePostIps(posts []database.Post) int {
} }
func isAdmin(r *http.Request) bool { func isAdmin(r *http.Request) bool {
if util.DevMode {
return true
}
admin := false admin := false
if c, err := r.Cookie("comfy_admin"); err == nil { if c, err := r.Cookie("comfy_admin"); err == nil {
admin = util.IsAdminSessionValid(c.Value) admin = util.IsAdminSessionValid(c.Value)
@@ -487,7 +488,7 @@ func main() {
Name: "comfy_admin", Name: "comfy_admin",
Value: token, Value: token,
HttpOnly: true, HttpOnly: true,
Secure: !dev, Secure: !util.DevMode,
Expires: tokenValidUntil, Expires: tokenValidUntil,
SameSite: http.SameSiteStrictMode, SameSite: http.SameSiteStrictMode,
Path: "/", Path: "/",
@@ -516,7 +517,7 @@ func main() {
Name: "comfy_admin", Name: "comfy_admin",
Value: "", Value: "",
HttpOnly: true, HttpOnly: true,
Secure: !dev, Secure: !util.DevMode,
Expires: time.Now(), Expires: time.Now(),
SameSite: http.SameSiteStrictMode, SameSite: http.SameSiteStrictMode,
Path: "/", Path: "/",
+2 -2
View File
@@ -76,7 +76,7 @@ templ PostOriginal(post database.Post, thread database.Thread) {
{ post.MediaPath } { post.MediaPath }
</a> </a>
<div class="post-img-info"> <div class="post-img-info">
<span>{ util.FormatFileInfo(util.GetPostFileInfo(post.MediaPath)) }</span> <span>{ util.FormatPostFileInfo(util.GetPostFileInfo(post.MediaPath)) }</span>
</div> </div>
</div> </div>
<img <img
@@ -146,7 +146,7 @@ templ PostReply(post database.Post, threadContext ThreadContext) {
{ post.MediaPath } { post.MediaPath }
</a> </a>
<div class="post-img-info"> <div class="post-img-info">
<span>{ util.FormatFileInfo(util.GetPostFileInfo(post.MediaPath)) }</span> <span>{ util.FormatPostFileInfo(util.GetPostFileInfo(post.MediaPath)) }</span>
</div> </div>
</div> </div>
<img <img