Compare commits
8 Commits
csrf-token
...
important-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b1293bb6f | ||
|
|
d9de02f08d | ||
| e2d8bd344d | |||
| 82eb9de5f1 | |||
| 5bcca61d59 | |||
|
|
db5c2558f8 | ||
|
|
09d919ca27 | ||
|
|
50fa003842 |
@@ -15,6 +15,7 @@ import (
|
|||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
@@ -39,9 +40,6 @@ func main() {
|
|||||||
|
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
|
||||||
// CSRF: set a token cookie for browsers and enforce it on unsafe /api calls.
|
|
||||||
r.Use(middleware.EnsureCSRFCookie())
|
|
||||||
|
|
||||||
r.MaxMultipartMemory = 10 << 30
|
r.MaxMultipartMemory = 10 << 30
|
||||||
r.SetFuncMap(template.FuncMap{
|
r.SetFuncMap(template.FuncMap{
|
||||||
"add": func(a, b int) int { return a + b },
|
"add": func(a, b int) int { return a + b },
|
||||||
@@ -78,7 +76,9 @@ func main() {
|
|||||||
createAdminUser(userService)
|
createAdminUser(userService)
|
||||||
|
|
||||||
apiRoute := r.Group("/api")
|
apiRoute := r.Group("/api")
|
||||||
apiRoute.Use(middleware.CSRFMiddleware())
|
// General API rate limiting to reduce abuse/spam.
|
||||||
|
// ~60 req/min per IP with some burst room.
|
||||||
|
apiRoute.Use(middleware.RateLimitByIP(60, time.Minute, 30, 5*time.Minute))
|
||||||
|
|
||||||
auth.RegisterRoutes(apiRoute, authHandler)
|
auth.RegisterRoutes(apiRoute, authHandler)
|
||||||
user.RegisterRoutes(apiRoute, userHandler)
|
user.RegisterRoutes(apiRoute, userHandler)
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func randomToken(n int) (string, error) {
|
|
||||||
b := make([]byte, n)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EnsureCSRFCookie sets a csrf_token cookie if it's missing.
|
|
||||||
//
|
|
||||||
// Uses SameSite=Strict to reduce cross-site cookie sending.
|
|
||||||
// HttpOnly must be false so browser JS can read it and send it back in a header.
|
|
||||||
func EnsureCSRFCookie() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
if tok, err := c.Cookie("csrf_token"); err != nil || tok == "" {
|
|
||||||
if tok, err := randomToken(32); err == nil {
|
|
||||||
secure := os.Getenv("USE_HTTPS") == "true"
|
|
||||||
http.SetCookie(c.Writer, &http.Cookie{
|
|
||||||
Name: "csrf_token",
|
|
||||||
Value: tok,
|
|
||||||
Path: "/",
|
|
||||||
Secure: secure,
|
|
||||||
HttpOnly: false,
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// CSRFMiddleware enforces CSRF checks on unsafe methods for cookie-authenticated requests.
|
|
||||||
//
|
|
||||||
// - Skips safe methods (GET/HEAD/OPTIONS).
|
|
||||||
// - Skips requests using Authorization: Bearer (non-cookie API clients).
|
|
||||||
// - Enforces only when auth_token cookie is present (browser session).
|
|
||||||
//
|
|
||||||
// Validation uses the double-submit cookie pattern:
|
|
||||||
// cookie csrf_token must match X-CSRF-Token header OR _csrf form field.
|
|
||||||
func CSRFMiddleware() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
m := c.Request.Method
|
|
||||||
if m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions {
|
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if strings.HasPrefix(c.GetHeader("Authorization"), "Bearer ") {
|
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only enforce when cookie auth is in play
|
|
||||||
if _, err := c.Cookie("auth_token"); err != nil {
|
|
||||||
c.Next()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extra hardening: basic Origin check when present.
|
|
||||||
if origin := c.GetHeader("Origin"); origin != "" {
|
|
||||||
host := c.Request.Host
|
|
||||||
if !strings.Contains(origin, host) {
|
|
||||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "csrf origin blocked"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cookieTok, err := c.Cookie("csrf_token")
|
|
||||||
if err != nil || cookieTok == "" {
|
|
||||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "missing csrf cookie"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
reqTok := c.GetHeader("X-CSRF-Token")
|
|
||||||
if reqTok == "" {
|
|
||||||
reqTok = c.PostForm("_csrf")
|
|
||||||
}
|
|
||||||
|
|
||||||
if reqTok == "" || reqTok != cookieTok {
|
|
||||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "bad csrf token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
118
internal/api/middleware/ratelimit.go
Normal file
118
internal/api/middleware/ratelimit.go
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tokenBucket struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
rate float64 // tokens per second
|
||||||
|
burst float64 // max tokens
|
||||||
|
tokens float64
|
||||||
|
last time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTokenBucket(max int, per time.Duration, burst int) *tokenBucket {
|
||||||
|
if burst <= 0 {
|
||||||
|
burst = max
|
||||||
|
}
|
||||||
|
rate := float64(max) / per.Seconds()
|
||||||
|
b := float64(burst)
|
||||||
|
now := time.Now()
|
||||||
|
return &tokenBucket{rate: rate, burst: b, tokens: b, last: now}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *tokenBucket) allow() bool {
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
delta := now.Sub(b.last).Seconds()
|
||||||
|
b.last = now
|
||||||
|
|
||||||
|
b.tokens += delta * b.rate
|
||||||
|
if b.tokens > b.burst {
|
||||||
|
b.tokens = b.burst
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.tokens < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.tokens -= 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type ipClient struct {
|
||||||
|
bucket *tokenBucket
|
||||||
|
lastSeen time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIP returns a Gin middleware that rate limits requests per client IP.
|
||||||
|
//
|
||||||
|
// max: max requests per time window (per)
|
||||||
|
// per: the time window duration
|
||||||
|
// burst: optional burst capacity (defaults to max if <=0)
|
||||||
|
// ttl: how long to keep idle IP buckets around
|
||||||
|
func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin.HandlerFunc {
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
clients = make(map[string]*ipClient)
|
||||||
|
)
|
||||||
|
|
||||||
|
// opportunistic cleanup (runs at most once per minute)
|
||||||
|
var (
|
||||||
|
cleanupMu sync.Mutex
|
||||||
|
lastCleanup time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
cleanup := func(now time.Time) {
|
||||||
|
cleanupMu.Lock()
|
||||||
|
defer cleanupMu.Unlock()
|
||||||
|
if !lastCleanup.IsZero() && now.Sub(lastCleanup) < time.Minute {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastCleanup = now
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
for ip, c := range clients {
|
||||||
|
if now.Sub(c.lastSeen) > ttl {
|
||||||
|
delete(clients, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getClient := func(ip string, now time.Time) *ipClient {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
c, ok := clients[ip]
|
||||||
|
if !ok {
|
||||||
|
c = &ipClient{bucket: newTokenBucket(max, per, burst), lastSeen: now}
|
||||||
|
clients[ip] = c
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
c.lastSeen = now
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
now := time.Now()
|
||||||
|
cleanup(now)
|
||||||
|
|
||||||
|
ip := c.ClientIP()
|
||||||
|
client := getClient(ip, now)
|
||||||
|
|
||||||
|
if !client.bucket.allow() {
|
||||||
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||||
|
"error": "rate limit exceeded",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
64
internal/api/middleware/ratelimit_test.go
Normal file
64
internal/api/middleware/ratelimit_test.go
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRateLimitByIP_BlocksAfterLimit(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
// 1 request per hour, burst 1 => second immediate request should 429.
|
||||||
|
r.Use(RateLimitByIP(1, time.Hour, 1, time.Minute))
|
||||||
|
r.GET("/", func(c *gin.Context) { c.String(200, "ok") })
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.RemoteAddr = "203.0.113.10:1234"
|
||||||
|
|
||||||
|
w1 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w1, req)
|
||||||
|
if w1.Code != http.StatusOK {
|
||||||
|
t.Fatalf("first request code = %d, want %d", w1.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
w2 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w2, req)
|
||||||
|
if w2.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("second request code = %d, want %d", w2.Code, http.StatusTooManyRequests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRateLimitByIP_AllowsBurst(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
|
||||||
|
r := gin.New()
|
||||||
|
// 1 per hour, but burst 2 => first two immediate requests should pass.
|
||||||
|
r.Use(RateLimitByIP(1, time.Hour, 2, time.Minute))
|
||||||
|
r.GET("/", func(c *gin.Context) { c.String(200, "ok") })
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.RemoteAddr = "203.0.113.11:1234"
|
||||||
|
|
||||||
|
w1 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w1, req)
|
||||||
|
if w1.Code != http.StatusOK {
|
||||||
|
t.Fatalf("first request code = %d, want %d", w1.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
w2 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w2, req)
|
||||||
|
if w2.Code != http.StatusOK {
|
||||||
|
t.Fatalf("second request code = %d, want %d", w2.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
w3 := httptest.NewRecorder()
|
||||||
|
r.ServeHTTP(w3, req)
|
||||||
|
if w3.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("third request code = %d, want %d", w3.Code, http.StatusTooManyRequests)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -50,17 +49,15 @@ func (h *Handler) Login(c *gin.Context) {
|
|||||||
|
|
||||||
isSecure := os.Getenv("USE_HTTPS") == "true"
|
isSecure := os.Getenv("USE_HTTPS") == "true"
|
||||||
|
|
||||||
// Use http.SetCookie so we can set SameSite.
|
c.SetCookie(
|
||||||
http.SetCookie(c.Writer, &http.Cookie{
|
"auth_token",
|
||||||
Name: "auth_token",
|
token,
|
||||||
Value: token,
|
3600*24,
|
||||||
Path: "/",
|
"/",
|
||||||
Domain: os.Getenv("DOMAIN"),
|
os.Getenv("DOMAIN"),
|
||||||
MaxAge: 3600 * 24,
|
isSecure,
|
||||||
Secure: isSecure,
|
true, // httpOnly (IMPORTANT)
|
||||||
HttpOnly: true,
|
)
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
})
|
|
||||||
|
|
||||||
c.JSON(200, gin.H{"token": token})
|
c.JSON(200, gin.H{"token": token})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/api/middleware"
|
"ResendIt/internal/api/middleware"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -9,7 +10,9 @@ import (
|
|||||||
func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
||||||
auth := r.Group("/auth")
|
auth := r.Group("/auth")
|
||||||
|
|
||||||
auth.POST("/login", h.Login)
|
// Stricter rate limit on login to reduce brute-force / log spam.
|
||||||
|
// 5 attempts per minute per IP, burst 10.
|
||||||
|
auth.POST("/login", middleware.RateLimitByIP(5, time.Minute, 10, 15*time.Minute), h.Login)
|
||||||
|
|
||||||
protected := auth.Group("/")
|
protected := auth.Group("/")
|
||||||
protected.Use(middleware.AuthMiddleware())
|
protected.Use(middleware.AuthMiddleware())
|
||||||
|
|||||||
82
internal/auth/service_test.go
Normal file
82
internal/auth/service_test.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/security"
|
||||||
|
"ResendIt/internal/user"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestServiceLogin_InvalidUserDoesNotEnumerate(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&user.User{}); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := NewService(NewRepository(db))
|
||||||
|
|
||||||
|
_, err = svc.Login("does-not-exist", "whatever")
|
||||||
|
if err != ErrInvalidCredentials {
|
||||||
|
t.Fatalf("expected ErrInvalidCredentials for missing user, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServiceLogin_WrongPassword(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&user.User{}); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := security.HashPassword("right")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
u := user.User{Username: "alice", PasswordHash: hash, Role: "user"}
|
||||||
|
if err := db.Create(&u).Error; err != nil {
|
||||||
|
t.Fatalf("create user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := NewService(NewRepository(db))
|
||||||
|
_, err = svc.Login("alice", "wrong")
|
||||||
|
if err != ErrInvalidCredentials {
|
||||||
|
t.Fatalf("expected ErrInvalidCredentials for wrong password, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServiceLogin_SuccessReturnsJWT(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open sqlite: %v", err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&user.User{}); err != nil {
|
||||||
|
t.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := security.HashPassword("right")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("hash: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
u := user.User{Username: "alice", PasswordHash: hash, Role: "user"}
|
||||||
|
if err := db.Create(&u).Error; err != nil {
|
||||||
|
t.Fatalf("create user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := NewService(NewRepository(db))
|
||||||
|
token, err := svc.Login("alice", "right")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expected success, got error: %v", err)
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
t.Fatalf("expected non-empty jwt token")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/util"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -77,27 +78,12 @@ func (h *Handler) View(c *gin.Context) {
|
|||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, record.Filename))
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
c.File(record.Path)
|
c.File(record.Path)
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeFilename(name string) string {
|
|
||||||
// keep it simple: drop control chars and quotes
|
|
||||||
out := make([]rune, 0, len(name))
|
|
||||||
for _, r := range name {
|
|
||||||
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, r)
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
return "file"
|
|
||||||
}
|
|
||||||
return string(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
func isXSSRisk(filename string) bool {
|
func isXSSRisk(filename string) bool {
|
||||||
ext := filepath.Ext(filename)
|
ext := filepath.Ext(filename)
|
||||||
switch ext {
|
switch ext {
|
||||||
@@ -116,8 +102,8 @@ func (h *Handler) Download(c *gin.Context) {
|
|||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, record.Filename))
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
//c.Header("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; script-src 'none'; style-src 'none';")
|
//c.Header("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; script-src 'none'; style-src 'none';")
|
||||||
//c.Header("Content-Type", "application/octet-stream")
|
//c.Header("Content-Type", "application/octet-stream")
|
||||||
@@ -168,7 +154,7 @@ func (h *Handler) AdminDelete(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Redirect(303, "/admin")
|
c.Redirect(301, "/admin")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) AdminForceDelete(c *gin.Context) {
|
func (h *Handler) AdminForceDelete(c *gin.Context) {
|
||||||
@@ -185,7 +171,7 @@ func (h *Handler) AdminForceDelete(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Redirect(303, "/admin")
|
c.Redirect(301, "/admin")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Import(c *gin.Context) {
|
func (h *Handler) Import(c *gin.Context) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
|||||||
files := r.Group("/files")
|
files := r.Group("/files")
|
||||||
|
|
||||||
files.POST("/upload", h.Upload)
|
files.POST("/upload", h.Upload)
|
||||||
|
files.POST("/upload-multi", h.UploadMulti)
|
||||||
//files.GET("/download/:id", h.Download)
|
//files.GET("/download/:id", h.Download)
|
||||||
|
|
||||||
files.GET("/view/:id", h.View)
|
files.GET("/view/:id", h.View)
|
||||||
@@ -24,8 +25,8 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
|||||||
|
|
||||||
adminRoutes.GET("/download/:id", h.AdminGet)
|
adminRoutes.GET("/download/:id", h.AdminGet)
|
||||||
|
|
||||||
adminRoutes.POST("/delete/:id", h.AdminDelete)
|
adminRoutes.GET("/delete/:id", h.AdminDelete)
|
||||||
adminRoutes.POST("/delete/fr/:id", h.AdminForceDelete)
|
adminRoutes.GET("/delete/fr/:id", h.AdminForceDelete)
|
||||||
|
|
||||||
adminRoutes.POST("/import", h.Import)
|
adminRoutes.POST("/import", h.Import)
|
||||||
adminRoutes.GET("/export", h.Export)
|
adminRoutes.GET("/export", h.Export)
|
||||||
|
|||||||
57
internal/file/upload_multi.go
Normal file
57
internal/file/upload_multi.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UploadMulti accepts up to 10 files, zips them server-side, and returns a single download/view key.
|
||||||
|
func (h *Handler) UploadMulti(c *gin.Context) {
|
||||||
|
if err := c.Request.ParseMultipartForm(0); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
form, err := c.MultipartForm()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid multipart form"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
files := form.File["files"]
|
||||||
|
if len(files) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(files) > 50 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files (max 50)"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
once := c.PostForm("once") == "true"
|
||||||
|
|
||||||
|
durationStr := c.PostForm("duration")
|
||||||
|
hours, err := strconv.Atoi(durationStr)
|
||||||
|
if err != nil || hours <= 0 {
|
||||||
|
hours = 24
|
||||||
|
}
|
||||||
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
|
record, err := h.service.UploadBundle(files, once, duration)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
"id": record.ID,
|
||||||
|
"deletion_id": record.DeletionID,
|
||||||
|
"filename": record.Filename,
|
||||||
|
"size": record.Size,
|
||||||
|
"expires_at": record.ExpiresAt,
|
||||||
|
"view_key": record.ViewID,
|
||||||
|
})
|
||||||
|
}
|
||||||
159
internal/file/zip.go
Normal file
159
internal/file/zip.go
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/util"
|
||||||
|
"archive/zip"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func safeZipName(name string) string {
|
||||||
|
name = filepath.Base(name)
|
||||||
|
name = strings.ReplaceAll(name, "\\", "_")
|
||||||
|
name = strings.ReplaceAll(name, "/", "_")
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" || name == "." {
|
||||||
|
return "file"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func dedupeName(name string, seen map[string]int) string {
|
||||||
|
if _, ok := seen[name]; !ok {
|
||||||
|
seen[name] = 1
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
seen[name]++
|
||||||
|
ext := filepath.Ext(name)
|
||||||
|
base := strings.TrimSuffix(name, ext)
|
||||||
|
return fmt.Sprintf("%s (%d)%s", base, seen[name], ext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cuteZipName(fileCount int) string {
|
||||||
|
adjective := util.RandomAdjective()
|
||||||
|
verb := util.RandomVerb()
|
||||||
|
thing := util.RandomThing()
|
||||||
|
return fmt.Sprintf("%d%s%s%s.zip", fileCount, adjective, verb, thing)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadBundle zips multiple uploaded files into a single .zip stored on disk and tracked as one FileRecord.
|
||||||
|
func (s *Service) UploadBundle(files []*multipart.FileHeader, deleteAfterDownload bool, expiresAfter time.Duration) (*FileRecord, error) {
|
||||||
|
if len(files) == 0 {
|
||||||
|
return nil, errors.New("no files")
|
||||||
|
}
|
||||||
|
if len(files) > 50 {
|
||||||
|
return nil, errors.New("too many files (max 50)")
|
||||||
|
}
|
||||||
|
|
||||||
|
folderID := uuid.NewString()
|
||||||
|
folderPath := filepath.Join(s.storageDir, folderID)
|
||||||
|
if err := os.MkdirAll(folderPath, os.ModePerm); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
zipDiskName := uuid.NewString() + ".zip"
|
||||||
|
zipPath := filepath.Join(folderPath, zipDiskName)
|
||||||
|
|
||||||
|
out, err := os.Create(zipPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = out.Close()
|
||||||
|
if err != nil {
|
||||||
|
_ = os.Remove(zipPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
zw := zip.NewWriter(out)
|
||||||
|
defer func() { _ = zw.Close() }()
|
||||||
|
|
||||||
|
seen := map[string]int{}
|
||||||
|
for _, fh := range files {
|
||||||
|
rc, openErr := fh.Open()
|
||||||
|
if openErr != nil {
|
||||||
|
err = openErr
|
||||||
|
return nil, openErr
|
||||||
|
}
|
||||||
|
|
||||||
|
name := dedupeName(safeZipName(fh.Filename), seen)
|
||||||
|
h, _ := zip.FileInfoHeader(dummyFileInfo{name: name, size: fh.Size, mod: time.Now()})
|
||||||
|
h.Name = name
|
||||||
|
h.Method = zip.Deflate
|
||||||
|
|
||||||
|
w, createErr := zw.CreateHeader(h)
|
||||||
|
if createErr != nil {
|
||||||
|
_ = rc.Close()
|
||||||
|
err = createErr
|
||||||
|
return nil, createErr
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, copyErr := io.Copy(w, rc); copyErr != nil {
|
||||||
|
_ = rc.Close()
|
||||||
|
err = copyErr
|
||||||
|
return nil, copyErr
|
||||||
|
}
|
||||||
|
_ = rc.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
if closeErr := zw.Close(); closeErr != nil {
|
||||||
|
err = closeErr
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
if closeErr := out.Close(); closeErr != nil {
|
||||||
|
err = closeErr
|
||||||
|
return nil, closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
zipDisplayName := cuteZipName(len(files))
|
||||||
|
|
||||||
|
f := &FileRecord{
|
||||||
|
ID: folderID,
|
||||||
|
DeletionID: uuid.NewString(),
|
||||||
|
ViewID: uuid.NewString(),
|
||||||
|
Filename: zipDisplayName,
|
||||||
|
Path: zipPath,
|
||||||
|
Size: fileSize(zipPath),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
ExpiresAt: time.Now().Add(expiresAfter),
|
||||||
|
DeleteAfterDownload: deleteAfterDownload,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.repo.Create(f); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileSize(path string) int64 {
|
||||||
|
st, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return st.Size()
|
||||||
|
}
|
||||||
|
|
||||||
|
// dummyFileInfo provides minimal os.FileInfo for zip headers.
|
||||||
|
// This avoids relying on the underlying uploaded file having a real modtime.
|
||||||
|
// (zip.Writer can work without this too, but headers look nicer.)
|
||||||
|
type dummyFileInfo struct {
|
||||||
|
name string
|
||||||
|
size int64
|
||||||
|
mod time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d dummyFileInfo) Name() string { return d.name }
|
||||||
|
func (d dummyFileInfo) Size() int64 { return d.size }
|
||||||
|
func (d dummyFileInfo) Mode() os.FileMode { return 0o644 }
|
||||||
|
func (d dummyFileInfo) ModTime() time.Time { return d.mod }
|
||||||
|
func (d dummyFileInfo) IsDir() bool { return false }
|
||||||
|
func (d dummyFileInfo) Sys() any { return nil }
|
||||||
22
internal/security/password_test.go
Normal file
22
internal/security/password_test.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestHashAndCheckPassword(t *testing.T) {
|
||||||
|
pw := "correct horse battery staple"
|
||||||
|
|
||||||
|
hash, err := HashPassword(pw)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("HashPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
if hash == "" {
|
||||||
|
t.Fatalf("expected non-empty hash")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !CheckPassword(pw, hash) {
|
||||||
|
t.Fatalf("expected CheckPassword to succeed for correct password")
|
||||||
|
}
|
||||||
|
if CheckPassword("wrong", hash) {
|
||||||
|
t.Fatalf("expected CheckPassword to fail for wrong password")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
func HumanSize(size int64) string {
|
func HumanSize(size int64) string {
|
||||||
const unit = 1024
|
const unit = 1024
|
||||||
@@ -17,3 +20,24 @@ func HumanSize(size int64) string {
|
|||||||
"KMGTPE"[exp],
|
"KMGTPE"[exp],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SafeFilename(name string) string {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
|
||||||
|
out := make([]rune, 0, len(name))
|
||||||
|
for _, r := range name {
|
||||||
|
// block control chars (incl CR/LF/TAB), DEL, quotes, backslash
|
||||||
|
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return "file"
|
||||||
|
}
|
||||||
|
// optional: cap length
|
||||||
|
if len(out) > 200 {
|
||||||
|
out = out[:200]
|
||||||
|
}
|
||||||
|
return string(out)
|
||||||
|
}
|
||||||
|
|||||||
40
internal/util/util_test.go
Normal file
40
internal/util/util_test.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestHumanSize(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
in int64
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{0, "0 B"},
|
||||||
|
{1, "1 B"},
|
||||||
|
{1023, "1023 B"},
|
||||||
|
{1024, "1.0 KB"},
|
||||||
|
{1024 * 1024, "1.0 MB"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := HumanSize(tt.in); got != tt.want {
|
||||||
|
t.Fatalf("HumanSize(%d) = %q, want %q", tt.in, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSafeFilename(t *testing.T) {
|
||||||
|
if got := SafeFilename(" hello.txt "); got != "hello.txt" {
|
||||||
|
t.Fatalf("expected trimmed filename, got %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strips control characters, quotes, and backslashes.
|
||||||
|
in := "a\n\rb\t\"c\\d"
|
||||||
|
got := SafeFilename(in)
|
||||||
|
if got != "abcd" {
|
||||||
|
t.Fatalf("SafeFilename(%q) = %q, want %q", in, got, "abcd")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Empty after sanitization becomes default.
|
||||||
|
if got := SafeFilename("\n\r\t"); got != "file" {
|
||||||
|
t.Fatalf("expected default filename, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
47
internal/util/worldlist.go
Normal file
47
internal/util/worldlist.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package util
|
||||||
|
|
||||||
|
import "math/rand"
|
||||||
|
|
||||||
|
var Adjectives = []string{
|
||||||
|
"Cool", "Super", "Hot", "Spicy", "Sneaky", "Sleepy", "Tiny", "Mega", "Cosmic", "Silly",
|
||||||
|
"Cursed", "Blessed", "Wiggly", "Giga", "Chonky", "Shiny", "Angry", "Happy", "Soft", "Turbo",
|
||||||
|
"Zany", "Snappy", "Fluffy", "Cranky", "Glitchy", "Bubbly", "Frosty", "Electric", "Jolly", "Mystic",
|
||||||
|
"Weird", "Chunky", "Psycho", "Cheesy", "Smelly", "Slippery", "Fiery", "Wacky", "Vivid", "Hyper",
|
||||||
|
"Soggy", "Grumpy", "Luminous", "Spooky", "Funky", "Twisted", "Nifty", "Prickly", "Velvet", "Epic",
|
||||||
|
"Glorious", "Majestic", "Quirky", "Radiant", "Sneaky", "Bouncy", "Mysterious", "Noodle", "Raging", "Zesty",
|
||||||
|
"Shimmering", "Fabled", "Plush", "Snazzy", "Stormy", "Gleaming", "Vibrant", "Odd", "Tasty", "Whimsical",
|
||||||
|
"Feral", "Clever", "Jumpy", "Dizzy", "Wicked", "Chilly", "Hasty", "Bizarre", "Snug", "Cheerful",
|
||||||
|
}
|
||||||
|
|
||||||
|
var Things = []string{
|
||||||
|
"Potato", "Griefers", "Raccoons", "Pigeons", "Wizards", "Ninjas", "Pickles", "Dragons", "Goblins", "Burgers",
|
||||||
|
"Pancakes", "Hamsters", "Bananas", "Comets", "Robots", "Cats", "Kiwis", "Frogs", "Cupcakes", "Sprites",
|
||||||
|
"Monsters", "Aliens", "Slimes", "Tacos", "Unicorns", "Ghosts", "Snails", "Vampires", "Donuts", "Owls",
|
||||||
|
"Zombies", "Mermaids", "Beavers", "Octopuses", "Chickens", "Penguins", "Mushrooms", "Felines", "Llamas", "Waffles",
|
||||||
|
"Baboons", "Dragettes", "Pixies", "Sharks", "Elephants", "Squirrels", "Gnomes", "Wombats", "Cacti", "Puppets",
|
||||||
|
"Koalas", "Moose", "Yeti", "Bats", "Crabs", "Otters", "Trolls", "Geckos", "Parrots", "Snakes",
|
||||||
|
"Sloths", "Clowns", "Jellyfish", "Froggies", "Dragoneers", "Nuggets", "Sprites", "Critters", "Knights", "Squids",
|
||||||
|
"Tigers", "Foxes", "Penguinos", "Burglebugs", "Clouds", "Fireflies", "Shrooms", "Mice", "Wizards", "Berries",
|
||||||
|
}
|
||||||
|
|
||||||
|
var Verbs = []string{
|
||||||
|
"Zoom", "Bonk", "Yeet", "Vibe", "Hack", "Spark", "Bounce", "Nibble", "Smuggle", "Cook",
|
||||||
|
"Flick", "Slap", "Whack", "Zap", "Blast", "Slam", "Twist", "Flip", "Slide", "Crash",
|
||||||
|
"Pop", "Fling", "Snatch", "Boing", "Sizzle", "Clap", "Roar", "Sniff", "Swoop", "Blink",
|
||||||
|
"Dodge", "Smash", "Roll", "Twirl", "Snore", "Drip", "Slurp", "Chomp", "Shuffle", "Juggle",
|
||||||
|
"Bounce", "Whirl", "Gush", "Spit", "Frolic", "Honk", "Wiggle", "Crackle", "Pounce", "Sprinkle",
|
||||||
|
"Slam", "Zoomerang", "Flop", "Squish", "Boop", "Whiz", "Flipflop", "Snip", "Glide", "Zapzap",
|
||||||
|
"Bop", "Wobble", "Fumble", "Twinkle", "Splash", "Dribble", "Clobber", "Whackadoo", "Bounceback", "Snizzle",
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomAdjective() string {
|
||||||
|
return Adjectives[rand.Intn(len(Adjectives))]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomThing() string {
|
||||||
|
return Things[rand.Intn(len(Things))]
|
||||||
|
}
|
||||||
|
|
||||||
|
func RandomVerb() string {
|
||||||
|
return Verbs[rand.Intn(len(Verbs))]
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package web
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -70,10 +71,35 @@ func (h *Handler) AdminPage(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only check files on the current page.
|
||||||
|
// Status meanings:
|
||||||
|
// - green: file exists on disk
|
||||||
|
// - red: file missing
|
||||||
|
// - rainbow: stat error (something unexpected)
|
||||||
|
type AdminFileView struct {
|
||||||
|
file.FileRecord
|
||||||
|
ActualStatus string
|
||||||
|
}
|
||||||
|
|
||||||
|
adminFiles := make([]AdminFileView, 0, len(files))
|
||||||
|
for _, f := range files {
|
||||||
|
status := "red"
|
||||||
|
if f.Path != "" {
|
||||||
|
if _, err := os.Stat(f.Path); err == nil {
|
||||||
|
status = "green"
|
||||||
|
} else if os.IsNotExist(err) {
|
||||||
|
status = "red"
|
||||||
|
} else {
|
||||||
|
status = "rainbow"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
adminFiles = append(adminFiles, AdminFileView{FileRecord: f, ActualStatus: status})
|
||||||
|
}
|
||||||
|
|
||||||
totalPages := (totalCount + limit - 1) / limit
|
totalPages := (totalCount + limit - 1) / limit
|
||||||
|
|
||||||
c.HTML(200, "admin.html", gin.H{
|
c.HTML(200, "admin.html", gin.H{
|
||||||
"Files": files,
|
"Files": adminFiles,
|
||||||
"Page": page,
|
"Page": page,
|
||||||
"TotalPages": totalPages,
|
"TotalPages": totalPages,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -16,6 +16,24 @@
|
|||||||
td { border: 1px solid #000; padding: 10px; font-size: 13px; font-weight: 500; }
|
td { border: 1px solid #000; padding: 10px; font-size: 13px; font-weight: 500; }
|
||||||
tr:hover { background: #ffff00; }
|
tr:hover { background: #ffff00; }
|
||||||
|
|
||||||
|
/* Actual file status dot */
|
||||||
|
.dot { width: 12px; height: 12px; border: 2px solid #000; display: inline-block; }
|
||||||
|
.dot-green { background: #00ff00; }
|
||||||
|
.dot-red { background: #ff0000; }
|
||||||
|
.dot-rainbow {
|
||||||
|
animation: rainbow 0.8s linear infinite;
|
||||||
|
background: red;
|
||||||
|
}
|
||||||
|
@keyframes rainbow {
|
||||||
|
0% { background: #ff0000; }
|
||||||
|
16% { background: #ff9900; }
|
||||||
|
33% { background: #ffff00; }
|
||||||
|
50% { background: #00ff00; }
|
||||||
|
66% { background: #00ccff; }
|
||||||
|
83% { background: #9900ff; }
|
||||||
|
100% { background: #ff0000; }
|
||||||
|
}
|
||||||
|
|
||||||
/* Harsh Status Tags */
|
/* Harsh Status Tags */
|
||||||
.status-tag { font-weight: 900; font-size: 11px; padding: 3px 6px; border: 2px solid #000; display: inline-block; text-transform: uppercase; }
|
.status-tag { font-weight: 900; font-size: 11px; padding: 3px 6px; border: 2px solid #000; display: inline-block; text-transform: uppercase; }
|
||||||
.status-deleted { background: #000; color: #ff0000; }
|
.status-deleted { background: #000; color: #ff0000; }
|
||||||
@@ -109,12 +127,13 @@
|
|||||||
<th>Hits</th>
|
<th>Hits</th>
|
||||||
<th>Burn</th>
|
<th>Burn</th>
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
|
<th>Actual</th>
|
||||||
<th>System_Actions</th>
|
<th>System_Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{{if not .Files}}
|
{{if not .Files}}
|
||||||
<tr><td colspan="7" class="text-center py-10 font-bold uppercase italic">Zero files in buffer</td></tr>
|
<tr><td colspan="8" class="text-center py-10 font-bold uppercase italic">Zero files in buffer</td></tr>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{range .Files}}
|
{{range .Files}}
|
||||||
<tr>
|
<tr>
|
||||||
@@ -147,16 +166,24 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
|
<td class="text-center">
|
||||||
|
{{if eq .ActualStatus "green"}}
|
||||||
|
<span class="dot dot-green" title="File exists"></span>
|
||||||
|
{{else if eq .ActualStatus "red"}}
|
||||||
|
<span class="dot dot-red" title="File missing"></span>
|
||||||
|
{{else}}
|
||||||
|
<span class="dot dot-rainbow" title="Stat error"></span>
|
||||||
|
{{end}}
|
||||||
|
</td>
|
||||||
|
|
||||||
<td>
|
<td>
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
{{if not .Deleted}}
|
{{if not .Deleted}}
|
||||||
<form action="/api/files/admin/delete/{{.ID}}" method="POST" onsubmit="return openConfirm(event, 'TERMINATE', 'Kill this file? It will be removed from active storage.')">
|
<form action="/api/files/admin/delete/{{.ID}}" method="GET" onsubmit="return openConfirm(event, 'TERMINATE', 'Kill this file? It will be removed from active storage.')">
|
||||||
<input type="hidden" name="_csrf" class="csrf-field">
|
|
||||||
<button type="submit" style="background: #ffcccc;">Terminate</button>
|
<button type="submit" style="background: #ffcccc;">Terminate</button>
|
||||||
</form>
|
</form>
|
||||||
{{end}}
|
{{end}}
|
||||||
<form action="/api/files/admin/delete/fr/{{.ID}}" method="POST" onsubmit="return openConfirm(event, 'FULL_WIPE', 'Wiping file and purging record? This is a permanent database scrub.')">
|
<form action="/api/files/admin/delete/fr/{{.ID}}" method="GET" onsubmit="return openConfirm(event, 'FULL_WIPE', 'Wiping file and purging record? This is a permanent database scrub.')">
|
||||||
<input type="hidden" name="_csrf" class="csrf-field">
|
|
||||||
<button type="submit">Full_Wipe</button>
|
<button type="submit">Full_Wipe</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
@@ -204,13 +231,6 @@
|
|||||||
currentForm = null;
|
currentForm = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill CSRF hidden inputs from cookie (double-submit pattern)
|
|
||||||
(function fillCSRF() {
|
|
||||||
const m = document.cookie.match('(^|;)\\s*csrf_token\\s*=\\s*([^;]+)');
|
|
||||||
const tok = m ? m.pop() : '';
|
|
||||||
document.querySelectorAll('.csrf-field').forEach(el => el.value = tok);
|
|
||||||
})();
|
|
||||||
|
|
||||||
document.getElementById('modal-confirm-btn').addEventListener('click', () => {
|
document.getElementById('modal-confirm-btn').addEventListener('click', () => {
|
||||||
if (currentForm) {
|
if (currentForm) {
|
||||||
currentForm.submit();
|
currentForm.submit();
|
||||||
|
|||||||
@@ -258,12 +258,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const m = document.cookie.match('(^|;)\\s*csrf_token\\s*=\\s*([^;]+)');
|
|
||||||
const csrf = m ? m.pop() : '';
|
|
||||||
|
|
||||||
const res = await fetch('/api/user/change-password', {
|
const res = await fetch('/api/user/change-password', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
old_password: current,
|
old_password: current,
|
||||||
new_password: nv
|
new_password: nv
|
||||||
|
|||||||
@@ -102,7 +102,7 @@
|
|||||||
|
|
||||||
<div id="upload-ui">
|
<div id="upload-ui">
|
||||||
<div id="drop-zone" class="drop-zone mb-4">
|
<div id="drop-zone" class="drop-zone mb-4">
|
||||||
<input type="file" id="fileInput" class="hidden">
|
<input type="file" id="fileInput" class="hidden" multiple>
|
||||||
|
|
||||||
<div id="dz-content">
|
<div id="dz-content">
|
||||||
<span id="dz-text" class="text-sm">Click to select or drop file</span>
|
<span id="dz-text" class="text-sm">Click to select or drop file</span>
|
||||||
@@ -232,20 +232,36 @@
|
|||||||
|
|
||||||
input.onchange = () => {
|
input.onchange = () => {
|
||||||
if (input.files.length) {
|
if (input.files.length) {
|
||||||
showFile(input.files[0]);
|
showFiles(input.files);
|
||||||
uploadBtn.disabled = false;
|
uploadBtn.disabled = false;
|
||||||
} else {
|
} else {
|
||||||
uploadBtn.disabled = true;
|
uploadBtn.disabled = true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function showFile(file) {
|
function showFiles(fileList) {
|
||||||
|
const files = Array.from(fileList || []);
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
const total = files.reduce((acc, f) => acc + f.size, 0);
|
||||||
|
|
||||||
|
if (files.length === 1) {
|
||||||
document.getElementById('dz-text').innerText =
|
document.getElementById('dz-text').innerText =
|
||||||
`${file.name} (${formatBytes(file.size)})`;
|
`${files[0].name} (${formatBytes(files[0].size)})`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('dz-text').innerText =
|
||||||
|
`${files.length} FILES (${formatBytes(total)}) — will be zipped`;
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadBtn.onclick = () => {
|
uploadBtn.onclick = () => {
|
||||||
if (input.files.length) handleUpload(input.files[0]);
|
if (!input.files.length) return;
|
||||||
|
if (input.files.length === 1) {
|
||||||
|
handleUploadSingle(input.files[0]);
|
||||||
|
} else {
|
||||||
|
handleUploadMulti(input.files);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
cancelBtn.onclick = (e) => {
|
cancelBtn.onclick = (e) => {
|
||||||
@@ -257,7 +273,15 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleUpload(file) {
|
function commonFormData() {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("once", document.getElementById("once").checked ? "true" : "false");
|
||||||
|
const hours = parseInt(document.getElementById("duration").value, 10);
|
||||||
|
fd.append("duration", hours);
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startUploadUI() {
|
||||||
uploadBtn.disabled = true;
|
uploadBtn.disabled = true;
|
||||||
uploadBtn.innerText = "UPLOADING...";
|
uploadBtn.innerText = "UPLOADING...";
|
||||||
cancelBtn.classList.remove('hidden');
|
cancelBtn.classList.remove('hidden');
|
||||||
@@ -265,16 +289,9 @@
|
|||||||
progressContainer.classList.remove("hidden");
|
progressContainer.classList.remove("hidden");
|
||||||
progressText.classList.remove("hidden");
|
progressText.classList.remove("hidden");
|
||||||
statsText.classList.remove("hidden");
|
statsText.classList.remove("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
const fd = new FormData();
|
function setupXHRHandlers(xhr) {
|
||||||
fd.append("file", file);
|
|
||||||
fd.append("once", document.getElementById("once").checked ? "true" : "false");
|
|
||||||
const hours = parseInt(document.getElementById("duration").value, 10);
|
|
||||||
fd.append("duration", hours);
|
|
||||||
|
|
||||||
const xhr = new XMLHttpRequest();
|
|
||||||
currentXhr = xhr;
|
|
||||||
|
|
||||||
let startTime = Date.now();
|
let startTime = Date.now();
|
||||||
|
|
||||||
xhr.upload.onprogress = (e) => {
|
xhr.upload.onprogress = (e) => {
|
||||||
@@ -301,7 +318,6 @@
|
|||||||
const data = JSON.parse(xhr.responseText);
|
const data = JSON.parse(xhr.responseText);
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
|
|
||||||
// Redirect using view key
|
|
||||||
window.location.href = "/f/" + data.view_key;
|
window.location.href = "/f/" + data.view_key;
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -319,11 +335,38 @@
|
|||||||
location.reload();
|
location.reload();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUploadSingle(file) {
|
||||||
|
startUploadUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
setupXHRHandlers(xhr);
|
||||||
|
|
||||||
xhr.open("POST", "/api/files/upload");
|
xhr.open("POST", "/api/files/upload");
|
||||||
xhr.send(fd);
|
xhr.send(fd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleUploadMulti(fileList) {
|
||||||
|
startUploadUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
Array.from(fileList).forEach(f => fd.append("files", f));
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
setupXHRHandlers(xhr);
|
||||||
|
|
||||||
|
xhr.open("POST", "/api/files/upload-multi");
|
||||||
|
xhr.send(fd);
|
||||||
|
}
|
||||||
|
|
||||||
function copy(id) {
|
function copy(id) {
|
||||||
const el = document.getElementById(id);
|
const el = document.getElementById(id);
|
||||||
el.select();
|
el.select();
|
||||||
|
|||||||
@@ -127,14 +127,10 @@
|
|||||||
const password = document.getElementById("password").value;
|
const password = document.getElementById("password").value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const m = document.cookie.match('(^|;)\\s*csrf_token\\s*=\\s*([^;]+)');
|
|
||||||
const csrf = m ? m.pop() : '';
|
|
||||||
|
|
||||||
const res = await fetch("/api/auth/login", {
|
const res = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json"
|
||||||
"X-CSRF-Token": csrf
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
username: username,
|
username: username,
|
||||||
|
|||||||
Reference in New Issue
Block a user