Compare commits
46 Commits
e2d8bd344d
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| a91b9b36d3 | |||
| 1a82f21202 | |||
| d1f6782c96 | |||
| ca25cdd924 | |||
| a7541b322b | |||
|
|
84af348da7 | ||
|
|
73b67ab61d | ||
| 9aeb7faa15 | |||
| 1566ccf348 | |||
| 6065b4d95f | |||
| 8ae5dfc483 | |||
| 0ce248b2f9 | |||
| e2f1bbcd64 | |||
| afcb4d72f5 | |||
| b0d1f17540 | |||
| fc85e859e0 | |||
| 3116d53b65 | |||
| 16c636dc94 | |||
| bf21ccdccd | |||
| 5be74d9402 | |||
| a9a59a4f90 | |||
| a0973373af | |||
| 23a2951f8c | |||
| ead2b18991 | |||
| 781e4f3100 | |||
| c2d799eb18 | |||
| b4bbaf25c9 | |||
| 524f2deb50 | |||
| b3dcdf09be | |||
| c478a4306a | |||
| 6d60a8663e | |||
| b9c40596b3 | |||
| b31d39d971 | |||
| 253308dcc5 | |||
| 90d1c1b562 | |||
| 1fe45eaed1 | |||
| a6979805c1 | |||
| 644cf426d6 | |||
| f11c758008 | |||
| bfeeaa1190 | |||
| ad656fd636 | |||
|
|
fa8c6d02fd | ||
|
|
fc67533db9 | ||
| ccb4ff7ecb | |||
|
|
ba06fb0c7c | ||
|
|
d9de02f08d |
@@ -1,3 +1,4 @@
|
|||||||
uploads/**
|
uploads/**
|
||||||
data/**
|
data/**
|
||||||
logs/**
|
logs/**
|
||||||
|
tmp/**
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,4 +2,5 @@
|
|||||||
|
|
||||||
data/**
|
data/**
|
||||||
uploads/**
|
uploads/**
|
||||||
|
tmp/**
|
||||||
.env
|
.env
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
FROM golang:1.26-alpine AS builder
|
FROM golang:1.26-alpine AS builder
|
||||||
|
|
||||||
|
ARG GIT_COMMIT=dev
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ COPY . .
|
|||||||
ENV CGO_ENABLED=1
|
ENV CGO_ENABLED=1
|
||||||
ENV GIN_MODE=release
|
ENV GIN_MODE=release
|
||||||
|
|
||||||
RUN go build -o app ./cmd/server
|
RUN go build -ldflags "-X ResendIt/internal/buildinfo.Commit=${GIT_COMMIT}" -o app ./cmd/server
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
|
||||||
@@ -24,11 +25,12 @@ RUN apk add --no-cache ca-certificates tzdata
|
|||||||
COPY --from=builder /app/app .
|
COPY --from=builder /app/app .
|
||||||
COPY --from=builder /app/templates ./templates
|
COPY --from=builder /app/templates ./templates
|
||||||
COPY --from=builder /app/static ./static
|
COPY --from=builder /app/static ./static
|
||||||
COPY --from=builder /app/.env ./
|
|
||||||
|
|
||||||
RUN mkdir -p /app/uploads
|
RUN mkdir -p /app/uploads
|
||||||
|
RUN mkdir -p /app/tmp
|
||||||
|
|
||||||
RUN adduser -D appuser
|
RUN adduser -D appuser
|
||||||
|
RUN chown -R appuser:appuser /app
|
||||||
USER appuser
|
USER appuser
|
||||||
|
|
||||||
ENV GIN_MODE=release
|
ENV GIN_MODE=release
|
||||||
|
|||||||
115
Jenkinsfile
vendored
Normal file
115
Jenkinsfile
vendored
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
pipeline {
|
||||||
|
agent any
|
||||||
|
|
||||||
|
options {
|
||||||
|
timestamps()
|
||||||
|
disableConcurrentBuilds()
|
||||||
|
}
|
||||||
|
|
||||||
|
environment {
|
||||||
|
REGISTRY = "git.brammie15.dev"
|
||||||
|
IMAGE_NAME = "brammie15/resendit"
|
||||||
|
REGISTRY_CREDS = "registry-creds"
|
||||||
|
IMAGE = "${REGISTRY}/${IMAGE_NAME}"
|
||||||
|
DD_URL = "https://DD.brammie15.dev"
|
||||||
|
DD_API_KEY = credentials('dd-api-key')
|
||||||
|
NVD_API_KEY = credentials("nvd-api-key")
|
||||||
|
}
|
||||||
|
|
||||||
|
stages {
|
||||||
|
|
||||||
|
stage('Debug') {
|
||||||
|
steps {
|
||||||
|
sh 'echo "WORKSPACE: $WORKSPACE" && echo "PWD: $(pwd)" && ls -la'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Checkout') {
|
||||||
|
steps {
|
||||||
|
checkout scm
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stage('SAST - Semgrep') {
|
||||||
|
// steps {
|
||||||
|
// sh """
|
||||||
|
// docker run --rm -v "\$(pwd):/src" \
|
||||||
|
// returntocorp/semgrep:latest \
|
||||||
|
// semgrep scan --config=auto --debug \
|
||||||
|
// --json --output /src/semgrep.json \
|
||||||
|
// /src/internal /src/cmd || true
|
||||||
|
//
|
||||||
|
// echo "After semgrep:"
|
||||||
|
// ls -la
|
||||||
|
// """
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// stage('Upload to DefectDojo') {
|
||||||
|
// steps {
|
||||||
|
// sh """
|
||||||
|
// curl -X POST "${DD_URL}/api/v2/import-scan/" \
|
||||||
|
// -H "Authorization: Token ${DD_API_KEY}" \
|
||||||
|
// -F "scan_type=Semgrep JSON Report" \
|
||||||
|
// -F "file=@\$(pwd)/semgrep.json" \
|
||||||
|
// -F "product_name=Sendit" \
|
||||||
|
// -F "engagement_name=Jenkins-CI" \
|
||||||
|
// -F "auto_create_context=true" \
|
||||||
|
// -F "close_old_findings=true"
|
||||||
|
// """
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
stage('Build image') {
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
def shortSha = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||||
|
env.IMAGE_TAG_SHA = shortSha
|
||||||
|
sh """
|
||||||
|
docker build \
|
||||||
|
--build-arg GIT_COMMIT=${IMAGE_TAG_SHA} \
|
||||||
|
-t ${IMAGE}:${IMAGE_TAG_SHA} .
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Login to registry') {
|
||||||
|
steps {
|
||||||
|
withCredentials([usernamePassword(credentialsId: "${REGISTRY_CREDS}", usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) {
|
||||||
|
sh 'echo "$REG_PASS" | docker login ${REGISTRY} -u "$REG_USER" --password-stdin'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Push image') {
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
sh "docker push ${IMAGE}:${IMAGE_TAG_SHA}"
|
||||||
|
def branch = (env.BRANCH_NAME ?: sh(script: 'git rev-parse --abbrev-ref HEAD', returnStdout: true).trim())
|
||||||
|
def safeBranch = branch.replaceAll('[^a-zA-Z0-9_.-]', '-')
|
||||||
|
sh """
|
||||||
|
docker tag ${IMAGE}:${IMAGE_TAG_SHA} ${IMAGE}:${safeBranch}
|
||||||
|
docker push ${IMAGE}:${safeBranch}
|
||||||
|
"""
|
||||||
|
if (branch == 'master') {
|
||||||
|
sh """
|
||||||
|
docker tag ${IMAGE}:${IMAGE_TAG_SHA} ${IMAGE}:latest
|
||||||
|
docker push ${IMAGE}:latest
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
post {
|
||||||
|
always {
|
||||||
|
sh 'docker logout ${REGISTRY} || true'
|
||||||
|
sh 'docker image rm -f ${IMAGE}:${IMAGE_TAG_SHA} || true'
|
||||||
|
sh 'docker image prune -f || true'
|
||||||
|
// sh 'rm -f semgrep.sarif || true'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
"ResendIt/internal/auth"
|
"ResendIt/internal/auth"
|
||||||
|
"ResendIt/internal/config"
|
||||||
"ResendIt/internal/db"
|
"ResendIt/internal/db"
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
|
"ResendIt/internal/logger"
|
||||||
"ResendIt/internal/user"
|
"ResendIt/internal/user"
|
||||||
"ResendIt/internal/util"
|
"ResendIt/internal/util"
|
||||||
"ResendIt/internal/web"
|
"ResendIt/internal/web"
|
||||||
@@ -14,6 +17,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"
|
||||||
@@ -25,18 +29,37 @@ func main() {
|
|||||||
fmt.Printf("Error loading .env file\n")
|
fmt.Printf("Error loading .env file\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
os.Setenv("LOG_FORMAT", "json")
|
||||||
|
|
||||||
|
logger.Log.Info().Str("type", "startup").Msg("Starting ReSendIt")
|
||||||
|
|
||||||
dbCon, err := db.Connect()
|
dbCon, err := db.Connect()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Errorf("failed to connect database: %w", err))
|
logger.Log.Fatal().Err(err).Str("type", "startup").Msg("Failed to connect to database")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{})
|
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{}, &config.ConfigEntry{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error migrating database: %v\n", err)
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Database migration failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
r := gin.Default()
|
// create temp folder
|
||||||
|
path := "./tmp"
|
||||||
|
if os.IsExist(os.Mkdir(path, os.ModePerm)) {
|
||||||
|
logger.Log.Info().Str("type", "startup").Msg("Temp folder already exists")
|
||||||
|
} else {
|
||||||
|
if err := os.MkdirAll(path, os.ModePerm); err != nil {
|
||||||
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Failed to create temp folder")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use gin.New() instead of gin.Default() to have custom middleware
|
||||||
|
r := gin.New()
|
||||||
|
// Add structured logging and recovery middleware
|
||||||
|
r.Use(middleware.StructuredLogger())
|
||||||
|
r.Use(gin.Recovery())
|
||||||
|
|
||||||
r.MaxMultipartMemory = 10 << 30
|
r.MaxMultipartMemory = 10 << 30
|
||||||
r.SetFuncMap(template.FuncMap{
|
r.SetFuncMap(template.FuncMap{
|
||||||
@@ -46,9 +69,11 @@ func main() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
r.LoadHTMLGlob("templates/*.html")
|
r.LoadHTMLGlob("templates/*.html")
|
||||||
//r.LoadHTMLGlob("internal/templates/new/*.html")
|
|
||||||
r.Static("/static", "./static")
|
r.Static("/static", "./static")
|
||||||
|
|
||||||
|
// Add request ID middleware
|
||||||
|
r.Use(middleware.RequestIDMiddleware())
|
||||||
|
|
||||||
r.GET("/ping", func(c *gin.Context) {
|
r.GET("/ping", func(c *gin.Context) {
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"message": "hello",
|
"message": "hello",
|
||||||
@@ -67,19 +92,37 @@ func main() {
|
|||||||
userService := user.NewService(userRepo)
|
userService := user.NewService(userRepo)
|
||||||
userHandler := user.NewHandler(userService)
|
userHandler := user.NewHandler(userService)
|
||||||
|
|
||||||
|
configRepo := config.NewRepository(dbCon)
|
||||||
|
configService := config.NewService(configRepo)
|
||||||
|
|
||||||
|
if err := configService.EnsureDefaults(); err != nil {
|
||||||
|
logger.Log.Fatal().Err(err).Str("type", "startup").Msg("Failed to ensure config defaults")
|
||||||
|
}
|
||||||
|
|
||||||
fileRepo := file.NewRepository(dbCon)
|
fileRepo := file.NewRepository(dbCon)
|
||||||
fileService := file.NewService(fileRepo, "./uploads")
|
fileService := file.NewService(fileRepo, "./uploads")
|
||||||
fileHandler := file.NewHandler(fileService)
|
fileHandler := file.NewHandler(fileService, configService)
|
||||||
|
|
||||||
createAdminUser(userService)
|
createAdminUser(userService)
|
||||||
|
|
||||||
apiRoute := r.Group("/api")
|
apiRoute := r.Group("/api")
|
||||||
|
// General API rate limiting to reduce abuse/spam.
|
||||||
|
apiRoute.Use(middleware.RateLimitByIPDynamic(
|
||||||
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst)
|
||||||
|
},
|
||||||
|
5*time.Minute,
|
||||||
|
))
|
||||||
|
|
||||||
auth.RegisterRoutes(apiRoute, authHandler)
|
auth.RegisterRoutes(apiRoute, authHandler, configService)
|
||||||
user.RegisterRoutes(apiRoute, userHandler)
|
user.RegisterRoutes(apiRoute, userHandler)
|
||||||
file.RegisterRoutes(apiRoute, fileHandler)
|
file.RegisterRoutes(apiRoute, fileHandler)
|
||||||
|
|
||||||
webHandler := web.NewHandler(fileService)
|
webHandler := web.NewHandler(fileService, configService)
|
||||||
web.RegisterRoutes(r, webHandler, userService)
|
web.RegisterRoutes(r, webHandler, userService)
|
||||||
|
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
@@ -87,8 +130,21 @@ func main() {
|
|||||||
port = "8080"
|
port = "8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
domain := os.Getenv("DOMAIN")
|
||||||
|
if domain == "" {
|
||||||
|
domain = "http://localhost:" + port + "/"
|
||||||
|
os.Setenv("DOMAIN", domain)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Log.Info().
|
||||||
|
Str("type", "startup").
|
||||||
|
Str("port", port).
|
||||||
|
Str("domain", domain).
|
||||||
|
Msg("Server starting")
|
||||||
|
|
||||||
err = r.Run(":" + port)
|
err = r.Run(":" + port)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Server failed to start")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,15 +161,15 @@ func createAdminUser(service *user.Service) {
|
|||||||
_, err := service.FindByUsername("admin")
|
_, err := service.FindByUsername("admin")
|
||||||
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fmt.Println("Admin user already exists, skipping creation")
|
logger.Log.Info().Str("type", "startup").Msg("Admin user already exists")
|
||||||
return
|
return
|
||||||
} else if errors.Is(err, user.ErrUserNotFound) {
|
} else if errors.Is(err, user.ErrUserNotFound) {
|
||||||
fmt.Println("Admin user not found, creating new admin user")
|
logger.Log.Info().Str("type", "startup").Msg("Creating admin user")
|
||||||
|
|
||||||
password := generateRandomPassword(16)
|
password := generateRandomPassword(16)
|
||||||
adminUser, err := service.CreateUser("admin", password, "admin")
|
adminUser, err := service.CreateUser("admin", password, "admin")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error creating admin user: %v\n", err)
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Failed to create admin user")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,13 +177,16 @@ func createAdminUser(service *user.Service) {
|
|||||||
_, err = service.UpdateUser(adminUser)
|
_, err = service.UpdateUser(adminUser)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error creating admin user: %v\n", err)
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Failed to update admin user")
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("Admin user created with random password: %s\n", password)
|
logger.Log.Info().
|
||||||
|
Str("type", "startup").
|
||||||
|
Str("password", password).
|
||||||
|
Msg("Admin user created")
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("Error checking for admin user: %v\n", err)
|
logger.Log.Error().Err(err).Str("type", "startup").Msg("Error checking for admin user")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
JWT_SECRET: supersecretkey
|
JWT_SECRET: supersecretkey
|
||||||
PORT: 8000
|
PORT: 8000
|
||||||
ADMIN_PASSWORD: ""
|
|
||||||
|
|
||||||
DB_TYPE: sqlite
|
DB_TYPE: sqlite
|
||||||
DATABASE_URL: ./data/database.db
|
DATABASE_URL: ./data/database.db
|
||||||
|
|
||||||
|
LOG_FORMAT: "json"
|
||||||
|
|
||||||
DOMAIN: ""
|
DOMAIN: ""
|
||||||
USE_HTTPS: "false"
|
USE_HTTPS: "false"
|
||||||
|
|
||||||
|
|||||||
2
go.mod
2
go.mod
@@ -7,6 +7,7 @@ require (
|
|||||||
github.com/golang-jwt/jwt/v4 v4.5.2
|
github.com/golang-jwt/jwt/v4 v4.5.2
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
|
github.com/rs/zerolog v1.33.0
|
||||||
golang.org/x/crypto v0.49.0
|
golang.org/x/crypto v0.49.0
|
||||||
gorm.io/driver/mysql v1.6.0
|
gorm.io/driver/mysql v1.6.0
|
||||||
gorm.io/driver/postgres v1.6.0
|
gorm.io/driver/postgres v1.6.0
|
||||||
@@ -37,6 +38,7 @@ require (
|
|||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
|||||||
12
go.sum
12
go.sum
@@ -8,6 +8,7 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD
|
|||||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||||
|
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@@ -31,6 +32,7 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
|||||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||||
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
|
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
|
||||||
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
@@ -58,6 +60,10 @@ github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzh
|
|||||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
@@ -69,12 +75,16 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
|||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||||
|
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||||
|
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
|
||||||
|
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
@@ -103,7 +113,9 @@ golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
|||||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ type Claims struct {
|
|||||||
|
|
||||||
func AuthMiddleware() gin.HandlerFunc {
|
func AuthMiddleware() gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
|
log := StructuredLog(c).With().
|
||||||
|
Str("event", "auth_middleware").
|
||||||
|
Logger()
|
||||||
|
|
||||||
var tokenString string
|
var tokenString string
|
||||||
|
|
||||||
@@ -39,6 +42,7 @@ func AuthMiddleware() gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if tokenString == "" {
|
if tokenString == "" {
|
||||||
|
log.Warn().Str("reason", "no_token").Msg("Auth failed - no token provided")
|
||||||
abortUnauthorized(c)
|
abortUnauthorized(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -51,13 +55,26 @@ func AuthMiddleware() gin.HandlerFunc {
|
|||||||
return jwtSecret, nil
|
return jwtSecret, nil
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil || !token.Valid {
|
if err != nil {
|
||||||
|
log.Warn().
|
||||||
|
Str("reason", "token_parse_error").
|
||||||
|
Err(err).
|
||||||
|
Msg("Auth failed - token parse error")
|
||||||
|
abortUnauthorized(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !token.Valid {
|
||||||
|
log.Warn().Str("reason", "invalid_token").Msg("Auth failed - invalid token")
|
||||||
abortUnauthorized(c)
|
abortUnauthorized(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Set("user_id", claims.UserID)
|
c.Set("user_id", claims.UserID)
|
||||||
c.Set("role", claims.Role)
|
c.Set("role", claims.Role)
|
||||||
|
c.Set("username", claims.UserID)
|
||||||
|
|
||||||
|
log.Debug().Str("user_id", claims.UserID).Str("role", claims.Role).Msg("Auth successful")
|
||||||
|
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
@@ -76,26 +93,37 @@ func abortUnauthorized(c *gin.Context) {
|
|||||||
|
|
||||||
func RequireRole(roles ...string) gin.HandlerFunc {
|
func RequireRole(roles ...string) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
|
log := StructuredLog(c).With().
|
||||||
|
Str("event", "role_check").
|
||||||
|
Logger()
|
||||||
|
|
||||||
roleValue, exists := c.Get("role")
|
roleValue, exists := c.Get("role")
|
||||||
if !exists {
|
if !exists {
|
||||||
|
log.Warn().Str("reason", "no_role").Msg("Role check failed - no role in context")
|
||||||
abortForbidden(c)
|
abortForbidden(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
userRole, ok := roleValue.(string)
|
userRole, ok := roleValue.(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
log.Warn().Str("reason", "invalid_role_type").Msg("Role check failed - invalid role type")
|
||||||
abortForbidden(c)
|
abortForbidden(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, allowed := range roles {
|
for _, allowed := range roles {
|
||||||
if userRole == allowed {
|
if userRole == allowed {
|
||||||
|
log.Debug().Str("required_roles", strings.Join(roles, ",")).Str("user_role", userRole).Msg("Role check passed")
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Warn().
|
||||||
|
Str("required_roles", strings.Join(roles, ",")).
|
||||||
|
Str("user_role", userRole).
|
||||||
|
Msg("Role check failed - insufficient permissions")
|
||||||
|
|
||||||
abortForbidden(c)
|
abortForbidden(c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,87 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ResendIt/internal/logger"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/rs/zerolog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StructuredLogger returns a gin middleware that logs HTTP requests in JSON format
|
||||||
|
func StructuredLogger() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
start := time.Now()
|
||||||
|
path := c.Request.URL.Path
|
||||||
|
query := c.Request.URL.RawQuery
|
||||||
|
method := c.Request.Method
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
|
||||||
|
latency := time.Since(start)
|
||||||
|
status := c.Writer.Status()
|
||||||
|
clientIP := c.ClientIP()
|
||||||
|
userAgent := c.Request.UserAgent()
|
||||||
|
requestID := c.GetString("request_id")
|
||||||
|
|
||||||
|
evt := logger.Log.Info().
|
||||||
|
Str("type", "http_request").
|
||||||
|
Str("method", method).
|
||||||
|
Str("path", path).
|
||||||
|
Str("query", query).
|
||||||
|
Int("status", status).
|
||||||
|
Dur("latency_ms", latency).
|
||||||
|
Str("client_ip", clientIP).
|
||||||
|
Str("user_agent", userAgent).
|
||||||
|
Str("request_id", requestID)
|
||||||
|
|
||||||
|
if len(c.Errors) > 0 {
|
||||||
|
evt = evt.Str("error", c.Errors.ByType(gin.ErrorTypePrivate).String())
|
||||||
|
}
|
||||||
|
|
||||||
|
if userID, exists := c.Get("user_id"); exists {
|
||||||
|
evt = evt.Str("user_id", userID.(string))
|
||||||
|
}
|
||||||
|
if username, exists := c.Get("username"); exists {
|
||||||
|
evt = evt.Str("username", username.(string))
|
||||||
|
}
|
||||||
|
|
||||||
|
evt.Msg("")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestIDMiddleware adds a unique request ID to each request
|
||||||
|
func RequestIDMiddleware() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
requestID := c.GetHeader("X-Request-ID")
|
||||||
|
if requestID == "" {
|
||||||
|
requestID = generateRequestID()
|
||||||
|
}
|
||||||
|
c.Set("request_id", requestID)
|
||||||
|
c.Header("X-Request-ID", requestID)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateRequestID() string {
|
||||||
|
// Simple request ID generation - could use uuid package for more entropy
|
||||||
|
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StructuredLog returns a child logger with HTTP context for use in handlers
|
||||||
|
func StructuredLog(c *gin.Context) zerolog.Logger {
|
||||||
|
log := logger.Log.With().
|
||||||
|
Str("type", "app_log").
|
||||||
|
Str("request_id", c.GetString("request_id"))
|
||||||
|
|
||||||
|
if userID, exists := c.Get("user_id"); exists {
|
||||||
|
log = log.Str("user_id", userID.(string))
|
||||||
|
}
|
||||||
|
if username, exists := c.Get("username"); exists {
|
||||||
|
log = log.Str("username", username.(string))
|
||||||
|
}
|
||||||
|
|
||||||
|
return log.Logger()
|
||||||
|
}
|
||||||
|
|||||||
156
internal/api/middleware/ratelimit.go
Normal file
156
internal/api/middleware/ratelimit.go
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
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
|
||||||
|
max int
|
||||||
|
burst int
|
||||||
|
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 {
|
||||||
|
return RateLimitByIPDynamic(func() int { return max }, per, func() int { return burst }, ttl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIPDynamic is like RateLimitByIP but reads max/burst dynamically.
|
||||||
|
// This allows changing limits at runtime (e.g. from an admin config page).
|
||||||
|
func RateLimitByIPDynamic(maxFn func() int, per time.Duration, burstFn func() 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, max int, burst int) *ipClient {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
c, ok := clients[ip]
|
||||||
|
if !ok {
|
||||||
|
c = &ipClient{bucket: newTokenBucket(max, per, burst), max: max, burst: burst, lastSeen: now}
|
||||||
|
clients[ip] = c
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
c.lastSeen = now
|
||||||
|
// If settings changed, reset the bucket.
|
||||||
|
if c.max != max || c.burst != burst {
|
||||||
|
c.bucket = newTokenBucket(max, per, burst)
|
||||||
|
c.max = max
|
||||||
|
c.burst = burst
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
log := StructuredLog(c).With().
|
||||||
|
Str("event", "rate_limit_check").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
// Kinda a shitty fix
|
||||||
|
if c.FullPath() == "/api/files/upload/chunk" || c.FullPath() == "/api/files/upload/init" || c.FullPath() == "/api/files/upload/complete" {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
cleanup(now)
|
||||||
|
|
||||||
|
ip := c.ClientIP()
|
||||||
|
max := maxFn()
|
||||||
|
if max <= 0 {
|
||||||
|
max = 1
|
||||||
|
}
|
||||||
|
burst := burstFn()
|
||||||
|
if burst <= 0 {
|
||||||
|
burst = max
|
||||||
|
}
|
||||||
|
client := getClient(ip, now, max, burst)
|
||||||
|
|
||||||
|
if !client.bucket.allow() {
|
||||||
|
log.Warn().
|
||||||
|
Str("ip", ip).
|
||||||
|
Int("max", max).
|
||||||
|
Int("burst", burst).
|
||||||
|
Msg("Rate limit exceeded")
|
||||||
|
|
||||||
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||||
|
"error": "rate limit exceeded",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,9 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -37,16 +40,44 @@ func (h *Handler) Login(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
log := middleware.StructuredLog(c)
|
||||||
|
|
||||||
|
log.Warn().
|
||||||
|
Str("event", "login_failed").
|
||||||
|
Str("reason", "invalid_request").
|
||||||
|
Str("username", req.Username).
|
||||||
|
Msg("Login attempt with invalid request")
|
||||||
|
|
||||||
c.JSON(400, gin.H{"error": "Invalid request body"})
|
c.JSON(400, gin.H{"error": "Invalid request body"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "login_attempt").
|
||||||
|
Str("username", req.Username).
|
||||||
|
Str("ip", c.ClientIP()).
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
token, err := h.service.Login(req.Username, req.Password)
|
token, err := h.service.Login(req.Username, req.Password)
|
||||||
|
latency := time.Since(start)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Warn().
|
||||||
|
Str("result", "failed").
|
||||||
|
Dur("latency_ms", latency).
|
||||||
|
Err(err).
|
||||||
|
Msg("Login failed")
|
||||||
|
|
||||||
c.JSON(401, gin.H{"error": "Invalid credentials"})
|
c.JSON(401, gin.H{"error": "Invalid credentials"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().
|
||||||
|
Str("result", "success").
|
||||||
|
Dur("latency_ms", latency).
|
||||||
|
Msg("Login successful")
|
||||||
|
|
||||||
isSecure := os.Getenv("USE_HTTPS") == "true"
|
isSecure := os.Getenv("USE_HTTPS") == "true"
|
||||||
|
|
||||||
c.SetCookie(
|
c.SetCookie(
|
||||||
@@ -56,7 +87,7 @@ func (h *Handler) Login(c *gin.Context) {
|
|||||||
"/",
|
"/",
|
||||||
os.Getenv("DOMAIN"),
|
os.Getenv("DOMAIN"),
|
||||||
isSecure,
|
isSecure,
|
||||||
true, // httpOnly (IMPORTANT)
|
true,
|
||||||
)
|
)
|
||||||
|
|
||||||
c.JSON(200, gin.H{"token": token})
|
c.JSON(200, gin.H{"token": token})
|
||||||
|
|||||||
@@ -2,14 +2,30 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/api/middleware"
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterRoutes(r *gin.RouterGroup, h *Handler, cfg ConfigService) {
|
||||||
auth := r.Group("/auth")
|
auth := r.Group("/auth")
|
||||||
|
|
||||||
auth.POST("/login", h.Login)
|
// Stricter rate limit on login to reduce brute-force / log spam.
|
||||||
|
auth.POST("/login", middleware.RateLimitByIPDynamic(
|
||||||
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst)
|
||||||
|
},
|
||||||
|
15*time.Minute,
|
||||||
|
), h.Login)
|
||||||
|
|
||||||
protected := auth.Group("/")
|
protected := auth.Group("/")
|
||||||
protected.Use(middleware.AuthMiddleware())
|
protected.Use(middleware.AuthMiddleware())
|
||||||
|
|||||||
7
internal/buildinfo/buildinfo.go
Normal file
7
internal/buildinfo/buildinfo.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package buildinfo
|
||||||
|
|
||||||
|
// Commit is the git commit SHA the binary was built from.
|
||||||
|
//
|
||||||
|
// Set at build time via:
|
||||||
|
// -ldflags "-X ResendIt/internal/buildinfo.Commit=<sha>"
|
||||||
|
var Commit = "dev"
|
||||||
58
internal/config/defaults.go
Normal file
58
internal/config/defaults.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "strconv"
|
||||||
|
|
||||||
|
const (
|
||||||
|
KeyModtext = "modt"
|
||||||
|
|
||||||
|
KeyUploadMaxFileSizeBytes = "upload.max_file_size_bytes"
|
||||||
|
KeyUploadMultiMaxFiles = "upload.multi.max_files"
|
||||||
|
KeyUploadMaxHours = "upload.max_hours"
|
||||||
|
KeyRateLimitLoginPerMinute = "ratelimit.login.per_minute"
|
||||||
|
KeyRateLimitApiPerMinute = "ratelimit.api.per_minute"
|
||||||
|
KeyRateLimitApiBurst = "ratelimit.api.burst"
|
||||||
|
KeyRateLimitLoginBurst = "ratelimit.login.burst"
|
||||||
|
|
||||||
|
KeyUseNtfy = "use_ntfy"
|
||||||
|
KeyNtfyUrl = "ntfy.url"
|
||||||
|
KeyNtfyTopic = "ntfy.topic"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Defaults (used when DB does not have an override)
|
||||||
|
const (
|
||||||
|
DefaultModt = "A_SERVICE_BY_BRAMMIE15"
|
||||||
|
|
||||||
|
DefaultUploadMaxFileSizeBytes int64 = 10 << 30 // 10 GiB (matches MaxMultipartMemory intent)
|
||||||
|
DefaultUploadMultiMaxFiles = 50
|
||||||
|
DefaultUploadMaxHours = 24 * 7 // 7 days
|
||||||
|
|
||||||
|
DefaultRateLimitLoginPerMinute = 5
|
||||||
|
DefaultRateLimitLoginBurst = 10
|
||||||
|
DefaultRateLimitApiPerMinute = 60
|
||||||
|
DefaultRateLimitApiBurst = 30
|
||||||
|
|
||||||
|
DefaultUseNtfy = 0
|
||||||
|
DefaultNtfyUrl = ""
|
||||||
|
DefaultNtfyTopic = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultKeyValues returns a map of config keys to their default string values, for use when initializing the database.
|
||||||
|
// Code duplication be dammed
|
||||||
|
func DefaultKeyValues() map[string]string {
|
||||||
|
return map[string]string{
|
||||||
|
KeyModtext: DefaultModt,
|
||||||
|
|
||||||
|
KeyUploadMaxFileSizeBytes: strconv.FormatInt(DefaultUploadMaxFileSizeBytes, 10),
|
||||||
|
KeyUploadMultiMaxFiles: strconv.Itoa(DefaultUploadMultiMaxFiles),
|
||||||
|
KeyUploadMaxHours: strconv.Itoa(DefaultUploadMaxHours),
|
||||||
|
|
||||||
|
KeyRateLimitLoginPerMinute: strconv.Itoa(DefaultRateLimitLoginPerMinute),
|
||||||
|
KeyRateLimitLoginBurst: strconv.Itoa(DefaultRateLimitLoginBurst),
|
||||||
|
KeyRateLimitApiPerMinute: strconv.Itoa(DefaultRateLimitApiPerMinute),
|
||||||
|
KeyRateLimitApiBurst: strconv.Itoa(DefaultRateLimitApiBurst),
|
||||||
|
|
||||||
|
KeyUseNtfy: strconv.Itoa(DefaultUseNtfy),
|
||||||
|
KeyNtfyUrl: DefaultNtfyUrl,
|
||||||
|
KeyNtfyTopic: DefaultNtfyTopic,
|
||||||
|
}
|
||||||
|
}
|
||||||
18
internal/config/model.go
Normal file
18
internal/config/model.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ConfigEntry stores runtime-tunable configuration in the database.
|
||||||
|
// Values are stored as strings but helpers exist for ints/bools/durations.
|
||||||
|
//
|
||||||
|
// Example keys:
|
||||||
|
// - upload.max_file_size_bytes
|
||||||
|
// - upload.multi.max_files
|
||||||
|
// - upload.max_hours
|
||||||
|
// - ratelimit.login.per_minute
|
||||||
|
// - ratelimit.api.per_minute
|
||||||
|
type ConfigEntry struct {
|
||||||
|
Key string `gorm:"primaryKey;size:128"`
|
||||||
|
Value string `gorm:"size:2048"`
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
55
internal/config/repository.go
Normal file
55
internal/config/repository.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Repository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(db *gorm.DB) *Repository {
|
||||||
|
return &Repository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Get(key string) (*ConfigEntry, error) {
|
||||||
|
var e ConfigEntry
|
||||||
|
if err := r.db.First(&e, "key = ?", key).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Upsert(key, value string) error {
|
||||||
|
// Try update first, then insert if nothing updated.
|
||||||
|
res := r.db.Model(&ConfigEntry{}).Where("key = ?", key).Update("value", value)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return r.db.Create(&ConfigEntry{Key: key, Value: value}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) List() ([]ConfigEntry, error) {
|
||||||
|
var entries []ConfigEntry
|
||||||
|
if err := r.db.Order("key asc").Find(&entries).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) CreateIfMissing(key, value string) error {
|
||||||
|
var e ConfigEntry
|
||||||
|
err := r.db.First(&e, "key = ?", key).Error
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return r.db.Create(&ConfigEntry{Key: key, Value: value}).Error
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
134
internal/config/service.go
Normal file
134
internal/config/service.go
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
repo *Repository
|
||||||
|
|
||||||
|
// Small in-memory cache to avoid hitting the DB on every request.
|
||||||
|
// Updated on SetString; lazy-filled on first Get.
|
||||||
|
mu sync.RWMutex
|
||||||
|
cache map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(r *Repository) *Service {
|
||||||
|
return &Service{repo: r, cache: make(map[string]string)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) EnsureDefaults() error {
|
||||||
|
for k, v := range DefaultKeyValues() {
|
||||||
|
if err := s.repo.CreateIfMissing(k, v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) List() ([]ConfigEntry, error) {
|
||||||
|
entries, err := s.repo.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// refresh cache snapshot
|
||||||
|
s.mu.Lock()
|
||||||
|
for _, e := range entries {
|
||||||
|
s.cache[e.Key] = e.Value
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SetString(key, value string) error {
|
||||||
|
if err := s.repo.Upsert(key, value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = value
|
||||||
|
s.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetStringDefault(key, def string) string {
|
||||||
|
s.mu.RLock()
|
||||||
|
v, ok := s.cache[key]
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if ok {
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
e, err := s.repo.Get(key)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = e.Value
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if e.Value == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return e.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetIntDefault(key string, def int) int {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetInt64Default(key string, def int64) int64 {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetBoolDefault(key string, def bool) bool {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
b, err := strconv.ParseBool(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetDurationSecondsDefault(key string, def time.Duration) time.Duration {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
|
"ResendIt/internal/logger"
|
||||||
|
|
||||||
"gorm.io/driver/mysql"
|
"gorm.io/driver/mysql"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
"gorm.io/driver/sqlite"
|
"gorm.io/driver/sqlite"
|
||||||
@@ -21,19 +23,43 @@ func Connect() (*gorm.DB, error) {
|
|||||||
dsn = "./data/database.db"
|
dsn = "./data/database.db"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.Log.Info().
|
||||||
|
Str("type", "db_connect").
|
||||||
|
Str("db_type", dbType).
|
||||||
|
Msg("Connecting to database")
|
||||||
|
|
||||||
|
var db *gorm.DB
|
||||||
|
var err error
|
||||||
|
|
||||||
switch dbType {
|
switch dbType {
|
||||||
case "sqlite":
|
case "sqlite":
|
||||||
return connectSQLite(dsn)
|
db, err = connectSQLite(dsn)
|
||||||
|
|
||||||
case "postgres":
|
case "postgres":
|
||||||
return connectPostgres(dsn)
|
db, err = connectPostgres(dsn)
|
||||||
|
|
||||||
case "mysql":
|
case "mysql":
|
||||||
return connectMySQL(dsn)
|
db, err = connectMySQL(dsn)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupported DB_TYPE: %s", dbType)
|
return nil, fmt.Errorf("unsupported DB_TYPE: %s", dbType)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
logger.Log.Error().
|
||||||
|
Str("type", "db_connect").
|
||||||
|
Str("db_type", dbType).
|
||||||
|
Err(err).
|
||||||
|
Msg("Failed to connect to database")
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Log.Info().
|
||||||
|
Str("type", "db_connect").
|
||||||
|
Str("db_type", dbType).
|
||||||
|
Msg("Database connected successfully")
|
||||||
|
|
||||||
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func connectSQLite(filePath string) (*gorm.DB, error) {
|
func connectSQLite(filePath string) (*gorm.DB, error) {
|
||||||
@@ -51,6 +77,12 @@ func connectSQLite(filePath string) (*gorm.DB, error) {
|
|||||||
return nil, fmt.Errorf("failed to open SQLite database: %w", err)
|
return nil, fmt.Errorf("failed to open SQLite database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err == nil {
|
||||||
|
sqlDB.SetMaxIdleConns(10)
|
||||||
|
sqlDB.SetMaxOpenConns(100)
|
||||||
|
}
|
||||||
|
|
||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,6 +96,12 @@ func connectPostgres(dsn string) (*gorm.DB, error) {
|
|||||||
return nil, fmt.Errorf("failed to connect to Postgres: %w", err)
|
return nil, fmt.Errorf("failed to connect to Postgres: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err == nil {
|
||||||
|
sqlDB.SetMaxIdleConns(10)
|
||||||
|
sqlDB.SetMaxOpenConns(100)
|
||||||
|
}
|
||||||
|
|
||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,5 +115,11 @@ func connectMySQL(dsn string) (*gorm.DB, error) {
|
|||||||
return nil, fmt.Errorf("failed to connect to MySQL: %w", err)
|
return nil, fmt.Errorf("failed to connect to MySQL: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err == nil {
|
||||||
|
sqlDB.SetMaxIdleConns(10)
|
||||||
|
sqlDB.SetMaxOpenConns(100)
|
||||||
|
}
|
||||||
|
|
||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"ResendIt/internal/logger"
|
||||||
|
"ResendIt/internal/notify"
|
||||||
"ResendIt/internal/util"
|
"ResendIt/internal/util"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
@@ -13,27 +19,54 @@ import (
|
|||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
service *Service
|
service *Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(s *Service) *Handler {
|
// ConfigService is the small interface we need from the config package.
|
||||||
return &Handler{service: s}
|
// Keeping it as an interface avoids import cycles and keeps file.Handler easy to test.
|
||||||
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
GetStringDefault(key string, def string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(s *Service, cfg ConfigService) *Handler {
|
||||||
|
return &Handler{service: s, configService: cfg}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Upload(c *gin.Context) {
|
func (h *Handler) Upload(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "file_upload").
|
||||||
|
Logger()
|
||||||
|
|
||||||
err := c.Request.ParseMultipartForm(0)
|
err := c.Request.ParseMultipartForm(0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Warn().Str("reason", "parse_error").Err(err).Msg("Upload failed")
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
file, err := c.FormFile("file")
|
file, err := c.FormFile("file")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Warn().Str("reason", "missing_file").Msg("Upload failed")
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing file"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing file"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
if file.Size > maxSize {
|
||||||
|
log.Warn().
|
||||||
|
Str("reason", "file_too_large").
|
||||||
|
Int64("file_size", file.Size).
|
||||||
|
Int64("max_size", maxSize).
|
||||||
|
Msg("Upload rejected")
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
f, err := file.Open()
|
f, err := file.Open()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to open uploaded file")
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -46,6 +79,10 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
if err != nil || hours <= 0 {
|
if err != nil || hours <= 0 {
|
||||||
hours = 24 // default
|
hours = 24 // default
|
||||||
}
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
|
|
||||||
duration := time.Duration(hours) * time.Hour
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
@@ -56,10 +93,33 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
duration,
|
duration,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Upload failed")
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().
|
||||||
|
Str("file_id", record.ID).
|
||||||
|
Str("filename", record.Filename).
|
||||||
|
Int64("file_size", record.Size).
|
||||||
|
Bool("once", once).
|
||||||
|
Msg("File uploaded successfully")
|
||||||
|
|
||||||
|
enabled := h.configService.GetIntDefault(config.KeyUseNtfy, config.DefaultUseNtfy)
|
||||||
|
if enabled == 1 {
|
||||||
|
ntfyURL := h.configService.GetStringDefault(config.KeyNtfyUrl, "")
|
||||||
|
topic := h.configService.GetStringDefault(config.KeyNtfyTopic, config.DefaultNtfyTopic)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
title := "ReSendit: new upload"
|
||||||
|
msg := fmt.Sprintf("%s (%s)\nID: %s", record.Filename, util.HumanSize(record.Size), record.ID)
|
||||||
|
clickUrl := fmt.Sprintf("f/%s", record.ViewID)
|
||||||
|
if err := notify.Publish(ntfyURL, topic, title, msg, clickUrl); err != nil {
|
||||||
|
logger.Log.Warn().Err(err).Str("type", "ntfy").Msg("ntfy publish failed")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"id": record.ID,
|
"id": record.ID,
|
||||||
"deletion_id": record.DeletionID,
|
"deletion_id": record.DeletionID,
|
||||||
@@ -71,13 +131,21 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) View(c *gin.Context) {
|
func (h *Handler) View(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "file_view").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
record, err := h.service.DownloadFile(id)
|
record, err := h.service.DownloadFile(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
log.Warn().Str("file_id", id).Err(err).Msg("File view failed - not found")
|
||||||
|
c.HTML(http.StatusOK, "error.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Str("file_id", id).Str("filename", record.Filename).Msg("File viewed")
|
||||||
|
|
||||||
name := util.SafeFilename(record.Filename)
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
||||||
c.Header("X-Content-Type-Options", "nosniff")
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
@@ -95,31 +163,46 @@ func isXSSRisk(filename string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Download(c *gin.Context) {
|
func (h *Handler) Download(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "file_download").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
record, err := h.service.DownloadFile(id)
|
record, err := h.service.DownloadFile(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
log.Warn().Str("file_id", id).Err(err).Msg("File download failed - not found")
|
||||||
|
c.HTML(http.StatusOK, "error.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Str("file_id", id).Str("filename", record.Filename).Int64("size", record.Size).Msg("File downloaded")
|
||||||
|
|
||||||
name := util.SafeFilename(record.Filename)
|
name := util.SafeFilename(record.Filename)
|
||||||
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
|
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-Type", "application/octet-stream")
|
|
||||||
c.File(record.Path)
|
c.File(record.Path)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Delete(c *gin.Context) {
|
func (h *Handler) Delete(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "file_delete").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("del_id")
|
id := c.Param("del_id")
|
||||||
|
|
||||||
_, err := h.service.DeleteFileByDeletionID(id)
|
record, err := h.service.DeleteFileByDeletionID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.HTML(http.StatusOK, "fileNotFound.html", nil)
|
log.Warn().Str("deletion_id", id).Err(err).Msg("File delete failed")
|
||||||
|
c.HTML(http.StatusOK, "error.html", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
log.Info().
|
||||||
|
Str("file_id", record.ID).
|
||||||
|
Str("filename", record.Filename).
|
||||||
|
Msg("File deleted")
|
||||||
|
|
||||||
c.HTML(http.StatusOK, "deleted.html", nil)
|
c.HTML(http.StatusOK, "deleted.html", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,22 +225,36 @@ func (h *Handler) AdminGet(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, util.SafeFilename(record.Filename)))
|
||||||
|
c.Header("X-Content-Type-Options", "nosniff")
|
||||||
|
|
||||||
c.File(record.Path)
|
c.File(record.Path)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) AdminDelete(c *gin.Context) {
|
func (h *Handler) AdminDelete(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "admin_file_delete").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
_, err := h.service.DeleteFileByID(id)
|
record, err := h.service.DeleteFileByID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Warn().Str("file_id", id).Err(err).Msg("Admin file delete failed")
|
||||||
c.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Str("file_id", record.ID).Str("filename", record.Filename).Msg("Admin deleted file")
|
||||||
|
|
||||||
c.Redirect(301, "/admin")
|
c.Redirect(301, "/admin")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) AdminForceDelete(c *gin.Context) {
|
func (h *Handler) AdminForceDelete(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "admin_file_force_delete").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
_, err := h.service.GetFileByID(id)
|
_, err := h.service.GetFileByID(id)
|
||||||
@@ -167,10 +264,37 @@ func (h *Handler) AdminForceDelete(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if _, err := h.service.ForceDelete(id); err != nil {
|
if _, err := h.service.ForceDelete(id); err != nil {
|
||||||
|
log.Error().Err(err).Msg("Admin force delete failed")
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Str("file_id", id).Msg("Admin force deleted file")
|
||||||
|
|
||||||
|
c.Redirect(301, "/admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) AdminReinstate(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "admin_file_reinstate").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
id := c.Param("id")
|
||||||
|
|
||||||
|
_, err := h.service.GetFileByID(id)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, gin.H{"error": "file not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := h.service.ReinstateFile(id); err != nil {
|
||||||
|
log.Error().Err(err).Msg("Admin reinstate failed")
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info().Str("file_id", id).Msg("Admin reinstated file")
|
||||||
|
|
||||||
c.Redirect(301, "/admin")
|
c.Redirect(301, "/admin")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,3 +325,170 @@ func (h *Handler) Export(c *gin.Context) {
|
|||||||
|
|
||||||
c.JSON(http.StatusOK, records)
|
c.JSON(http.StatusOK, records)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Chunked stuff
|
||||||
|
func (h *Handler) UploadInit(c *gin.Context) {
|
||||||
|
var req struct {
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
TotalChunks int `json:"totalChunks"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileID := util.RandomString(32)
|
||||||
|
|
||||||
|
// create temp folder
|
||||||
|
path := filepath.Join("tmp", fileID)
|
||||||
|
if err := os.MkdirAll(path, os.ModePerm); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "failed to create temp dir"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"fileId": fileID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UploadChunk(c *gin.Context) {
|
||||||
|
fileID := c.GetHeader("fileId")
|
||||||
|
chunkIndex := c.GetHeader("chunkIndex")
|
||||||
|
|
||||||
|
if fileID == "" || chunkIndex == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "missing headers"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
idx, err := strconv.Atoi(chunkIndex)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid chunkIndex"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := c.FormFile("chunk")
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "missing chunk"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
src, err := file.Open()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "cannot open chunk"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer src.Close()
|
||||||
|
|
||||||
|
chunkPath := filepath.Join("tmp", fileID, fmt.Sprintf("chunk_%d", idx))
|
||||||
|
|
||||||
|
dst, err := os.Create(chunkPath)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "cannot save chunk"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer dst.Close()
|
||||||
|
|
||||||
|
if _, err := io.Copy(dst, src); err != nil {
|
||||||
|
c.JSON(500, gin.H{"error": "write failed"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{"status": "ok"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UploadComplete(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "chunked_upload_complete").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
var req struct {
|
||||||
|
FileID string `json:"fileId"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
TotalChunks int `json:"totalChunks"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid request"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpDir := filepath.Join("tmp", req.FileID)
|
||||||
|
|
||||||
|
// create pipe to stream into your existing service
|
||||||
|
pr, pw := io.Pipe()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer pw.Close()
|
||||||
|
|
||||||
|
for i := 0; i < req.TotalChunks; i++ {
|
||||||
|
chunkPath := filepath.Join(tmpDir, fmt.Sprintf("chunk_%d", i))
|
||||||
|
|
||||||
|
f, err := os.Open(chunkPath)
|
||||||
|
if err != nil {
|
||||||
|
pw.CloseWithError(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(pw, f); err != nil {
|
||||||
|
f.Close()
|
||||||
|
pw.CloseWithError(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
f.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
record, err := h.service.UploadFile(
|
||||||
|
req.Filename,
|
||||||
|
pr,
|
||||||
|
false,
|
||||||
|
24*time.Hour,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Chunked upload failed")
|
||||||
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = os.RemoveAll(tmpDir)
|
||||||
|
|
||||||
|
log.Info().
|
||||||
|
Str("file_id", record.ID).
|
||||||
|
Str("filename", record.Filename).
|
||||||
|
Int("chunks", req.TotalChunks).
|
||||||
|
Msg("Chunked upload completed")
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"id": record.ID,
|
||||||
|
"view_key": record.ViewID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) UploadStatus(c *gin.Context) {
|
||||||
|
fileID := c.Param("fileId")
|
||||||
|
|
||||||
|
dir := filepath.Join("tmp", fileID)
|
||||||
|
|
||||||
|
files, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(404, gin.H{"error": "not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var uploaded []int
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
var idx int
|
||||||
|
_, err := fmt.Sscanf(f.Name(), "chunk_%d", &idx)
|
||||||
|
if err == nil {
|
||||||
|
uploaded = append(uploaded, idx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(200, gin.H{
|
||||||
|
"uploadedChunks": uploaded,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -95,6 +95,12 @@ func (r *Repository) MarkDeleted(f *FileRecord) error {
|
|||||||
return r.db.Save(f).Error
|
return r.db.Save(f).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MarkNotDeleted Restore a deleted record by setting Deleted to false
|
||||||
|
func (r *Repository) MarkNotDeleted(f *FileRecord) error {
|
||||||
|
f.Deleted = false
|
||||||
|
return r.db.Save(f).Error
|
||||||
|
}
|
||||||
|
|
||||||
// Delete Permanently delete the record from the database
|
// Delete Permanently delete the record from the database
|
||||||
func (r *Repository) Delete(f *FileRecord) error {
|
func (r *Repository) Delete(f *FileRecord) error {
|
||||||
return r.db.Delete(f).Error
|
return r.db.Delete(f).Error
|
||||||
|
|||||||
@@ -16,6 +16,12 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
|||||||
files.GET("/view/:id", h.View)
|
files.GET("/view/:id", h.View)
|
||||||
files.GET("/delete/:del_id", h.Delete)
|
files.GET("/delete/:del_id", h.Delete)
|
||||||
|
|
||||||
|
// Chunked upload endpoints
|
||||||
|
files.POST("/upload/init", h.UploadInit)
|
||||||
|
files.POST("/upload/chunk", h.UploadChunk)
|
||||||
|
files.POST("/upload/complete", h.UploadComplete)
|
||||||
|
files.GET("/upload/status/:fileId", h.UploadStatus)
|
||||||
|
|
||||||
adminRoutes := files.Group("/admin")
|
adminRoutes := files.Group("/admin")
|
||||||
adminRoutes.Use(middleware.AuthMiddleware())
|
adminRoutes.Use(middleware.AuthMiddleware())
|
||||||
adminRoutes.Use(middleware.RequireRole("admin"))
|
adminRoutes.Use(middleware.RequireRole("admin"))
|
||||||
@@ -27,6 +33,7 @@ func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
|||||||
|
|
||||||
adminRoutes.GET("/delete/:id", h.AdminDelete)
|
adminRoutes.GET("/delete/:id", h.AdminDelete)
|
||||||
adminRoutes.GET("/delete/fr/:id", h.AdminForceDelete)
|
adminRoutes.GET("/delete/fr/:id", h.AdminForceDelete)
|
||||||
|
adminRoutes.GET("/reinstate/:id", h.AdminReinstate)
|
||||||
|
|
||||||
adminRoutes.POST("/import", h.Import)
|
adminRoutes.POST("/import", h.Import)
|
||||||
adminRoutes.GET("/export", h.Export)
|
adminRoutes.GET("/export", h.Export)
|
||||||
|
|||||||
@@ -134,6 +134,29 @@ func (s *Service) ForceDelete(id string) (*FileRecord, error) {
|
|||||||
return f, nil
|
return f, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Service) ReinstateFile(id string) (*FileRecord, error) {
|
||||||
|
f, err := s.repo.GetByID(id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !f.Deleted {
|
||||||
|
return nil, ErrFileNotFound // or just return f, nil maybe?
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if file actually exists on disk
|
||||||
|
path := s.storageDir + "/" + f.ID
|
||||||
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
|
return nil, ErrFileNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.repo.MarkNotDeleted(f); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Service) GetPaginatedFiles(limit, offset int) ([]FileRecord, int, error) {
|
func (s *Service) GetPaginatedFiles(limit, offset int) ([]FileRecord, int, error) {
|
||||||
return s.repo.GetPaginated(limit, offset)
|
return s.repo.GetPaginated(limit, offset)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
@@ -26,11 +27,27 @@ func (h *Handler) UploadMulti(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(files) > 50 {
|
maxFiles := h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles)
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files (max 50)"})
|
if len(files) > maxFiles {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
var total int64
|
||||||
|
for _, fh := range files {
|
||||||
|
if fh.Size > maxSize {
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
total += fh.Size
|
||||||
|
if total > maxSize {
|
||||||
|
// crude guard against huge bundles; you can add a separate config later.
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "bundle too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
once := c.PostForm("once") == "true"
|
once := c.PostForm("once") == "true"
|
||||||
|
|
||||||
durationStr := c.PostForm("duration")
|
durationStr := c.PostForm("duration")
|
||||||
@@ -38,6 +55,10 @@ func (h *Handler) UploadMulti(c *gin.Context) {
|
|||||||
if err != nil || hours <= 0 {
|
if err != nil || hours <= 0 {
|
||||||
hours = 24
|
hours = 24
|
||||||
}
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
duration := time.Duration(hours) * time.Hour
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
record, err := h.service.UploadBundle(files, once, duration)
|
record, err := h.service.UploadBundle(files, once, duration)
|
||||||
|
|||||||
40
internal/logger/logger.go
Normal file
40
internal/logger/logger.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package logger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/rs/zerolog"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Log zerolog.Logger
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
output := os.Stderr
|
||||||
|
|
||||||
|
logFormat := os.Getenv("LOG_FORMAT")
|
||||||
|
if logFormat == "json" {
|
||||||
|
Log = zerolog.New(output).With().Timestamp().Logger()
|
||||||
|
} else {
|
||||||
|
Log = zerolog.New(zerolog.ConsoleWriter{
|
||||||
|
Out: output,
|
||||||
|
TimeFormat: time.RFC3339,
|
||||||
|
}).With().Timestamp().Logger()
|
||||||
|
}
|
||||||
|
|
||||||
|
level := os.Getenv("LOG_LEVEL")
|
||||||
|
switch level {
|
||||||
|
case "debug":
|
||||||
|
Log = Log.Level(zerolog.DebugLevel)
|
||||||
|
case "warn":
|
||||||
|
Log = Log.Level(zerolog.WarnLevel)
|
||||||
|
case "error":
|
||||||
|
Log = Log.Level(zerolog.ErrorLevel)
|
||||||
|
default:
|
||||||
|
Log = Log.Level(zerolog.InfoLevel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func With() zerolog.Context {
|
||||||
|
return Log.With()
|
||||||
|
}
|
||||||
39
internal/notify/ntfy.go
Normal file
39
internal/notify/ntfy.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Publish(ntfyURL, topic, title, message string, clickUrl string) error {
|
||||||
|
ntfyURL = strings.TrimRight(ntfyURL, "/")
|
||||||
|
if ntfyURL == "" || topic == "" {
|
||||||
|
return nil // nothing configured
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest("POST", ntfyURL+"/"+topic, strings.NewReader(message))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if title != "" {
|
||||||
|
req.Header.Set("Title", title)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
domain := os.Getenv("DOMAIN")
|
||||||
|
req.Header.Set("Click", fmt.Sprintf("%s%s", domain, clickUrl))
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: 3 * time.Second}
|
||||||
|
res, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
|
||||||
|
if res.StatusCode >= 300 {
|
||||||
|
return fmt.Errorf("ntfy returned %s", res.Status)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -2,6 +2,9 @@ package user
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
@@ -15,6 +18,10 @@ func NewHandler(service *Service) *Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Register(c *gin.Context) {
|
func (h *Handler) Register(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "user_register").
|
||||||
|
Logger()
|
||||||
|
|
||||||
var req struct {
|
var req struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
@@ -22,20 +29,43 @@ func (h *Handler) Register(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
log.Warn().
|
||||||
|
Str("reason", "invalid_request").
|
||||||
|
Msg("Registration failed")
|
||||||
|
|
||||||
c.JSON(400, gin.H{"error": "invalid request"})
|
c.JSON(400, gin.H{"error": "invalid request"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := h.service.CreateUser(req.Username, req.Password, req.Role)
|
user, err := h.service.CreateUser(req.Username, req.Password, req.Role)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Error().
|
||||||
|
Err(err).
|
||||||
|
Str("username", req.Username).
|
||||||
|
Msg("Registration failed")
|
||||||
|
|
||||||
c.JSON(500, gin.H{"error": err.Error()})
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.JSON(201, gin.H{"id": user.ID, "username": user.Username, "role": user.Role})
|
log.Info().
|
||||||
|
Str("user_id", fmt.Sprint(user.ID)).
|
||||||
|
Str("username", user.Username).
|
||||||
|
Str("role", user.Role).
|
||||||
|
Msg("User registered successfully")
|
||||||
|
|
||||||
|
c.JSON(201, gin.H{
|
||||||
|
"id": user.ID,
|
||||||
|
"username": user.Username,
|
||||||
|
"role": user.Role,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) ChangePassword(c *gin.Context) {
|
func (h *Handler) ChangePassword(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "password_change").
|
||||||
|
Logger()
|
||||||
|
|
||||||
var req struct {
|
var req struct {
|
||||||
OldPassword string `json:"old_password"`
|
OldPassword string `json:"old_password"`
|
||||||
NewPassword string `json:"new_password"`
|
NewPassword string `json:"new_password"`
|
||||||
@@ -43,41 +73,75 @@ func (h *Handler) ChangePassword(c *gin.Context) {
|
|||||||
|
|
||||||
userID, exists := c.Get("user_id")
|
userID, exists := c.Get("user_id")
|
||||||
if !exists {
|
if !exists {
|
||||||
fmt.Println("User ID not found in context")
|
|
||||||
c.JSON(401, gin.H{"error": "unauthorized"})
|
c.JSON(401, gin.H{"error": "unauthorized"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
log.Warn().
|
||||||
|
Str("reason", "invalid_request").
|
||||||
|
Msg("Password change failed")
|
||||||
|
|
||||||
c.JSON(400, gin.H{"error": "invalid request"})
|
c.JSON(400, gin.H{"error": "invalid request"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := h.service.ChangePassword(userID.(string), req.OldPassword, req.NewPassword)
|
uid := fmt.Sprint(userID)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
err := h.service.ChangePassword(uid, req.OldPassword, req.NewPassword)
|
||||||
|
latency := time.Since(start)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Warn().
|
||||||
|
Str("user_id", uid).
|
||||||
|
Str("reason", err.Error()).
|
||||||
|
Dur("latency_ms", latency).
|
||||||
|
Msg("Password change failed")
|
||||||
|
|
||||||
c.JSON(500, gin.H{"error": err.Error()})
|
c.JSON(500, gin.H{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().
|
||||||
|
Str("user_id", uid).
|
||||||
|
Dur("latency_ms", latency).
|
||||||
|
Msg("Password changed successfully")
|
||||||
|
|
||||||
c.JSON(200, gin.H{"message": "password changed successfully"})
|
c.JSON(200, gin.H{"message": "password changed successfully"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func ForcePasswordChangeMiddleware(userService *Service) gin.HandlerFunc {
|
func ForcePasswordChangeMiddleware(userService *Service) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "force_password_check").
|
||||||
|
Logger()
|
||||||
|
|
||||||
userID, exists := c.Get("user_id")
|
userID, exists := c.Get("user_id")
|
||||||
if !exists {
|
if !exists {
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := userService.FindByID(userID.(string))
|
uid := fmt.Sprint(userID)
|
||||||
|
|
||||||
|
user, err := userService.FindByID(uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Error().
|
||||||
|
Err(err).
|
||||||
|
Str("user_id", uid).
|
||||||
|
Msg("Failed to find user for password check")
|
||||||
|
|
||||||
c.AbortWithStatus(500)
|
c.AbortWithStatus(500)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow access to change password page itself
|
|
||||||
if user.ForceChangePassword && c.Request.URL.Path != "/change-password" {
|
if user.ForceChangePassword && c.Request.URL.Path != "/change-password" {
|
||||||
|
log.Warn().
|
||||||
|
Str("user_id", uid).
|
||||||
|
Str("path", c.Request.URL.Path).
|
||||||
|
Msg("Access denied - force password change required")
|
||||||
|
|
||||||
c.Redirect(302, "/change-password")
|
c.Redirect(302, "/change-password")
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package util
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -41,3 +42,12 @@ func SafeFilename(name string) string {
|
|||||||
}
|
}
|
||||||
return string(out)
|
return string(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func RandomString(n int) string {
|
||||||
|
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
b := make([]byte, n)
|
||||||
|
for i := range b {
|
||||||
|
b[i] = letters[rand.Intn(len(letters))]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|||||||
216
internal/web/config.go
Normal file
216
internal/web/config.go
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConfigPageData struct {
|
||||||
|
Success bool
|
||||||
|
Error string
|
||||||
|
|
||||||
|
MODT string
|
||||||
|
|
||||||
|
UploadMaxFileSizeMB int64
|
||||||
|
UploadMultiMaxFiles int
|
||||||
|
UploadMaxHours int
|
||||||
|
|
||||||
|
RateLimitLoginPerMinute int
|
||||||
|
RateLimitLoginBurst int
|
||||||
|
RateLimitApiPerMinute int
|
||||||
|
RateLimitApiBurst int
|
||||||
|
|
||||||
|
NtfyUse bool
|
||||||
|
NtfyUrl string
|
||||||
|
NtfyTopic string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigPage renders a modular admin config screen.
|
||||||
|
func (h *Handler) ConfigPage(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "config_page_view").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
maxBytes := cfg.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Success: c.Query("saved") == "1",
|
||||||
|
MODT: cfg.GetStringDefault(config.KeyModtext, config.DefaultModt),
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: cfg.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: cfg.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: cfg.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: cfg.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
NtfyUse: cfg.GetIntDefault(config.KeyUseNtfy, 0) != 0,
|
||||||
|
NtfyUrl: cfg.GetStringDefault(config.KeyNtfyUrl, config.DefaultNtfyUrl),
|
||||||
|
NtfyTopic: cfg.GetStringDefault(config.KeyNtfyTopic, config.DefaultNtfyTopic),
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug().Msg("Config page viewed")
|
||||||
|
|
||||||
|
c.HTML(http.StatusOK, "config.html", data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) ConfigSave(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "config_save").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
// Parse + validate.
|
||||||
|
parseInt := func(name string, min, max int) (int, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
parseInt64 := func(name string, min int64, max int64) (int64, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
newMODT, err := strconv.Unquote(`"` + c.PostForm("site_modt") + `"`)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("reason", "invalid_modtext").Msg("Config save failed")
|
||||||
|
h.renderConfigError(c, "invalid modtext")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
maxMB, err := parseInt64("upload_max_file_size_mb", 1, 1024*1024)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "upload_max_file_size_mb").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid max file size")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxFiles, err := parseInt("upload_multi_max_files", 1, 500)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "upload_multi_max_files").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid max files")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxHours, err := parseInt("upload_max_hours", 1, 24*365)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "upload_max_hours").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid max hours")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limits: stored, but not applied dynamically yet.
|
||||||
|
loginPerMin, err := parseInt("ratelimit_login_per_minute", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "ratelimit_login_per_minute").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid login rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loginBurst, err := parseInt("ratelimit_login_burst", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "ratelimit_login_burst").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid login burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiPerMin, err := parseInt("ratelimit_api_per_minute", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "ratelimit_api_per_minute").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid api rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiBurst, err := parseInt("ratelimit_api_burst", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "ratelimit_api_burst").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid api burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
useNTFY, err := strconv.ParseBool(c.PostForm("ntfy_use"))
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Str("key", "ntfy_use").Msg("Config save failed - invalid value")
|
||||||
|
h.renderConfigError(c, "invalid ntfy use value")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ntfyUrl := c.PostForm("ntfy_url")
|
||||||
|
ntfyTopic := c.PostForm("ntfy_topic")
|
||||||
|
|
||||||
|
// Persist.
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxFileSizeBytes, strconv.FormatInt(maxMB*1024*1024, 10)); err != nil {
|
||||||
|
log.Error().Err(err).Str("key", config.KeyUploadMaxFileSizeBytes).Msg("Config save failed")
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMultiMaxFiles, strconv.Itoa(maxFiles)); err != nil {
|
||||||
|
log.Error().Err(err).Str("key", config.KeyUploadMultiMaxFiles).Msg("Config save failed")
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxHours, strconv.Itoa(maxHours)); err != nil {
|
||||||
|
log.Error().Err(err).Str("key", config.KeyUploadMaxHours).Msg("Config save failed")
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = cfg.SetString(config.KeyModtext, newMODT)
|
||||||
|
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginPerMinute, strconv.Itoa(loginPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginBurst, strconv.Itoa(loginBurst))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiPerMinute, strconv.Itoa(apiPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiBurst, strconv.Itoa(apiBurst))
|
||||||
|
|
||||||
|
// shitty ah fix
|
||||||
|
actualBool := 0
|
||||||
|
if useNTFY {
|
||||||
|
actualBool = 1
|
||||||
|
}
|
||||||
|
_ = cfg.SetString(config.KeyUseNtfy, strconv.Itoa(actualBool))
|
||||||
|
_ = cfg.SetString(config.KeyNtfyUrl, ntfyUrl)
|
||||||
|
_ = cfg.SetString(config.KeyNtfyTopic, ntfyTopic)
|
||||||
|
|
||||||
|
log.Info().
|
||||||
|
Str("modtext", newMODT).
|
||||||
|
Int64("max_file_size_mb", maxMB).
|
||||||
|
Int("max_files", maxFiles).
|
||||||
|
Int("max_hours", maxHours).
|
||||||
|
Msg("Config saved successfully")
|
||||||
|
|
||||||
|
c.Redirect(http.StatusFound, "/config?saved=1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) renderConfigError(c *gin.Context, msg string) {
|
||||||
|
maxBytes := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Error: msg,
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: h.configService.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: h.configService.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: h.configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: h.configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
}
|
||||||
|
c.HTML(http.StatusBadRequest, "config.html", data)
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
package web
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/buildinfo"
|
||||||
|
"ResendIt/internal/config"
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -10,11 +13,24 @@ import (
|
|||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
fileService *file.Service
|
fileService *file.Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(fileService *file.Service) *Handler {
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
GetStringDefault(key string, def string) string
|
||||||
|
|
||||||
|
//SetInt(key string, value int) error
|
||||||
|
//SetInt64(key string, value int64) error
|
||||||
|
//SetBool(key string, value bool) error
|
||||||
|
SetString(key string, value string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(fileService *file.Service, cfg ConfigService) *Handler {
|
||||||
return &Handler{
|
return &Handler{
|
||||||
fileService: fileService,
|
fileService: fileService,
|
||||||
|
configService: cfg,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,6 +38,7 @@ func NewHandler(fileService *file.Service) *Handler {
|
|||||||
func (h *Handler) Index(c *gin.Context) {
|
func (h *Handler) Index(c *gin.Context) {
|
||||||
c.HTML(200, "index.html", gin.H{
|
c.HTML(200, "index.html", gin.H{
|
||||||
"title": "Home",
|
"title": "Home",
|
||||||
|
"MODT": h.configService.GetStringDefault(config.KeyModtext, config.DefaultModt),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,18 +52,28 @@ func (h *Handler) LoginPage(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) FileView(c *gin.Context) {
|
func (h *Handler) FileView(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "file_view_page").
|
||||||
|
Logger()
|
||||||
|
|
||||||
id := c.Param("id")
|
id := c.Param("id")
|
||||||
|
|
||||||
fileRecord, err := h.fileService.GetFileByViewID(id)
|
fileRecord, err := h.fileService.GetFileByViewID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.HTML(404, "fileNotFound.html", nil)
|
log.Warn().Str("view_id", id).Err(err).Msg("File view failed - not found")
|
||||||
|
c.HTML(404, "error.html", gin.H{
|
||||||
|
"MODT": h.configService.GetStringDefault(config.KeyModtext, config.DefaultModt),
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Str("view_id", id).Str("filename", fileRecord.Filename).Msg("File view page rendered")
|
||||||
|
|
||||||
downloadKey := fileRecord.ID
|
downloadKey := fileRecord.ID
|
||||||
deleteKey := fileRecord.DeletionID
|
deleteKey := fileRecord.DeletionID
|
||||||
|
|
||||||
c.HTML(200, "complete.html", gin.H{
|
c.HTML(200, "complete.html", gin.H{
|
||||||
|
"MODT": h.configService.GetStringDefault(config.KeyModtext, config.DefaultModt),
|
||||||
"Filename": fileRecord.Filename,
|
"Filename": fileRecord.Filename,
|
||||||
"DownloadID": downloadKey,
|
"DownloadID": downloadKey,
|
||||||
"DeleteID": deleteKey,
|
"DeleteID": deleteKey,
|
||||||
@@ -54,6 +81,10 @@ func (h *Handler) FileView(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) AdminPage(c *gin.Context) {
|
func (h *Handler) AdminPage(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "admin_page_view").
|
||||||
|
Logger()
|
||||||
|
|
||||||
pageStr := c.Query("page")
|
pageStr := c.Query("page")
|
||||||
page, err := strconv.Atoi(pageStr)
|
page, err := strconv.Atoi(pageStr)
|
||||||
if err != nil || page < 1 {
|
if err != nil || page < 1 {
|
||||||
@@ -65,6 +96,7 @@ func (h *Handler) AdminPage(c *gin.Context) {
|
|||||||
|
|
||||||
files, totalCount, err := h.fileService.GetPaginatedFiles(limit, offset)
|
files, totalCount, err := h.fileService.GetPaginatedFiles(limit, offset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("Failed to load files for admin page")
|
||||||
c.HTML(500, "admin.html", gin.H{
|
c.HTML(500, "admin.html", gin.H{
|
||||||
"error": err.Error(),
|
"error": err.Error(),
|
||||||
})
|
})
|
||||||
@@ -98,14 +130,23 @@ func (h *Handler) AdminPage(c *gin.Context) {
|
|||||||
|
|
||||||
totalPages := (totalCount + limit - 1) / limit
|
totalPages := (totalCount + limit - 1) / limit
|
||||||
|
|
||||||
|
log.Debug().Int("page", page).Int("total_files", totalCount).Msg("Admin page viewed")
|
||||||
|
|
||||||
c.HTML(200, "admin.html", gin.H{
|
c.HTML(200, "admin.html", gin.H{
|
||||||
"Files": adminFiles,
|
"Files": adminFiles,
|
||||||
"Page": page,
|
"Page": page,
|
||||||
"TotalPages": totalPages,
|
"TotalPages": totalPages,
|
||||||
|
"BuildCommit": buildinfo.Commit,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Logout(c *gin.Context) {
|
func (h *Handler) Logout(c *gin.Context) {
|
||||||
|
log := middleware.StructuredLog(c).With().
|
||||||
|
Str("event", "logout").
|
||||||
|
Logger()
|
||||||
|
|
||||||
|
log.Info().Msg("User logged out")
|
||||||
|
|
||||||
c.SetCookie("auth_token", "", -1, "/", "", false, true)
|
c.SetCookie("auth_token", "", -1, "/", "", false, true)
|
||||||
c.Redirect(302, "/")
|
c.Redirect(302, "/")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ func RegisterRoutes(r *gin.Engine, h *Handler, userService *user.Service) {
|
|||||||
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
||||||
|
|
||||||
adminRoutes.GET("/admin", h.AdminPage)
|
adminRoutes.GET("/admin", h.AdminPage)
|
||||||
|
adminRoutes.GET("/config", h.ConfigPage)
|
||||||
|
adminRoutes.POST("/config", h.ConfigSave)
|
||||||
adminRoutes.GET("/logout", h.Logout)
|
adminRoutes.GET("/logout", h.Logout)
|
||||||
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
||||||
}
|
}
|
||||||
|
|||||||
331
static/js/upload.js
Normal file
331
static/js/upload.js
Normal file
@@ -0,0 +1,331 @@
|
|||||||
|
const zone = document.getElementById('drop-zone');
|
||||||
|
const input = document.getElementById('fileInput');
|
||||||
|
const uploadBtn = document.getElementById('uploadBtn');
|
||||||
|
const cancelBtn = document.getElementById('cancelBtn');
|
||||||
|
|
||||||
|
const progressText = document.getElementById("progress-text");
|
||||||
|
const speedText = document.getElementById("speed-text");
|
||||||
|
const etaText = document.getElementById("eta-text");
|
||||||
|
const progressBar = document.getElementById("progress-bar");
|
||||||
|
const progressContainer = document.getElementById("progress-container");
|
||||||
|
|
||||||
|
let currentXhr = null;
|
||||||
|
|
||||||
|
const CHUNK_THRESHOLD = 1024 * 1024 * 1024;
|
||||||
|
const CHUNK_SIZE = 10 * 1024 * 1024;
|
||||||
|
const MAX_PARALLEL_UPLOADS = 4;
|
||||||
|
const MAX_RETRIES = 3;
|
||||||
|
|
||||||
|
function formatBytes(bytes) {
|
||||||
|
if (bytes === 0) return '0 Bytes';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(seconds) {
|
||||||
|
if (!isFinite(seconds) || seconds < 0) return "--:--";
|
||||||
|
const h = Math.floor(seconds / 3600);
|
||||||
|
const m = Math.floor((seconds % 3600) / 60);
|
||||||
|
const s = Math.floor(seconds % 60);
|
||||||
|
return [
|
||||||
|
h > 0 ? h : null,
|
||||||
|
(h > 0 ? m.toString().padStart(2, '0') : m),
|
||||||
|
s.toString().padStart(2, '0')
|
||||||
|
].filter(Boolean).join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
function startUI() {
|
||||||
|
uploadBtn.disabled = true;
|
||||||
|
uploadBtn.innerText = "UPLOADING...";
|
||||||
|
cancelBtn.classList.remove('hidden');
|
||||||
|
progressContainer.classList.remove("hidden");
|
||||||
|
progressText.classList.remove("hidden");
|
||||||
|
document.getElementById("stats-text").classList.remove("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateProgress(loaded, total, startTime) {
|
||||||
|
const percent = Math.round((loaded / total) * 100);
|
||||||
|
progressBar.style.width = percent + "%";
|
||||||
|
progressText.innerText = percent + "%";
|
||||||
|
|
||||||
|
const elapsed = (Date.now() - startTime) / 1000;
|
||||||
|
if (elapsed <= 0) return;
|
||||||
|
|
||||||
|
const speed = loaded / elapsed;
|
||||||
|
const remaining = total - loaded;
|
||||||
|
|
||||||
|
speedText.innerText = formatBytes(speed) + "/S";
|
||||||
|
etaText.innerText = formatTime(remaining / speed);
|
||||||
|
}
|
||||||
|
|
||||||
|
function redirect(data) {
|
||||||
|
const key = data.view_key;
|
||||||
|
if (!key) {
|
||||||
|
alert("Invalid server response");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.location.href = "/f/" + key;
|
||||||
|
}
|
||||||
|
|
||||||
|
zone.onclick = () => input.click();
|
||||||
|
|
||||||
|
zone.ondragover = e => {
|
||||||
|
e.preventDefault();
|
||||||
|
zone.classList.add('active');
|
||||||
|
};
|
||||||
|
|
||||||
|
zone.ondragleave = () => zone.classList.remove('active');
|
||||||
|
|
||||||
|
zone.ondrop = e => {
|
||||||
|
e.preventDefault();
|
||||||
|
zone.classList.remove('active');
|
||||||
|
if (e.dataTransfer.files.length) {
|
||||||
|
input.files = e.dataTransfer.files;
|
||||||
|
input.dispatchEvent(new Event('change'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
input.onchange = () => {
|
||||||
|
const files = Array.from(input.files || []);
|
||||||
|
if (!files.length) {
|
||||||
|
uploadBtn.disabled = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = files.reduce((a, f) => a + f.size, 0);
|
||||||
|
document.getElementById('dz-text').innerText =
|
||||||
|
files.length === 1
|
||||||
|
? `${files[0].name} [${formatBytes(files[0].size)}]`
|
||||||
|
: `${files.length} FILES [${formatBytes(total)}]`;
|
||||||
|
|
||||||
|
uploadBtn.disabled = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
uploadBtn.onclick = () => {
|
||||||
|
const files = input.files;
|
||||||
|
if (!files.length) return;
|
||||||
|
|
||||||
|
if (files.length === 1 && files[0].size > CHUNK_THRESHOLD) {
|
||||||
|
uploadChunked(files[0]);
|
||||||
|
} else if (files.length === 1) {
|
||||||
|
uploadSingle(files[0]);
|
||||||
|
} else {
|
||||||
|
uploadMulti(files);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
cancelBtn.onclick = e => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (currentXhr) currentXhr.abort();
|
||||||
|
localStorage.clear();
|
||||||
|
location.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
function commonFormData() {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("once", document.getElementById("once").checked ? "true" : "false");
|
||||||
|
fd.append("duration", parseInt(document.getElementById("duration").value, 10));
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
function uploadSingle(file) {
|
||||||
|
startUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
fd.append("file", file);
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
xhr.upload.onprogress = e => {
|
||||||
|
if (e.lengthComputable) updateProgress(e.loaded, file.size, startTime);
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onload = () => {
|
||||||
|
try {
|
||||||
|
if (xhr.status < 200 || xhr.status >= 300) throw new Error();
|
||||||
|
redirect(JSON.parse(xhr.responseText));
|
||||||
|
} catch {
|
||||||
|
alert("Server error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onerror = () => {
|
||||||
|
if (xhr.statusText !== "abort") {
|
||||||
|
alert("Upload failed");
|
||||||
|
location.reload();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.open("POST", "/api/files/upload");
|
||||||
|
xhr.send(fd);
|
||||||
|
}
|
||||||
|
|
||||||
|
function uploadMulti(files) {
|
||||||
|
startUI();
|
||||||
|
|
||||||
|
const fd = commonFormData();
|
||||||
|
const list = Array.from(files);
|
||||||
|
list.forEach(f => fd.append("files", f));
|
||||||
|
|
||||||
|
const total = list.reduce((a, f) => a + f.size, 0);
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
xhr.upload.onprogress = e => {
|
||||||
|
if (e.lengthComputable) updateProgress(e.loaded, total, startTime);
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onload = () => {
|
||||||
|
try {
|
||||||
|
if (xhr.status < 200 || xhr.status >= 300) throw new Error();
|
||||||
|
redirect(JSON.parse(xhr.responseText));
|
||||||
|
} catch {
|
||||||
|
alert("Server error");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onerror = () => {
|
||||||
|
if (xhr.statusText !== "abort") {
|
||||||
|
alert("Upload failed");
|
||||||
|
location.reload();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.open("POST", "/api/files/upload-multi");
|
||||||
|
xhr.send(fd);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadChunked(file) {
|
||||||
|
startUI();
|
||||||
|
|
||||||
|
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
|
||||||
|
|
||||||
|
const initRes = await fetch("/api/files/upload/init", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/json"},
|
||||||
|
body: JSON.stringify({
|
||||||
|
filename: file.name,
|
||||||
|
totalChunks,
|
||||||
|
size: file.size
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const { fileId } = await initRes.json();
|
||||||
|
|
||||||
|
let uploadedBytes = 0;
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
const chunks = Array.from({ length: totalChunks }, (_, i) => ({
|
||||||
|
index: i,
|
||||||
|
start: i * CHUNK_SIZE,
|
||||||
|
end: Math.min((i + 1) * CHUNK_SIZE, file.size),
|
||||||
|
retries: 0,
|
||||||
|
uploading: false,
|
||||||
|
done: false
|
||||||
|
}));
|
||||||
|
|
||||||
|
let active = 0;
|
||||||
|
let completed = 0;
|
||||||
|
|
||||||
|
function uploadChunk(chunk) {
|
||||||
|
return new Promise((res, rej) => {
|
||||||
|
const blob = file.slice(chunk.start, chunk.end);
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("chunk", blob);
|
||||||
|
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
currentXhr = xhr;
|
||||||
|
|
||||||
|
let last = 0;
|
||||||
|
|
||||||
|
xhr.upload.onprogress = e => {
|
||||||
|
if (!e.lengthComputable) return;
|
||||||
|
const delta = e.loaded - last;
|
||||||
|
last = e.loaded;
|
||||||
|
uploadedBytes += delta;
|
||||||
|
updateProgress(uploadedBytes, file.size, startTime);
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onload = () => {
|
||||||
|
if (xhr.status >= 200 && xhr.status < 300) {
|
||||||
|
chunk.done = true;
|
||||||
|
completed++;
|
||||||
|
res();
|
||||||
|
} else {
|
||||||
|
rej();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onerror = rej;
|
||||||
|
|
||||||
|
xhr.open("POST", "/api/files/upload/chunk");
|
||||||
|
xhr.setRequestHeader("fileId", fileId);
|
||||||
|
xhr.setRequestHeader("chunkIndex", chunk.index);
|
||||||
|
xhr.send(fd);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
function next() {
|
||||||
|
if (completed === totalChunks) return finish();
|
||||||
|
|
||||||
|
while (active < MAX_PARALLEL_UPLOADS) {
|
||||||
|
const chunk = chunks.find(c => !c.done && !c.uploading);
|
||||||
|
if (!chunk) break;
|
||||||
|
|
||||||
|
chunk.uploading = true;
|
||||||
|
active++;
|
||||||
|
|
||||||
|
uploadChunk(chunk)
|
||||||
|
.then(() => {
|
||||||
|
active--;
|
||||||
|
next();
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
active--;
|
||||||
|
if (chunk.retries++ < MAX_RETRIES) {
|
||||||
|
chunk.uploading = false;
|
||||||
|
} else {
|
||||||
|
reject();
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finish() {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/files/upload/complete", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {"Content-Type": "application/json"},
|
||||||
|
body: JSON.stringify({
|
||||||
|
fileId,
|
||||||
|
filename: file.name,
|
||||||
|
totalChunks
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
redirect(await res.json());
|
||||||
|
resolve();
|
||||||
|
} catch {
|
||||||
|
reject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function copy(id) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
el.select();
|
||||||
|
document.execCommand('copy');
|
||||||
|
}
|
||||||
12
static/manifest.json
Normal file
12
static/manifest.json
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"name": "ReSendit",
|
||||||
|
"short_name": "ReSendit",
|
||||||
|
"start_url": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#ffffff",
|
||||||
|
"theme_color": "#000000",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "/logo.png", "sizes": "192x192", "type": "image/png" },
|
||||||
|
{ "src": "/logo.png", "sizes": "512x512", "type": "image/png" }
|
||||||
|
]
|
||||||
|
}
|
||||||
13
static/sw.js
Normal file
13
static/sw.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
self.addEventListener('install', e => {
|
||||||
|
e.waitUntil(
|
||||||
|
caches.open('resendit-v1').then(cache => {
|
||||||
|
return cache.addAll(['/', '/index.html', '/login.html', '/logo.png']);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
self.addEventListener('fetch', e => {
|
||||||
|
e.respondWith(
|
||||||
|
caches.match(e.request).then(response => response || fetch(e.request))
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -53,6 +53,13 @@
|
|||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
box-shadow: 3px 3px 0px #000;
|
box-shadow: 3px 3px 0px #000;
|
||||||
|
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
line-height: 1;
|
||||||
}
|
}
|
||||||
button:hover, .button:hover { background: #000; color: #fff; box-shadow: none; transform: translate(2px, 2px); }
|
button:hover, .button:hover { background: #000; color: #fff; box-shadow: none; transform: translate(2px, 2px); }
|
||||||
button:active { background: #ff0000; color: #fff; }
|
button:active { background: #ff0000; color: #fff; }
|
||||||
@@ -113,6 +120,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col items-end gap-2">
|
<div class="flex flex-col items-end gap-2">
|
||||||
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
||||||
|
<a href="/config" class="nav-link">CONFIG_MODULE</a>
|
||||||
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -179,12 +187,17 @@
|
|||||||
<td>
|
<td>
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
{{if not .Deleted}}
|
{{if not .Deleted}}
|
||||||
|
<a href="/f/{{.ViewID}}" target="_blank" class="button" title="Open download page">Link</a>
|
||||||
<form action="/api/files/admin/delete/{{.ID}}" method="GET" 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.')">
|
||||||
<button type="submit" style="background: #ffcccc;">Terminate</button>
|
<button type="submit" class="button" style="background: #ffcccc;">Terminate</button>
|
||||||
|
</form>
|
||||||
|
{{else}}
|
||||||
|
<form action="/api/files/admin/reinstate/{{.ID}}" method="GET" onsubmit="return openConfirm(event, 'REINSTATE', 'Restore this file to active status?')">
|
||||||
|
<button type="submit" class="button" style="background: #ccffcc;">Reinstate</button>
|
||||||
</form>
|
</form>
|
||||||
{{end}}
|
{{end}}
|
||||||
<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.')">
|
<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.')">
|
||||||
<button type="submit">Full_Wipe</button>
|
<button class="button" type="submit">Full_Wipe</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
@@ -208,6 +221,9 @@
|
|||||||
<div class="text-[12px] font-black uppercase">
|
<div class="text-[12px] font-black uppercase">
|
||||||
Data_Density: {{len .Files}} records | Page: {{.Page}}/{{.TotalPages}}
|
Data_Density: {{len .Files}} records | Page: {{.Page}}/{{.TotalPages}}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="text-[11px] font-black uppercase text-gray-600">
|
||||||
|
Build_Commit: {{.BuildCommit}}
|
||||||
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,105 +6,147 @@
|
|||||||
<title>Send.it - File Ready</title>
|
<title>Send.it - File Ready</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
|
||||||
<style>
|
<style>
|
||||||
/* No-design brutalist style */
|
|
||||||
* {
|
* {
|
||||||
border-radius: 0 !important;
|
border-radius: 0 !important;
|
||||||
transition: none !important;
|
transition: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #000;
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.box {
|
.box {
|
||||||
border: 2px solid #000;
|
border: 3px solid #000;
|
||||||
padding: 20px;
|
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-text {
|
.input-text {
|
||||||
border: 1px solid #000;
|
border: 2px solid #000;
|
||||||
padding: 4px 8px;
|
padding: 6px 10px;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
button {
|
||||||
border: 2px solid #000;
|
border: 2px solid #000;
|
||||||
background: #eee;
|
background: #fff;
|
||||||
padding: 4px 12px;
|
padding: 6px 14px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
font-size: 12px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
button:hover {
|
button:hover {
|
||||||
background: #ccc;
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
}
|
}
|
||||||
|
|
||||||
button:active {
|
button:active {
|
||||||
|
background: #ffff00;
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-label {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 11px;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
background: #000;
|
background: #000;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body class="min-h-screen flex items-center justify-center p-4">
|
<body class="min-h-screen flex flex-col items-center justify-center p-4">
|
||||||
|
|
||||||
<div class="w-full max-w-[493px] flex flex-col items-center">
|
<div class="w-full max-w-[520px] flex flex-col items-center">
|
||||||
|
|
||||||
<img src="/static/logo.png" alt="Send.it logo" style="width:50%;" class="mb-2 border-black">
|
<!-- Header -->
|
||||||
|
<header class="w-full mb-0 border-b-8 border-black pb-3 flex justify-between items-end">
|
||||||
<div class="box">
|
<div>
|
||||||
|
<img src="/static/logo.png" alt="Send.it logo" style="height:36px;" class="mb-1">
|
||||||
<header class="mb-6 border-b-2 border-black pb-2 text-center">
|
<h1 class="text-3xl font-black uppercase tracking-tighter leading-none">Send_It</h1>
|
||||||
<h1 class="text-xl font-bold uppercase">FILE READY</h1>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="space-y-4">
|
<!-- Main Box -->
|
||||||
|
<div class="box">
|
||||||
|
<div class="p-5 space-y-4">
|
||||||
|
|
||||||
<div class="bg-black text-white p-2 text-xs font-bold">
|
<!-- Status Banner -->
|
||||||
UPLOAD COMPLETE
|
<div class="border-2 border-black p-3" style="background:#00ff00;">
|
||||||
|
<span class="font-black text-sm uppercase">✓ File_Uploaded</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- <!– File info –>-->
|
<!-- Download Link -->
|
||||||
<!-- <div class="text-[10px] uppercase font-bold">-->
|
|
||||||
<!-- example_file.png (2.4 MB)-->
|
|
||||||
<!-- </div>-->
|
|
||||||
|
|
||||||
<!-- Download -->
|
|
||||||
<div>
|
<div>
|
||||||
<label class="text-[10px] font-bold block">DOWNLOAD LINK</label>
|
<div class="section-label mb-1">Download_Link:</div>
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<input id="res-url" readonly class="input-text text-sm">
|
<input id="res-url" readonly class="input-text">
|
||||||
<button onclick="copy('res-url')" class="border-l-0">COPY</button>
|
<button onclick="copy('res-url')" class="border-l-0 pl-1 pr-1">COPY</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Delete -->
|
<!-- Delete Link -->
|
||||||
<div>
|
<div>
|
||||||
<label class="text-[10px] font-bold block">DELETION LINK (PRIVATE)</label>
|
<div class="section-label mb-1 text-red-600">Deletion_Link <span class="text-gray-400 normal-case">(private)</span>:</div>
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<input id="res-del" readonly class="input-text text-sm text-red-600">
|
<input id="res-del" readonly class="input-text" style="color:#cc0000;">
|
||||||
<button onclick="copy('res-del')" class="border-l-0">COPY</button>
|
<button onclick="copy('res-del')" class="border-l-0 pl-1 pr-1">COPY</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button id="qr-btn" onclick="toggleQR()" class="pl-1 pr-1">Show_QR</button>
|
||||||
|
|
||||||
|
<div id="qr-container" class="mt-3 hidden border-2 border-black p-4 flex justify-center">
|
||||||
|
<div id="qr-code"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Actions -->
|
<!-- Actions -->
|
||||||
<div class="pt-4 flex justify-between">
|
<div class="border-t-2 border-black pt-4">
|
||||||
<a href="/" class="text-xs underline">NEW UPLOAD</a>
|
<a href="/" class="nav-link">← New_Upload</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p class="mt-1 text-[10px] uppercase font-bold text-gray-400">
|
<!-- Footer -->
|
||||||
A service by Brammie15
|
<div class="w-full mt-3 flex justify-between items-center">
|
||||||
</p>
|
<span class="text-[10px] font-black text-gray-400">{{ .MODT }}</span>
|
||||||
|
<div class="flex gap-4">
|
||||||
|
<a href="/static/TOS.txt" class="nav-link">TOS</a>
|
||||||
|
<a href="/admin" class="nav-link">SUDO</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -112,21 +154,36 @@
|
|||||||
function copy(id) {
|
function copy(id) {
|
||||||
const el = document.getElementById(id);
|
const el = document.getElementById(id);
|
||||||
el.select();
|
el.select();
|
||||||
el.setSelectionRange(0, 99999); // mobile support
|
el.setSelectionRange(0, 99999);
|
||||||
document.execCommand('copy');
|
document.execCommand('copy');
|
||||||
}
|
}
|
||||||
|
|
||||||
const downloadKey = "{{.DownloadID}}";
|
const downloadKey = "{{.DownloadID}}";
|
||||||
const deleteKey = "{{.DeleteID}}";
|
const deleteKey = "{{.DeleteID}}";
|
||||||
|
|
||||||
const base = window.location.origin;
|
const base = window.location.origin;
|
||||||
|
|
||||||
document.getElementById("res-url").value = `${base}/api/files/view/${downloadKey}`;
|
document.getElementById("res-url").value = `${base}/api/files/view/${downloadKey}`;
|
||||||
document.getElementById("res-del").value = `${base}/api/files/delete/${deleteKey}`;
|
document.getElementById("res-del").value = `${base}/api/files/delete/${deleteKey}`;
|
||||||
</script>
|
|
||||||
|
|
||||||
<a href="/admin" class="fixed bottom-1 right-1 text-[10px] underline">SUDO</a>
|
const downloadURL = `${base}/api/files/view/${downloadKey}`;
|
||||||
<a href="/static/TOS.txt" class="fixed bottom-1 left-1 text-[10px] underline">TOS</a>
|
|
||||||
|
// Generate QR code
|
||||||
|
new QRCode(document.getElementById("qr-code"), {
|
||||||
|
text: downloadURL,
|
||||||
|
width: 160,
|
||||||
|
height: 160
|
||||||
|
});
|
||||||
|
|
||||||
|
function toggleQR() {
|
||||||
|
const container = document.getElementById("qr-container");
|
||||||
|
const btn = document.getElementById("qr-btn");
|
||||||
|
|
||||||
|
const isHidden = container.classList.contains("hidden");
|
||||||
|
|
||||||
|
container.classList.toggle("hidden");
|
||||||
|
btn.textContent = isHidden ? "Hide_QR" : "Show_QR";
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
295
templates/config.html
Normal file
295
templates/config.html
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Config Module</title>
|
||||||
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* { border-radius: 0 !important; }
|
||||||
|
body {
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
background: #fff;
|
||||||
|
color: #000;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.box { border: 3px solid #000; background: #fff; padding: 20px; }
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
border-bottom: 3px solid #000;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 300px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
border: 2px solid #000;
|
||||||
|
padding: 6px 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
font-size: 11px;
|
||||||
|
font-style: italic;
|
||||||
|
margin-top: 4px;
|
||||||
|
border-left: 4px solid #000;
|
||||||
|
padding-left: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button, .button {
|
||||||
|
border: 2px solid #000;
|
||||||
|
background: #fff;
|
||||||
|
padding: 6px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover, .button:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ok {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #00ff00;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.err {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="max-w-4xl mx-auto">
|
||||||
|
|
||||||
|
<!-- HEADER -->
|
||||||
|
<header class="mb-6 border-b-8 border-black pb-4 flex justify-between items-start">
|
||||||
|
<h1 class="text-4xl font-black uppercase tracking-tighter leading-none">
|
||||||
|
Config_Settings
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div class="flex flex-col items-end gap-2">
|
||||||
|
<a href="/admin" class="nav-link">Admin_Panel</a>
|
||||||
|
<a href="/config" class="nav-link">Reload_Config</a>
|
||||||
|
<a href="/logout" class="nav-link text-red-600">Logout</a>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- STATUS -->
|
||||||
|
{{if .Success}}
|
||||||
|
<div class="ok mb-4">CONFIG_SAVED_SUCCESSFULLY</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .Error}}
|
||||||
|
<div class="err mb-4">{{.Error}}</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
<form method="POST" action="/config">
|
||||||
|
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">General_Settings</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Site_MODT</label>
|
||||||
|
<input type="text" name="site_modt" value="{{.MODT}}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- UPLOAD SETTINGS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Upload_Control</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_File_Size_MB</label>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex gap-2 items-center">
|
||||||
|
<input id="fileSizeMB" type="number" min="1" name="upload_max_file_size_mb" value="{{.UploadMaxFileSizeMB}}">
|
||||||
|
|
||||||
|
<input id="fileSizeGB" type="text" readonly placeholder="GB"
|
||||||
|
class="w-24 bg-gray-100 cursor-not-allowed">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hint">Hard limit enforced by upload endpoints</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Multi_Upload_Limit</label>
|
||||||
|
<div>
|
||||||
|
<input type="number" min="1" name="upload_multi_max_files" value="{{.UploadMultiMaxFiles}}">
|
||||||
|
<div class="hint">Max files per multi-upload request</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_Expiry_Hours</label>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex gap-2 items-center">
|
||||||
|
<input id="hoursInput" type="number" min="1" name="upload_max_hours" value="{{.UploadMaxHours}}">
|
||||||
|
|
||||||
|
<input id="daysOutput" type="text" readonly placeholder="Days" class="w-24 bg-gray-100 cursor-not-allowed">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hint">User duration capped to this value</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RATE LIMITS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Rate_Limits_(Static)</div>
|
||||||
|
|
||||||
|
<div class="hint mb-4">
|
||||||
|
Changes require server restart to take effect
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_per_minute" value="{{.RateLimitLoginPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_burst" value="{{.RateLimitLoginBurst}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_per_minute" value="{{.RateLimitApiPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_burst" value="{{.RateLimitApiBurst}}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">NTFY_Settings</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Use_NTFY</label>
|
||||||
|
<input type="checkbox" id="ntfy_use_seen" {{if .NtfyUse}}checked{{end}}>
|
||||||
|
<input type="hidden" name="ntfy_use" id="ntfy_use_hidden" value="{{if .NtfyUse}}true{{else}}false{{end}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>NTFY_Url</label>
|
||||||
|
<input type="text" name="ntfy_url" value="{{.NtfyUrl}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>NTFY_Topic</label>
|
||||||
|
<input type="text" name="ntfy_topic" value="{{.NtfyTopic}}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ACTIONS -->
|
||||||
|
<div class="flex justify-between items-center border-t-8 border-black pt-4">
|
||||||
|
<button type="submit">SAVE</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/change-password" class="fixed bottom-1 left-1 text-[10px] underline">
|
||||||
|
CHANGE_PASSWORD
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function formatNumber(num) {
|
||||||
|
return parseFloat(num.toFixed(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateConversions() {
|
||||||
|
const mb = parseFloat(document.getElementById('fileSizeMB')?.value);
|
||||||
|
const gbField = document.getElementById('fileSizeGB');
|
||||||
|
|
||||||
|
if (!isNaN(mb) && gbField) {
|
||||||
|
gbField.value = formatNumber(mb / 1024) + " GB";
|
||||||
|
} else if (gbField) {
|
||||||
|
gbField.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const hours = parseFloat(document.getElementById('hoursInput')?.value);
|
||||||
|
const daysField = document.getElementById('daysOutput');
|
||||||
|
|
||||||
|
if (!isNaN(hours) && daysField) {
|
||||||
|
daysField.value = formatNumber(hours / 24) + " days";
|
||||||
|
} else if (daysField) {
|
||||||
|
daysField.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run on load
|
||||||
|
window.addEventListener('DOMContentLoaded', updateConversions);
|
||||||
|
|
||||||
|
// Listen for changes
|
||||||
|
document.addEventListener('input', updateConversions);
|
||||||
|
|
||||||
|
const checkbox = document.getElementById('ntfy_use_seen');
|
||||||
|
const hidden = document.getElementById('ntfy_use_hidden');
|
||||||
|
|
||||||
|
if (checkbox && hidden) {
|
||||||
|
// Update hidden input whenever checkbox changes
|
||||||
|
checkbox.addEventListener('change', () => {
|
||||||
|
hidden.value = checkbox.checked ? "true" : "false";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -6,7 +6,6 @@
|
|||||||
<title>Nothing to see here</title>
|
<title>Nothing to see here</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
* {
|
* {
|
||||||
border-radius: 0 !important;
|
border-radius: 0 !important;
|
||||||
@@ -14,48 +13,56 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #000;
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.box {
|
.box {
|
||||||
border: 2px solid #000;
|
border: 3px solid #000;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.button {
|
a.button {
|
||||||
border: 2px solid #000;
|
border: 2px solid #000;
|
||||||
background: #eee;
|
background: #fff;
|
||||||
padding: 4px 12px;
|
padding: 6px 14px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
font-size: 12px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.button:hover {
|
a.button:hover {
|
||||||
background: #ccc;
|
|
||||||
}
|
|
||||||
|
|
||||||
.button:active {
|
|
||||||
background: #000;
|
background: #000;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
a.button:active {
|
||||||
|
background: #ffff00;
|
||||||
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
font-size: 28px;
|
font-size: 28px;
|
||||||
font-weight: 900;
|
font-weight: 900;
|
||||||
border-bottom: 2px solid #000;
|
border-bottom: 3px solid #000;
|
||||||
margin-bottom: 10px;
|
margin-bottom: 10px;
|
||||||
padding-bottom: 4px;
|
padding-bottom: 4px;
|
||||||
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
.subtitle {
|
.subtitle {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
}
|
}
|
||||||
@@ -63,14 +70,35 @@
|
|||||||
.text {
|
.text {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
|
font-weight: 700;
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 11px;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="min-h-screen flex items-center justify-center p-4">
|
<body class="min-h-screen flex items-center justify-center p-4">
|
||||||
|
|
||||||
<div class="w-full max-w-[493px] flex flex-col items-center">
|
<div class="w-full max-w-[493px] flex flex-col items-center">
|
||||||
|
|
||||||
|
<header class="w-full mb-0 border-b-8 border-black pb-3 flex justify-between items-end">
|
||||||
|
<div>
|
||||||
|
<img src="/static/logo.png" alt="Send.it logo" style="height:36px;" class="mb-1">
|
||||||
|
<h1 class="text-3xl font-black uppercase tracking-tighter leading-none">Send_It</h1>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
<div class="box text-center">
|
<div class="box text-center">
|
||||||
|
|
||||||
<div class="title">
|
<div class="title">
|
||||||
@@ -93,6 +121,14 @@
|
|||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="w-full mt-3 flex justify-between items-center">
|
||||||
|
<span class="text-[10px] font-black text-gray-400">{{.MODT}}</span>
|
||||||
|
<div class="flex gap-4">
|
||||||
|
<a href="/static/TOS.txt" class="nav-link">TOS</a>
|
||||||
|
<a href="/admin" class="nav-link">SUDO</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -6,48 +6,72 @@
|
|||||||
<title>Send.it</title>
|
<title>Send.it</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
<link rel="manifest" href="/static/manifest.json">
|
||||||
|
<script>
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
navigator.serviceWorker.register('/static/sw.js');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
<style>
|
<style>
|
||||||
/* The "No-Design" Design */
|
|
||||||
* {
|
* {
|
||||||
border-radius: 0 !important;
|
border-radius: 0 !important;
|
||||||
transition: none !important;
|
transition: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #000;
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.box {
|
.box {
|
||||||
border: 2px solid #000;
|
border: 3px solid #000;
|
||||||
padding: 20px;
|
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.input-text {
|
.input-text {
|
||||||
border: 1px solid #000;
|
border: 2px solid #000;
|
||||||
padding: 4px 8px;
|
padding: 6px 10px;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
border: 2px solid #000;
|
||||||
|
padding: 5px 8px;
|
||||||
|
background: #fff;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
button {
|
||||||
border: 2px solid #000;
|
border: 2px solid #000;
|
||||||
background: #eee;
|
background: #fff;
|
||||||
padding: 4px 12px;
|
padding: 6px 14px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
font-size: 12px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
button:hover {
|
button:hover {
|
||||||
background: #ccc;
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
}
|
}
|
||||||
|
|
||||||
button:active {
|
button:active {
|
||||||
background: #000;
|
background: #ffff00;
|
||||||
color: #fff;
|
color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
button:disabled {
|
button:disabled {
|
||||||
@@ -55,66 +79,150 @@
|
|||||||
color: #999;
|
color: #999;
|
||||||
border-color: #ccc;
|
border-color: #ccc;
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled:hover {
|
||||||
|
transform: none;
|
||||||
|
background: #f0f0f0;
|
||||||
|
color: #999;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-cancel {
|
.btn-cancel {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #cc0000;
|
color: #cc0000;
|
||||||
border-color: #cc0000;
|
border-color: #cc0000;
|
||||||
|
box-shadow: 3px 3px 0px #cc0000;
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
font-size: 10px;
|
font-size: 11px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-cancel:hover {
|
.btn-cancel:hover {
|
||||||
background: #fee2e2;
|
background: #cc0000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.drop-zone {
|
.drop-zone {
|
||||||
border: 2px dashed #000;
|
border: 3px dashed #000;
|
||||||
padding: 80px;
|
padding: 60px 40px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
background: #f9f9f9;
|
background: #f9f9f9;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.drop-zone.active {
|
.drop-zone.active {
|
||||||
background: #eee;
|
background: #ffff00;
|
||||||
border-style: solid;
|
border-style: solid;
|
||||||
}
|
}
|
||||||
|
|
||||||
.burn-option {
|
.drop-zone:hover {
|
||||||
|
background: #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.burn-label {
|
||||||
color: #cc0000;
|
color: #cc0000;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
font-size: 11px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-label {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-tag {
|
||||||
|
font-weight: 900;
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 3px 8px;
|
||||||
|
border: 2px solid #000;
|
||||||
|
display: inline-block;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-success {
|
||||||
|
background: #00ff00;
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 11px;
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="checkbox"] {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border: 2px solid #000;
|
||||||
|
appearance: none;
|
||||||
|
background: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
position: relative;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="checkbox"]:checked {
|
||||||
|
background: #ff00ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="checkbox"]:checked::after {
|
||||||
|
content: '✕';
|
||||||
|
position: absolute;
|
||||||
|
top: -2px;
|
||||||
|
left: 1px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
|
font-weight: 900;
|
||||||
|
color: #fff;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="min-h-screen flex items-center justify-center p-4">
|
<body class="min-h-screen flex flex-col items-center justify-center p-4">
|
||||||
|
|
||||||
<!--<div class="w-full max-w-[493px] flex flex-col items-end">-->
|
<div class="w-full max-w-[520px] flex flex-col items-center">
|
||||||
<div class="w-full max-w-[493px] flex flex-col items-center">
|
|
||||||
<img src="/static/logo.png" alt="Send.it logo" style="width:50%;" class="mb-2 border-black">
|
<!-- Header -->
|
||||||
<div class="box">
|
<header class="w-full mb-0 border-b-8 border-black pb-3 flex justify-between items-end">
|
||||||
<header class="mb-6 border-b-2 border-black pb-2 text-center">
|
<div>
|
||||||
<h1 class="text-xl font-bold uppercase">Send it</h1>
|
<img src="/static/logo.png" alt="Send.it logo" style="height:36px;" class="mb-1">
|
||||||
|
<h1 class="text-3xl font-black uppercase tracking-tighter leading-none">Send_It</h1>
|
||||||
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div id="upload-ui">
|
<!-- Main Box -->
|
||||||
<div id="drop-zone" class="drop-zone mb-4">
|
<div class="box">
|
||||||
|
|
||||||
|
<!-- Upload UI -->
|
||||||
|
<div id="upload-ui" class="p-5 space-y-4">
|
||||||
|
|
||||||
|
<!-- Drop Zone -->
|
||||||
|
<div id="drop-zone" class="drop-zone">
|
||||||
<input type="file" id="fileInput" class="hidden" multiple>
|
<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>
|
<div class="text-2xl mb-2">↓</div>
|
||||||
|
<span id="dz-text" class="section-label text-gray-500">Click to select or drop file(s)</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="progress-container" class="hidden mt-3 border border-black h-4">
|
<!-- Progress Bar -->
|
||||||
|
<div id="progress-container" class="hidden mt-4 border-2 border-black h-5 bg-white">
|
||||||
<div id="progress-bar" class="h-full bg-black" style="width:0%"></div>
|
<div id="progress-bar" class="h-full bg-black" style="width:0%"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex justify-between items-center mt-1">
|
<div class="flex justify-between items-center mt-1">
|
||||||
<div id="progress-text" class="text-[10px] font-bold hidden">0%</div>
|
<div id="progress-text" class="text-[10px] font-black hidden">0%</div>
|
||||||
<div id="stats-text" class="text-[10px] font-bold hidden uppercase">
|
<div id="stats-text" class="text-[10px] font-black hidden uppercase">
|
||||||
<span id="speed-text">0 KB/S</span>
|
<span id="speed-text">0 KB/S</span>
|
||||||
<span class="mx-1 opacity-30">|</span>
|
<span class="mx-1 opacity-30">|</span>
|
||||||
<span id="eta-text">--:--</span>
|
<span id="eta-text">--:--</span>
|
||||||
@@ -122,259 +230,71 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="space-y-4">
|
<!-- Config Row -->
|
||||||
<div class="flex items-center justify-between border-b border-black pb-2">
|
<div class="border-t-2 border-b-2 border-black py-3 space-y-3">
|
||||||
<label class="text-xs font-bold uppercase">Expire In:</label>
|
<div class="flex items-center justify-between">
|
||||||
<select id="duration" class="border border-black text-xs p-1">
|
<span class="section-label">Expire_In:</span>
|
||||||
<option value="1">1 Hour</option>
|
<select id="duration">
|
||||||
<option value="24">24 Hours</option>
|
<option value="1">1_Hour</option>
|
||||||
<option value="168">7 Days</option>
|
<option value="24">24_Hours</option>
|
||||||
<option value="730" selected>1 Month</option>
|
<option value="168">7_Days</option>
|
||||||
|
<option value="730" selected>1_Month</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-3">
|
||||||
<input type="checkbox" id="once" class="w-4 h-4 border-black">
|
<input type="checkbox" id="once">
|
||||||
<label for="once" class="burn-option uppercase">Burn after</label>
|
<label for="once" class="burn-label">Burn_After_Download</label>
|
||||||
</div>
|
|
||||||
|
|
||||||
<button id="uploadBtn" class="w-full" disabled>UPLOAD</button>
|
|
||||||
<button id="cancelBtn" class="btn-cancel hidden">CANCEL UPLOAD</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="success-ui" class="hidden space-y-4">
|
<!-- Actions -->
|
||||||
<div class="bg-black text-white p-2 text-xs font-bold">
|
<div>
|
||||||
UPLOAD COMPLETE
|
<button id="uploadBtn" class="w-full py-3 text-sm" disabled>UPLOAD_FILE</button>
|
||||||
|
<button id="cancelBtn" class="btn-cancel hidden">✕ CANCEL_UPLOAD</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Success UI -->
|
||||||
|
<div id="success-ui" class="hidden p-5 space-y-4">
|
||||||
|
<div class="border-2 border-black p-3" style="background:#00ff00;">
|
||||||
|
<span class="font-black text-sm uppercase">✓ Upload_Complete</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label class="text-[10px] font-bold block">DOWNLOAD LINK</label>
|
<div class="section-label mb-1">Download_Link:</div>
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<input id="res-url" readonly class="input-text text-sm">
|
<input id="res-url" readonly class="input-text">
|
||||||
<button onclick="copy('res-url')" class="border-l-0">COPY</button>
|
<button onclick="copy('res-url')" class="border-l-0 whitespace-nowrap">COPY</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label class="text-[10px] font-bold block">DELETION LINK (PRIVATE)</label>
|
<div class="section-label mb-1 text-red-600">Deletion_Link <span class="text-gray-400">(private)</span>:</div>
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<input id="res-del" readonly class="input-text text-sm text-red-600">
|
<input id="res-del" readonly class="input-text" style="color:#cc0000;">
|
||||||
<button onclick="copy('res-del')" class="border-l-0">COPY</button>
|
<button onclick="copy('res-del')" class="border-l-0 whitespace-nowrap">COPY</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pt-4 flex justify-between">
|
<div class="border-t-2 border-black pt-3">
|
||||||
<button onclick="location.reload()" class="text-xs">NEW UPLOAD</button>
|
<button onclick="location.reload()" class="text-xs">← New_Upload</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<p class="mt-1 text-[10px] uppercase font-bold text-gray-400">A service by Brammie15</p>
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<!-- Footer -->
|
||||||
const zone = document.getElementById('drop-zone');
|
<div class="w-full mt-3 flex justify-between items-center">
|
||||||
const input = document.getElementById('fileInput');
|
<span class="text-[10px] font-black text-gray-400">{{.MODT}}</span>
|
||||||
const uploadBtn = document.getElementById('uploadBtn');
|
<div class="flex gap-4">
|
||||||
const cancelBtn = document.getElementById('cancelBtn');
|
<a href="/static/TOS.txt" class="nav-link">TOS</a>
|
||||||
|
<a href="/admin" class="nav-link">SUDO</a>
|
||||||
const progressText = document.getElementById("progress-text");
|
</div>
|
||||||
const statsText = document.getElementById("stats-text");
|
</div>
|
||||||
const speedText = document.getElementById("speed-text");
|
|
||||||
const etaText = document.getElementById("eta-text");
|
|
||||||
const progressBar = document.getElementById("progress-bar");
|
|
||||||
const progressContainer = document.getElementById("progress-container");
|
|
||||||
|
|
||||||
let currentXhr = null;
|
|
||||||
|
|
||||||
// Helper: Human Readable Size
|
|
||||||
function formatBytes(bytes, decimals = 2) {
|
|
||||||
if (bytes === 0) return '0 Bytes';
|
|
||||||
const k = 1024;
|
|
||||||
const dm = decimals < 0 ? 0 : decimals;
|
|
||||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper: Human Readable Time
|
|
||||||
function formatTime(seconds) {
|
|
||||||
if (!isFinite(seconds) || seconds < 0) return "--:--";
|
|
||||||
const h = Math.floor(seconds / 3600);
|
|
||||||
const m = Math.floor((seconds % 3600) / 60);
|
|
||||||
const s = Math.floor(seconds % 60);
|
|
||||||
return [
|
|
||||||
h > 0 ? h : null,
|
|
||||||
(h > 0 ? m.toString().padStart(2, '0') : m),
|
|
||||||
s.toString().padStart(2, '0')
|
|
||||||
].filter(x => x !== null).join(':');
|
|
||||||
}
|
|
||||||
|
|
||||||
zone.onclick = () => input.click();
|
|
||||||
|
|
||||||
zone.ondragover = (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
zone.classList.add('active');
|
|
||||||
};
|
|
||||||
zone.ondragleave = () => zone.classList.remove('active');
|
|
||||||
|
|
||||||
zone.ondrop = (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
zone.classList.remove('active');
|
|
||||||
|
|
||||||
if (e.dataTransfer.files.length) {
|
|
||||||
input.files = e.dataTransfer.files;
|
|
||||||
input.dispatchEvent(new Event('change'));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
input.onchange = () => {
|
|
||||||
if (input.files.length) {
|
|
||||||
showFiles(input.files);
|
|
||||||
uploadBtn.disabled = false;
|
|
||||||
} else {
|
|
||||||
uploadBtn.disabled = true;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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 =
|
|
||||||
`${files[0].name} (${formatBytes(files[0].size)})`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById('dz-text').innerText =
|
|
||||||
`${files.length} FILES (${formatBytes(total)}) — will be zipped`;
|
|
||||||
}
|
|
||||||
|
|
||||||
uploadBtn.onclick = () => {
|
|
||||||
if (!input.files.length) return;
|
|
||||||
if (input.files.length === 1) {
|
|
||||||
handleUploadSingle(input.files[0]);
|
|
||||||
} else {
|
|
||||||
handleUploadMulti(input.files);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
cancelBtn.onclick = (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
if (currentXhr) {
|
|
||||||
currentXhr.abort();
|
|
||||||
alert("Upload cancelled.");
|
|
||||||
location.reload();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
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.innerText = "UPLOADING...";
|
|
||||||
cancelBtn.classList.remove('hidden');
|
|
||||||
|
|
||||||
progressContainer.classList.remove("hidden");
|
|
||||||
progressText.classList.remove("hidden");
|
|
||||||
statsText.classList.remove("hidden");
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupXHRHandlers(xhr) {
|
|
||||||
let startTime = Date.now();
|
|
||||||
|
|
||||||
xhr.upload.onprogress = (e) => {
|
|
||||||
if (e.lengthComputable) {
|
|
||||||
const percent = Math.round((e.loaded / e.total) * 100);
|
|
||||||
progressBar.style.width = percent + "%";
|
|
||||||
progressText.innerText = percent + "%";
|
|
||||||
|
|
||||||
const elapsedSeconds = (Date.now() - startTime) / 1000;
|
|
||||||
if (elapsedSeconds > 0) {
|
|
||||||
const bytesPerSecond = e.loaded / elapsedSeconds;
|
|
||||||
const remainingBytes = e.total - e.loaded;
|
|
||||||
const secondsRemaining = remainingBytes / bytesPerSecond;
|
|
||||||
|
|
||||||
speedText.innerText = formatBytes(bytesPerSecond) + "/S";
|
|
||||||
etaText.innerText = formatTime(secondsRemaining);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onload = () => {
|
|
||||||
if (xhr.status >= 200 && xhr.status < 300) {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(xhr.responseText);
|
|
||||||
if (data.error) throw new Error(data.error);
|
|
||||||
|
|
||||||
window.location.href = "/f/" + data.view_key;
|
|
||||||
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Invalid response:", xhr.responseText);
|
|
||||||
alert("Server error");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
alert("Upload failed");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onerror = () => {
|
|
||||||
if (xhr.statusText !== "abort") {
|
|
||||||
alert("Upload failed");
|
|
||||||
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.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) {
|
|
||||||
const el = document.getElementById(id);
|
|
||||||
el.select();
|
|
||||||
document.execCommand('copy');
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
<a href="/admin" class="fixed bottom-1 right-1 text-[10px] underline">SUDO</a>
|
|
||||||
<a href="/static/TOS.txt" class="fixed bottom-1 left-1 text-[10px] underline">TOS</a>
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<script src="/static/js/upload.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -10,64 +10,83 @@
|
|||||||
* { border-radius: 0 !important; }
|
* { border-radius: 0 !important; }
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #000;
|
color: #000;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.box {
|
.box {
|
||||||
border: 2px solid #000;
|
border: 3px solid #000;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
input {
|
input {
|
||||||
border: 1px solid #000;
|
border: 2px solid #000;
|
||||||
padding: 6px;
|
padding: 8px;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
input:focus {
|
input:focus {
|
||||||
outline: none;
|
outline: none;
|
||||||
background: #f9f9f9;
|
background: #ffff00;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Chunky button style */
|
||||||
button {
|
button {
|
||||||
border: 1px solid #000;
|
border: 2px solid #000;
|
||||||
background: #eee;
|
background: #fff;
|
||||||
padding: 4px 10px;
|
padding: 6px 12px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
button:hover {
|
button:hover {
|
||||||
background: #000;
|
background: #000;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.nav-link {
|
.nav-link {
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
font-size: 11px;
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
}
|
}
|
||||||
|
|
||||||
.label {
|
.label {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
margin-bottom: 2px;
|
margin-bottom: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.error {
|
.error {
|
||||||
border: 1px solid #000;
|
border: 3px solid #000;
|
||||||
background: #ffcccc;
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
padding: 4px;
|
padding: 6px;
|
||||||
margin-bottom: 10px;
|
margin-bottom: 12px;
|
||||||
font-weight: bold;
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -75,26 +94,25 @@
|
|||||||
|
|
||||||
<div class="max-w-md mx-auto">
|
<div class="max-w-md mx-auto">
|
||||||
|
|
||||||
<header class="mb-8 border-b-4 border-black pb-2 flex justify-between items-end">
|
<header class="mb-8 border-b-8 border-black pb-4 flex justify-between items-start">
|
||||||
<h1 class="text-3xl font-black uppercase tracking-tighter">
|
<h1 class="text-4xl font-black uppercase tracking-tighter leading-none">
|
||||||
System Access
|
System_Access
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<a href="/" class="nav-link">
|
<a href="/" class="nav-link">
|
||||||
← BACK
|
← Back
|
||||||
</a>
|
</a>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
<div class="box p-6">
|
||||||
<div class="box p-4">
|
|
||||||
|
|
||||||
{{if .Error}}
|
{{if .Error}}
|
||||||
<div class="error">
|
<div class="error">
|
||||||
ACCESS DENIED
|
ACCESS_DENIED
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
<form id="login-form" class="space-y-3">
|
<form id="login-form" class="space-y-4">
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<div class="label">Username</div>
|
<div class="label">Username</div>
|
||||||
@@ -108,7 +126,7 @@
|
|||||||
|
|
||||||
<div class="pt-2">
|
<div class="pt-2">
|
||||||
<button type="submit">
|
<button type="submit">
|
||||||
AUTHENTICATE
|
Authenticate
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -145,7 +163,6 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redirect to admin
|
|
||||||
window.location.href = "/admin";
|
window.location.href = "/admin";
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -159,7 +176,7 @@
|
|||||||
err = document.createElement("div");
|
err = document.createElement("div");
|
||||||
err.id = "error-box";
|
err.id = "error-box";
|
||||||
err.className = "error";
|
err.className = "error";
|
||||||
err.innerText = "ACCESS DENIED";
|
err.innerText = "ACCESS_DENIED";
|
||||||
form.prepend(err);
|
form.prepend(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user