add loger, access log and bans/whitelist

This commit is contained in:
nahakubuilde
2025-08-26 07:46:01 +01:00
parent e21a0b5b10
commit 4cafd9848f
10 changed files with 1163 additions and 60 deletions

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"html/template"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
@@ -43,8 +44,11 @@ func New(cfg *config.Config) *Server {
auth: authSvc,
}
// Global middlewares: session user + template setup
// Global middlewares
s.router.Use(s.SessionUser())
// Enforce IP bans/whitelists and log access for every request
s.router.Use(s.IPBanEnforce())
s.router.Use(s.AccessLogger())
s.setupRoutes()
s.setupStaticFiles()
@@ -66,6 +70,9 @@ func (s *Server) Start() error {
}
}
// Start background cleanup for access logs older than 7 days (daily)
go s.startAccessLogCleanup()
addr := fmt.Sprintf("%s:%d", s.config.Host, s.config.Port)
fmt.Printf("Starting Gobsidian server on %s\n", addr)
fmt.Printf("Notes directory: %s\n", s.config.NotesDir)
@@ -119,6 +126,9 @@ func (s *Server) setupRoutes() {
editor.POST("/settings/notes_dir", h.PostNotesDirSettingsHandler)
editor.GET("/settings/file_extensions", h.GetFileExtensionsSettingsHandler)
editor.POST("/settings/file_extensions", h.PostFileExtensionsSettingsHandler)
// Security settings (IP ban thresholds/duration/permanent)
editor.GET("/settings/security", h.GetSecuritySettingsHandler)
editor.POST("/settings/security", h.PostSecuritySettingsHandler)
// Profile
editor.GET("/profile", h.ProfilePage)
@@ -136,6 +146,14 @@ func (s *Server) setupRoutes() {
// Admin CRUD API under /editor/admin
admin := editor.Group("/admin", s.RequireAdmin())
{
// Logs page
admin.GET("/logs", h.AdminLogsPage)
// Manual clear old access logs (older than 7 days)
admin.POST("/logs/clear_access", h.AdminClearAccessLogs)
// Security: IP ban/whitelist actions
admin.POST("/ip/ban", h.AdminBanIP)
admin.POST("/ip/unban", h.AdminUnbanIP)
admin.POST("/ip/whitelist", h.AdminWhitelistIP)
admin.POST("/users", h.AdminCreateUser)
admin.DELETE("/users/:id", h.AdminDeleteUser)
admin.POST("/users/:id/active", h.AdminSetUserActive)
@@ -232,3 +250,13 @@ func (s *Server) setupTemplates() {
fmt.Printf("DEBUG: Templates loaded successfully\n")
}
// startAccessLogCleanup deletes access logs older than 7 days once at startup and then daily.
func (s *Server) startAccessLogCleanup() {
// initial cleanup
_, _ = s.auth.DB.Exec(`DELETE FROM access_logs WHERE created_at < DATETIME('now', '-7 days')`)
ticker := time.NewTicker(24 * time.Hour)
for range ticker.C {
_, _ = s.auth.DB.Exec(`DELETE FROM access_logs WHERE created_at < DATETIME('now', '-7 days')`)
}
}