Compare commits
3 Commits
4cafd9848f
...
latest
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
090d491dd6 | ||
|
|
e8658f5aab | ||
|
|
6fb6054803 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -13,3 +13,5 @@ __pycache__/
|
||||
*.sqlite3
|
||||
*.log
|
||||
*.bak
|
||||
|
||||
./gobsidian
|
||||
@@ -122,7 +122,8 @@ gobsidian/
|
||||
To build a standalone binary:
|
||||
|
||||
```bash
|
||||
go build -o gobsidian cmd/main.go
|
||||
go mod tidy
|
||||
go build -o gobsidian ./cmd
|
||||
```
|
||||
## Image storing trying to follow Obsidian settings
|
||||
Image storing modes:
|
||||
|
||||
@@ -17,6 +17,7 @@ type Config struct {
|
||||
SecretKey string
|
||||
Debug bool
|
||||
MaxContentLength int64 // in bytes
|
||||
URLPrefix string
|
||||
|
||||
// MD Notes App settings
|
||||
AppName string
|
||||
@@ -41,9 +42,9 @@ type Config struct {
|
||||
DBPath string
|
||||
|
||||
// Auth settings
|
||||
RequireAdminActivation bool
|
||||
RequireAdminActivation bool
|
||||
RequireEmailConfirmation bool
|
||||
MFAEnabledByDefault bool
|
||||
MFAEnabledByDefault bool
|
||||
|
||||
// Email (SMTP) settings
|
||||
SMTPHost string
|
||||
@@ -54,11 +55,11 @@ type Config struct {
|
||||
SMTPUseTLS bool
|
||||
|
||||
// Security settings (failed-login thresholds and auto-ban config)
|
||||
PwdFailuresThreshold int
|
||||
MFAFailuresThreshold int
|
||||
FailuresWindowMinutes int
|
||||
AutoBanDurationHours int
|
||||
AutoBanPermanent bool
|
||||
PwdFailuresThreshold int
|
||||
MFAFailuresThreshold int
|
||||
FailuresWindowMinutes int
|
||||
AutoBanDurationHours int
|
||||
AutoBanPermanent bool
|
||||
}
|
||||
|
||||
var defaultConfig = map[string]map[string]string{
|
||||
@@ -68,6 +69,7 @@ var defaultConfig = map[string]map[string]string{
|
||||
"SECRET_KEY": "change-this-secret-key",
|
||||
"DEBUG": "false",
|
||||
"MAX_CONTENT_LENGTH": "16", // in MB
|
||||
"URL_PREFIX": "",
|
||||
},
|
||||
"MD_NOTES_APP": {
|
||||
"APP_NAME": "Gobsidian",
|
||||
@@ -91,9 +93,9 @@ var defaultConfig = map[string]map[string]string{
|
||||
"PATH": "data/gobsidian.db",
|
||||
},
|
||||
"AUTH": {
|
||||
"REQUIRE_ADMIN_ACTIVATION": "true",
|
||||
"REQUIRE_ADMIN_ACTIVATION": "true",
|
||||
"REQUIRE_EMAIL_CONFIRMATION": "true",
|
||||
"MFA_ENABLED_BY_DEFAULT": "false",
|
||||
"MFA_ENABLED_BY_DEFAULT": "false",
|
||||
},
|
||||
"EMAIL": {
|
||||
"SMTP_HOST": "",
|
||||
@@ -112,8 +114,20 @@ var defaultConfig = map[string]map[string]string{
|
||||
},
|
||||
}
|
||||
|
||||
// exeDir returns the directory containing the running executable.
|
||||
func exeDir() string {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
wd, _ := os.Getwd()
|
||||
return wd
|
||||
}
|
||||
return filepath.Dir(exe)
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
configPath := "settings.ini"
|
||||
baseDir := exeDir()
|
||||
// settings.ini lives next to the executable
|
||||
configPath := filepath.Join(baseDir, "settings.ini")
|
||||
|
||||
// Ensure config file exists
|
||||
if err := ensureConfigFile(configPath); err != nil {
|
||||
@@ -136,6 +150,14 @@ func Load() (*Config, error) {
|
||||
config.Debug, _ = SERVERSection.Key("DEBUG").Bool()
|
||||
maxContentMB, _ := SERVERSection.Key("MAX_CONTENT_LENGTH").Int()
|
||||
config.MaxContentLength = int64(maxContentMB) * 1024 * 1024 // Convert MB to bytes
|
||||
// Normalize URL prefix: "" or starts with '/' and no trailing '/'
|
||||
rawPrefix := strings.TrimSpace(SERVERSection.Key("URL_PREFIX").String())
|
||||
if rawPrefix == "/" { rawPrefix = "" }
|
||||
if rawPrefix != "" {
|
||||
if !strings.HasPrefix(rawPrefix, "/") { rawPrefix = "/" + rawPrefix }
|
||||
rawPrefix = strings.TrimRight(rawPrefix, "/")
|
||||
}
|
||||
config.URLPrefix = rawPrefix
|
||||
|
||||
// Load MD_NOTES_APP section
|
||||
notesSection := cfg.Section("MD_NOTES_APP")
|
||||
@@ -167,15 +189,23 @@ func Load() (*Config, error) {
|
||||
config.ImageStoragePath = notesSection.Key("IMAGE_STORAGE_PATH").String()
|
||||
config.ImageSubfolderName = notesSection.Key("IMAGE_SUBFOLDER_NAME").String()
|
||||
|
||||
// Convert relative paths to absolute
|
||||
// Convert relative paths to be next to the executable
|
||||
if !filepath.IsAbs(config.NotesDir) {
|
||||
wd, _ := os.Getwd()
|
||||
config.NotesDir = filepath.Join(wd, config.NotesDir)
|
||||
config.NotesDir = filepath.Join(baseDir, config.NotesDir)
|
||||
}
|
||||
|
||||
if !filepath.IsAbs(config.ImageStoragePath) && config.ImageStorageMode == 2 {
|
||||
wd, _ := os.Getwd()
|
||||
config.ImageStoragePath = filepath.Join(wd, config.ImageStoragePath)
|
||||
config.ImageStoragePath = filepath.Join(baseDir, config.ImageStoragePath)
|
||||
}
|
||||
|
||||
// Ensure these directories exist
|
||||
if err := os.MkdirAll(config.NotesDir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create notes directory: %w", err)
|
||||
}
|
||||
if config.ImageStorageMode == 2 {
|
||||
if err := os.MkdirAll(config.ImageStoragePath, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create image storage directory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Load DATABASE section
|
||||
@@ -184,8 +214,7 @@ func Load() (*Config, error) {
|
||||
config.DBPath = dbSection.Key("PATH").String()
|
||||
if config.DBType == "sqlite" {
|
||||
if !filepath.IsAbs(config.DBPath) {
|
||||
wd, _ := os.Getwd()
|
||||
config.DBPath = filepath.Join(wd, config.DBPath)
|
||||
config.DBPath = filepath.Join(baseDir, config.DBPath)
|
||||
}
|
||||
// ensure parent dir exists
|
||||
if err := os.MkdirAll(filepath.Dir(config.DBPath), 0o755); err != nil {
|
||||
@@ -222,6 +251,10 @@ func Load() (*Config, error) {
|
||||
func ensureConfigFile(configPath string) error {
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
// ensure parent dir exists
|
||||
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return createDefaultConfigFile(configPath)
|
||||
}
|
||||
|
||||
@@ -290,7 +323,7 @@ func parseCommaSeparated(value string) []string {
|
||||
}
|
||||
|
||||
func (c *Config) SaveSetting(section, key, value string) error {
|
||||
configPath := "settings.ini"
|
||||
configPath := filepath.Join(exeDir(), "settings.ini")
|
||||
cfg, err := ini.Load(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -317,6 +350,14 @@ func (c *Config) SaveSetting(section, key, value string) error {
|
||||
if size, err := strconv.ParseInt(value, 10, 64); err == nil {
|
||||
c.MaxContentLength = size * 1024 * 1024
|
||||
}
|
||||
case "URL_PREFIX":
|
||||
v := strings.TrimSpace(value)
|
||||
if v == "/" { v = "" }
|
||||
if v != "" {
|
||||
if !strings.HasPrefix(v, "/") { v = "/" + v }
|
||||
v = strings.TrimRight(v, "/")
|
||||
}
|
||||
c.URLPrefix = v
|
||||
}
|
||||
case "MD_NOTES_APP":
|
||||
switch key {
|
||||
|
||||
@@ -14,16 +14,25 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gobsidian/internal/utils"
|
||||
)
|
||||
|
||||
const sessionCookieName = "gobsidian_session"
|
||||
|
||||
// LoginPage renders the login form
|
||||
func (h *Handlers) LoginPage(c *gin.Context) {
|
||||
// If already authenticated, redirect to home (respect URL prefix)
|
||||
if isAuthenticated(c) {
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/")
|
||||
return
|
||||
}
|
||||
token, _ := c.Get("csrf_token")
|
||||
// propagate return_to if provided
|
||||
returnTo := c.Query("return_to")
|
||||
c.HTML(http.StatusOK, "login", gin.H{
|
||||
"app_name": h.config.AppName,
|
||||
"csrf_token": token,
|
||||
"return_to": returnTo,
|
||||
"ContentTemplate": "login_content",
|
||||
"ScriptsTemplate": "login_scripts",
|
||||
"Page": "login",
|
||||
@@ -128,7 +137,7 @@ func isAllDigits(s string) bool {
|
||||
func (h *Handlers) MFALoginPage(c *gin.Context) {
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
if _, ok := session.Values["mfa_user_id"]; !ok {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/login")
|
||||
return
|
||||
}
|
||||
token, _ := c.Get("csrf_token")
|
||||
@@ -161,7 +170,7 @@ func (h *Handlers) MFALoginVerify(c *gin.Context) {
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
uidAny, ok := session.Values["mfa_user_id"]
|
||||
if !ok {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/login")
|
||||
return
|
||||
}
|
||||
uid, _ := uidAny.(int64)
|
||||
@@ -187,15 +196,24 @@ func (h *Handlers) MFALoginVerify(c *gin.Context) {
|
||||
// success: set user_id and clear mfa_user_id
|
||||
delete(session.Values, "mfa_user_id")
|
||||
session.Values["user_id"] = uid
|
||||
// use return_to if set in session
|
||||
var dest string
|
||||
if v, ok := session.Values["return_to"].(string); ok {
|
||||
dest = sanitizeReturnTo(h.config.URLPrefix, v)
|
||||
delete(session.Values, "return_to")
|
||||
}
|
||||
_ = session.Save(c.Request, c.Writer)
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
if dest == "" {
|
||||
dest = h.config.URLPrefix + "/"
|
||||
}
|
||||
c.Redirect(http.StatusFound, dest)
|
||||
}
|
||||
|
||||
// ProfileMFASetupPage shows QR and input to verify during enrollment
|
||||
func (h *Handlers) ProfileMFASetupPage(c *gin.Context) {
|
||||
uidPtr := getUserIDPtr(c)
|
||||
if uidPtr == nil {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/login")
|
||||
return
|
||||
}
|
||||
// ensure enrollment exists, otherwise create one
|
||||
@@ -218,9 +236,16 @@ func (h *Handlers) ProfileMFASetupPage(c *gin.Context) {
|
||||
label := url.PathEscape(fmt.Sprintf("%s:%s", issuer, username))
|
||||
otpauth := fmt.Sprintf("otpauth://totp/%s?secret=%s&issuer=%s&digits=6&period=30&algorithm=SHA1", label, secret, url.QueryEscape(issuer))
|
||||
|
||||
// Render simple page (uses base.html shell)
|
||||
// Build sidebar tree for consistent UI and pass auth flags
|
||||
notesTree, _ := utils.BuildTreeStructure(h.config.NotesDir, h.config.NotesDirHideSidepane, h.config)
|
||||
c.HTML(http.StatusOK, "mfa_setup", gin.H{
|
||||
"app_name": h.config.AppName,
|
||||
"notes_tree": notesTree,
|
||||
"active_path": []string{},
|
||||
"current_note": nil,
|
||||
"breadcrumbs": utils.GenerateBreadcrumbs(""),
|
||||
"Authenticated": true,
|
||||
"IsAdmin": isAdmin(c),
|
||||
"Secret": secret,
|
||||
"OTPAuthURI": otpauth,
|
||||
"ContentTemplate": "mfa_setup_content",
|
||||
@@ -308,6 +333,7 @@ func verifyTOTP(base32Secret, code string, t time.Time) bool {
|
||||
func (h *Handlers) LoginPost(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
password := c.PostForm("password")
|
||||
returnTo := strings.TrimSpace(c.PostForm("return_to"))
|
||||
|
||||
user, err := h.authSvc.Authenticate(username, password)
|
||||
if err != nil {
|
||||
@@ -318,6 +344,7 @@ func (h *Handlers) LoginPost(c *gin.Context) {
|
||||
"app_name": h.config.AppName,
|
||||
"csrf_token": token,
|
||||
"error": err.Error(),
|
||||
"return_to": returnTo,
|
||||
"ContentTemplate": "login_content",
|
||||
"ScriptsTemplate": "login_scripts",
|
||||
"Page": "login",
|
||||
@@ -328,28 +355,30 @@ func (h *Handlers) LoginPost(c *gin.Context) {
|
||||
if user.MFASecret.Valid && user.MFASecret.String != "" {
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
session.Values["mfa_user_id"] = user.ID
|
||||
if rt := sanitizeReturnTo(h.config.URLPrefix, returnTo); rt != "" {
|
||||
session.Values["return_to"] = rt
|
||||
}
|
||||
_ = session.Save(c.Request, c.Writer)
|
||||
c.Redirect(http.StatusFound, "/editor/mfa")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/mfa")
|
||||
return
|
||||
}
|
||||
|
||||
// If admin created an enrollment for this user, force MFA setup after login
|
||||
var pending int
|
||||
if err := h.authSvc.DB.QueryRow(`SELECT 1 FROM mfa_enrollments WHERE user_id = ?`, user.ID).Scan(&pending); err == nil {
|
||||
// normal login, then redirect to setup
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
session.Values["user_id"] = user.ID
|
||||
_ = session.Save(c.Request, c.Writer)
|
||||
c.Redirect(http.StatusFound, "/editor/profile/mfa/setup")
|
||||
return
|
||||
}
|
||||
// Do NOT automatically force MFA setup just because an enrollment row exists.
|
||||
// Some deployments may leave stale enrollment rows; we only require MFA when
|
||||
// the user actually has MFA enabled (mfa_secret set) or when they explicitly
|
||||
// navigate to setup from profile.
|
||||
|
||||
// Create normal session
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
session.Values["user_id"] = user.ID
|
||||
_ = session.Save(c.Request, c.Writer)
|
||||
|
||||
c.Redirect(http.StatusFound, "/")
|
||||
// Redirect to requested page if provided and safe; otherwise home
|
||||
if rt := sanitizeReturnTo(h.config.URLPrefix, returnTo); rt != "" {
|
||||
c.Redirect(http.StatusFound, rt)
|
||||
} else {
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/")
|
||||
}
|
||||
}
|
||||
|
||||
// LogoutPost clears the session
|
||||
@@ -357,5 +386,36 @@ func (h *Handlers) LogoutPost(c *gin.Context) {
|
||||
session, _ := h.store.Get(c.Request, sessionCookieName)
|
||||
session.Options.MaxAge = -1
|
||||
_ = session.Save(c.Request, c.Writer)
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/login")
|
||||
}
|
||||
|
||||
// sanitizeReturnTo ensures the provided return_to is a safe in-app path.
|
||||
// It rejects absolute URLs and protocol-relative URLs. When URLPrefix is set,
|
||||
// it enforces that the destination stays within that prefix; if a bare
|
||||
// "/..." path is provided, it will be rewritten to include the prefix.
|
||||
func sanitizeReturnTo(prefix, v string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
return ""
|
||||
}
|
||||
// Disallow absolute and protocol-relative URLs
|
||||
if strings.HasPrefix(v, "//") {
|
||||
return ""
|
||||
}
|
||||
if u, err := url.Parse(v); err != nil || (u != nil && u.IsAbs()) {
|
||||
return ""
|
||||
}
|
||||
// Must be a path
|
||||
if !strings.HasPrefix(v, "/") {
|
||||
v = "/" + v
|
||||
}
|
||||
// Enforce prefix containment when configured
|
||||
if prefix != "" {
|
||||
if strings.HasPrefix(v, prefix+"/") || v == prefix || v == prefix+"/" {
|
||||
return v
|
||||
}
|
||||
// If it's a root-relative path without prefix, rewrite into prefix
|
||||
return prefix + v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
@@ -142,9 +142,9 @@ func (h *Handlers) CreateNoteHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Redirect based on extension
|
||||
redirect := "/note/" + notePath
|
||||
redirect := h.config.URLPrefix + "/note/" + notePath
|
||||
if strings.ToLower(ext) != "md" {
|
||||
redirect = "/view_text/" + notePath
|
||||
redirect = h.config.URLPrefix + "/view_text/" + notePath
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -297,7 +297,7 @@ func (h *Handlers) EditNoteHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Note saved successfully",
|
||||
"redirect": "/note/" + notePath,
|
||||
"redirect": h.config.URLPrefix + "/note/" + notePath,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -344,7 +344,7 @@ func (h *Handlers) ProfilePage(c *gin.Context) {
|
||||
// Must be authenticated; middleware ensures user_id is set
|
||||
uidPtr := getUserIDPtr(c)
|
||||
if uidPtr == nil {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
c.Redirect(http.StatusFound, h.config.URLPrefix+"/editor/login")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -477,7 +477,7 @@ func (h *Handlers) PostProfileEnableMFA(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "setup": true, "redirect": "/editor/profile/mfa/setup"})
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "setup": true, "redirect": h.config.URLPrefix+"/editor/profile/mfa/setup"})
|
||||
}
|
||||
|
||||
// PostProfileDisableMFA clears the user's MFA secret
|
||||
@@ -611,16 +611,18 @@ func (h *Handlers) AdminEnableUserMFA(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
||||
return
|
||||
}
|
||||
// Create or replace an enrollment so user is prompted on next login
|
||||
// Admin enable: set a new secret directly so MFA is immediately enabled
|
||||
secret, err := generateBase32Secret()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate secret"})
|
||||
return
|
||||
}
|
||||
if _, err := h.authSvc.DB.Exec(`INSERT OR REPLACE INTO mfa_enrollments (user_id, secret) VALUES (?, ?)`, id, secret); err != nil {
|
||||
if _, err := h.authSvc.DB.Exec(`UPDATE users SET mfa_secret = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, secret, id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// Remove any pending enrollment rows
|
||||
_, _ = h.authSvc.DB.Exec(`DELETE FROM mfa_enrollments WHERE user_id = ?`, id)
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
@@ -890,7 +892,7 @@ func (h *Handlers) PostEditTextHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "redirect": "/view_text/" + filePath})
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "redirect": h.config.URLPrefix + "/view_text/" + filePath})
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, store *sessions.CookieStore, authSvc *auth.Service) *Handlers {
|
||||
|
||||
@@ -30,10 +30,9 @@ func (h *Handlers) SettingsPageHandler(c *gin.Context) {
|
||||
"notes_tree": notesTree,
|
||||
"active_path": []string{},
|
||||
"current_note": nil,
|
||||
"breadcrumbs": []gin.H{
|
||||
{"name": "/", "url": "/"},
|
||||
{"name": "Settings", "url": ""},
|
||||
},
|
||||
"breadcrumbs": utils.GenerateBreadcrumbs(""),
|
||||
"Authenticated": isAuthenticated(c),
|
||||
"IsAdmin": isAdmin(c),
|
||||
"ContentTemplate": "settings_content",
|
||||
"ScriptsTemplate": "settings_scripts",
|
||||
"Page": "settings",
|
||||
|
||||
@@ -100,6 +100,11 @@ func (r *Renderer) processObsidianImages(content string, notePath string) string
|
||||
imageURL = fmt.Sprintf("/serve_attached_image/%s", cleanPath)
|
||||
}
|
||||
|
||||
// Prefix with configured URL base
|
||||
if bp := r.config.URLPrefix; bp != "" {
|
||||
imageURL = bp + imageURL
|
||||
}
|
||||
|
||||
// Convert to standard markdown image syntax
|
||||
alt := filepath.Base(imagePath)
|
||||
return fmt.Sprintf("", alt, imageURL)
|
||||
@@ -127,6 +132,9 @@ func (r *Renderer) processObsidianLinks(content string) string {
|
||||
// Convert note name to URL-friendly format
|
||||
noteURL := strings.ReplaceAll(noteName, " ", "%20")
|
||||
noteURL = fmt.Sprintf("/note/%s.md", noteURL)
|
||||
if bp := r.config.URLPrefix; bp != "" {
|
||||
noteURL = bp + noteURL
|
||||
}
|
||||
|
||||
// Convert to standard markdown link syntax
|
||||
return fmt.Sprintf("[%s](%s)", displayText, noteURL)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -84,7 +85,17 @@ func (s *Server) CSRFRequire() gin.HandlerFunc {
|
||||
func (s *Server) RequireAuth() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if _, exists := c.Get("user_id"); !exists {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
// Attach return_to so user can be redirected back after login
|
||||
requested := c.Request.URL.RequestURI()
|
||||
q := url.Values{}
|
||||
if requested != "" {
|
||||
q.Set("return_to", requested)
|
||||
}
|
||||
loginURL := s.config.URLPrefix + "/editor/login"
|
||||
if qs := q.Encode(); qs != "" {
|
||||
loginURL = loginURL + "?" + qs
|
||||
}
|
||||
c.Redirect(http.StatusFound, loginURL)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
@@ -96,7 +107,16 @@ func (s *Server) RequireAuth() gin.HandlerFunc {
|
||||
func (s *Server) RequireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if _, exists := c.Get("user_id"); !exists {
|
||||
c.Redirect(http.StatusFound, "/editor/login")
|
||||
requested := c.Request.URL.RequestURI()
|
||||
q := url.Values{}
|
||||
if requested != "" {
|
||||
q.Set("return_to", requested)
|
||||
}
|
||||
loginURL := s.config.URLPrefix + "/editor/login"
|
||||
if qs := q.Encode(); qs != "" {
|
||||
loginURL = loginURL + "?" + qs
|
||||
}
|
||||
c.Redirect(http.StatusFound, loginURL)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/sessions"
|
||||
|
||||
webassets "gobsidian/web"
|
||||
"gobsidian/internal/auth"
|
||||
"gobsidian/internal/config"
|
||||
"gobsidian/internal/handlers"
|
||||
@@ -82,28 +85,30 @@ func (s *Server) Start() error {
|
||||
|
||||
func (s *Server) setupRoutes() {
|
||||
h := handlers.New(s.config, s.store, s.auth)
|
||||
// Group all routes under optional URL prefix
|
||||
r := s.router.Group(s.config.URLPrefix)
|
||||
|
||||
// Main routes
|
||||
s.router.GET("/", h.IndexHandler)
|
||||
s.router.GET("/folder/*path", h.FolderHandler)
|
||||
s.router.GET("/note/*path", h.NoteHandler)
|
||||
r.GET("/", h.IndexHandler)
|
||||
r.GET("/folder/*path", h.FolderHandler)
|
||||
r.GET("/note/*path", h.NoteHandler)
|
||||
|
||||
// File serving routes
|
||||
s.router.GET("/serve_attached_image/*path", h.ServeAttachedImageHandler)
|
||||
s.router.GET("/serve_stored_image/:filename", h.ServeStoredImageHandler)
|
||||
s.router.GET("/download/*path", h.DownloadHandler)
|
||||
s.router.GET("/view_text/*path", h.ViewTextHandler)
|
||||
r.GET("/serve_attached_image/*path", h.ServeAttachedImageHandler)
|
||||
r.GET("/serve_stored_image/:filename", h.ServeStoredImageHandler)
|
||||
r.GET("/download/*path", h.DownloadHandler)
|
||||
r.GET("/view_text/*path", h.ViewTextHandler)
|
||||
|
||||
// Auth routes
|
||||
s.router.GET("/editor/login", h.LoginPage)
|
||||
s.router.POST("/editor/login", s.CSRFRequire(), h.LoginPost)
|
||||
s.router.POST("/editor/logout", s.RequireAuth(), s.CSRFRequire(), h.LogoutPost)
|
||||
r.GET("/editor/login", h.LoginPage)
|
||||
r.POST("/editor/login", s.CSRFRequire(), h.LoginPost)
|
||||
r.POST("/editor/logout", s.RequireAuth(), s.CSRFRequire(), h.LogoutPost)
|
||||
// MFA challenge routes (no auth yet, but CSRF)
|
||||
s.router.GET("/editor/mfa", s.CSRFRequire(), h.MFALoginPage)
|
||||
s.router.POST("/editor/mfa", s.CSRFRequire(), h.MFALoginVerify)
|
||||
r.GET("/editor/mfa", s.CSRFRequire(), h.MFALoginPage)
|
||||
r.POST("/editor/mfa", s.CSRFRequire(), h.MFALoginVerify)
|
||||
|
||||
// New /editor group protected by auth + CSRF
|
||||
editor := s.router.Group("/editor", s.RequireAuth(), s.CSRFRequire())
|
||||
editor := r.Group("/editor", s.RequireAuth(), s.CSRFRequire())
|
||||
{
|
||||
editor.GET("/create", h.CreateNotePageHandler)
|
||||
editor.POST("/create", h.CreateNoteHandler)
|
||||
@@ -168,13 +173,19 @@ func (s *Server) setupRoutes() {
|
||||
}
|
||||
|
||||
// API routes
|
||||
s.router.GET("/api/tree", h.TreeAPIHandler)
|
||||
s.router.GET("/api/search", h.SearchHandler)
|
||||
r.GET("/api/tree", h.TreeAPIHandler)
|
||||
r.GET("/api/search", h.SearchHandler)
|
||||
}
|
||||
|
||||
func (s *Server) setupStaticFiles() {
|
||||
s.router.Static("/static", "./web/static")
|
||||
s.router.StaticFile("/favicon.ico", "./web/static/favicon.ico")
|
||||
// Serve /static from embedded web/static
|
||||
sub, err := fs.Sub(webassets.StaticFS, "static")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
s.router.StaticFS(s.config.URLPrefix+"/static", http.FS(sub))
|
||||
// Favicon from same sub FS
|
||||
s.router.StaticFileFS(s.config.URLPrefix+"/favicon.ico", "favicon.ico", http.FS(sub))
|
||||
}
|
||||
|
||||
func (s *Server) setupTemplates() {
|
||||
@@ -183,6 +194,24 @@ func (s *Server) setupTemplates() {
|
||||
"formatSize": utils.FormatFileSize,
|
||||
"formatTime": utils.FormatTime,
|
||||
"join": strings.Join,
|
||||
// base returns the configured URL prefix ("" for root)
|
||||
"base": func() string { return s.config.URLPrefix },
|
||||
// url joins the base with the given path ensuring single slash
|
||||
"url": func(p string) string {
|
||||
bp := s.config.URLPrefix
|
||||
if bp == "" {
|
||||
if p == "" { return "" }
|
||||
if strings.HasPrefix(p, "/") { return p }
|
||||
return "/" + p
|
||||
}
|
||||
if p == "" || p == "/" {
|
||||
return bp + "/"
|
||||
}
|
||||
if strings.HasPrefix(p, "/") {
|
||||
return bp + p
|
||||
}
|
||||
return bp + "/" + p
|
||||
},
|
||||
"contains": func(slice []string, item string) bool {
|
||||
for _, s := range slice {
|
||||
if s == item {
|
||||
@@ -244,8 +273,12 @@ func (s *Server) setupTemplates() {
|
||||
},
|
||||
}
|
||||
|
||||
// Load templates - make sure base.html is loaded with all the other templates
|
||||
templates := template.Must(template.New("").Funcs(funcMap).ParseGlob("web/templates/*.html"))
|
||||
// Load templates from embedded FS
|
||||
tplFS, err := fs.Sub(webassets.TemplatesFS, "templates")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
templates := template.Must(template.New("").Funcs(funcMap).ParseFS(tplFS, "*.html"))
|
||||
s.router.SetHTMLTemplate(templates)
|
||||
|
||||
fmt.Printf("DEBUG: Templates loaded successfully\n")
|
||||
@@ -253,10 +286,10 @@ func (s *Server) setupTemplates() {
|
||||
|
||||
// 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')`)
|
||||
}
|
||||
// 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')`)
|
||||
}
|
||||
}
|
||||
|
||||
11
web/assets_embed.go
Normal file
11
web/assets_embed.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package webassets
|
||||
|
||||
import "embed"
|
||||
|
||||
// TemplatesFS embeds all HTML templates under web/templates.
|
||||
//go:embed templates/*.html
|
||||
var TemplatesFS embed.FS
|
||||
|
||||
// StaticFS embeds all static assets under web/static.
|
||||
//go:embed static/*
|
||||
var StaticFS embed.FS
|
||||
@@ -64,9 +64,11 @@ function initEnhancedUpload() {
|
||||
|
||||
// Enhanced upload function with progress tracking
|
||||
function uploadFilesWithProgress(files) {
|
||||
const folderPath = window.location.pathname.includes('/folder/')
|
||||
? window.location.pathname.replace('/folder/', '')
|
||||
: '';
|
||||
// Derive folder path accounting for BASE prefix
|
||||
const base = (window.BASE || '').replace(/\/$/, '');
|
||||
let path = window.location.pathname || '';
|
||||
if (base && path.startsWith(base)) path = path.slice(base.length);
|
||||
const folderPath = path.startsWith('/folder/') ? path.replace('/folder/', '') : '';
|
||||
|
||||
uploadElements.progress.classList.remove('hidden');
|
||||
uploadElements.progressBar.style.width = '0%';
|
||||
@@ -117,7 +119,7 @@ function initEnhancedUpload() {
|
||||
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
xhr.open('POST', '/editor/upload');
|
||||
xhr.open('POST', window.prefix('/editor/upload'));
|
||||
if (csrf) {
|
||||
try { xhr.setRequestHeader('X-CSRF-Token', csrf); } catch (_) {}
|
||||
}
|
||||
@@ -210,13 +212,13 @@ function initKeyboardShortcuts() {
|
||||
case 'n':
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
e.preventDefault();
|
||||
window.location.href = '/editor/create';
|
||||
window.location.href = window.prefix('/editor/create');
|
||||
}
|
||||
break;
|
||||
case 's':
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
e.preventDefault();
|
||||
window.location.href = '/editor/settings';
|
||||
window.location.href = window.prefix('/editor/settings');
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@
|
||||
formCreateUser.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(formCreateUser);
|
||||
const res = await fetch('/editor/admin/users', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const res = await fetch(window.prefix('/editor/admin/users'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('User created', 'success'); window.location.reload(); }
|
||||
else { showNotification('Create user failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -200,7 +200,7 @@
|
||||
if (!id) return;
|
||||
if (username === 'admin') { showNotification('Cannot delete default admin user', 'error'); return; }
|
||||
if (!confirm('Delete user ' + username + ' ?')) return;
|
||||
const res = await fetch('/editor/admin/users/' + encodeURIComponent(id), { method: 'DELETE', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const res = await fetch(window.prefix('/editor/admin/users/' + encodeURIComponent(id)), { method: 'DELETE', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('User deleted', 'success'); window.location.reload(); }
|
||||
else { showNotification('Delete user failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -216,7 +216,7 @@
|
||||
const active = action === 'user-activate' ? '1' : '0';
|
||||
const fd = new FormData();
|
||||
fd.set('active', active);
|
||||
const res = await fetch('/editor/admin/users/' + encodeURIComponent(id) + '/active', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const res = await fetch(window.prefix('/editor/admin/users/' + encodeURIComponent(id) + '/active'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('User status updated', 'success'); window.location.reload(); }
|
||||
else { showNotification('Update status failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -226,7 +226,7 @@
|
||||
// MFA actions
|
||||
const mfaRequest = async (row, path, okMsg) => {
|
||||
const id = row && row.getAttribute('data-user-id');
|
||||
const res = await fetch('/editor/admin/users/' + encodeURIComponent(id) + path, { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const res = await fetch(window.prefix('/editor/admin/users/' + encodeURIComponent(id) + path), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification(okMsg, 'success'); window.location.reload(); }
|
||||
else { showNotification('MFA action failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -241,7 +241,7 @@
|
||||
formCreateGroup.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(formCreateGroup);
|
||||
const res = await fetch('/editor/admin/groups', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const res = await fetch(window.prefix('/editor/admin/groups'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('Group created', 'success'); window.location.reload(); }
|
||||
else { showNotification('Create group failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -257,7 +257,7 @@
|
||||
if (!id) return;
|
||||
if (name === 'admin' || name === 'public') { showNotification('Cannot delete core group: ' + name, 'error'); return; }
|
||||
if (!confirm('Delete group ' + name + ' ?')) return;
|
||||
const res = await fetch('/editor/admin/groups/' + encodeURIComponent(id), { method: 'DELETE', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const res = await fetch(window.prefix('/editor/admin/groups/' + encodeURIComponent(id)), { method: 'DELETE', headers: { 'X-CSRF-Token': getCSRF() } });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('Group deleted', 'success'); window.location.reload(); }
|
||||
else { showNotification('Delete group failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -270,7 +270,7 @@
|
||||
formAddMem.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(formAddMem);
|
||||
const res = await fetch('/editor/admin/memberships/add', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const res = await fetch(window.prefix('/editor/admin/memberships/add'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('User added to group', 'success'); }
|
||||
else { showNotification('Add membership failed: ' + (data.error || res.statusText), 'error'); }
|
||||
@@ -283,7 +283,7 @@
|
||||
formRemMem.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(formRemMem);
|
||||
const res = await fetch('/editor/admin/memberships/remove', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const res = await fetch(window.prefix('/editor/admin/memberships/remove'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) { showNotification('User removed from group', 'success'); }
|
||||
else { showNotification('Remove membership failed: ' + (data.error || res.statusText), 'error'); }
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
<h1 class="text-3xl font-bold text-white">Admin Logs</h1>
|
||||
<p class="text-gray-400">Recent access, errors, failed logins, and IP bans</p>
|
||||
</div>
|
||||
<a href="/editor/admin" class="btn-secondary">Back to Admin</a>
|
||||
<a href="{{url "/editor/admin"}}" class="btn-secondary">Back to Admin</a>
|
||||
</div>
|
||||
|
||||
<!-- Filters -->
|
||||
<form method="GET" action="/editor/admin/logs" class="mb-6 bg-slate-800 border border-slate-700 rounded-lg p-4">
|
||||
<form method="GET" action="{{url "/editor/admin/logs"}}" class="mb-6 bg-slate-800 border border-slate-700 rounded-lg p-4">
|
||||
<div class="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
|
||||
<div>
|
||||
<label class="block text-sm text-gray-300 mb-1">IP contains</label>
|
||||
@@ -38,7 +38,7 @@
|
||||
</div>
|
||||
<div class="flex space-x-2">
|
||||
<button type="submit" class="btn-primary">Apply</button>
|
||||
<a href="/editor/admin/logs" class="btn-secondary">Reset</a>
|
||||
<a href="{{url "/editor/admin/logs"}}" class="btn-secondary">Reset</a>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -249,7 +249,7 @@ async function postForm(url, data) {
|
||||
const csrf = getCSRF();
|
||||
const form = new URLSearchParams();
|
||||
Object.entries(data || {}).forEach(([k, v]) => form.append(k, v));
|
||||
const res = await fetch(url, { method: 'POST', headers: Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, csrf ? {'X-CSRF-Token': csrf} : {}), body: form.toString() });
|
||||
const res = await fetch(window.prefix(url), { method: 'POST', headers: Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, csrf ? {'X-CSRF-Token': csrf} : {}), body: form.toString() });
|
||||
if (!res.ok) {
|
||||
const j = await res.json().catch(() => ({}));
|
||||
throw new Error(j.error || res.statusText);
|
||||
|
||||
@@ -264,7 +264,7 @@
|
||||
<!-- Header -->
|
||||
<div class="p-4 border-b border-gray-700">
|
||||
<div class="flex items-center justify-between">
|
||||
<a href="/" class="sidebar-title text-xl font-bold text-white hover:text-blue-300" title="Home">
|
||||
<a href="{{url "/"}}" class="sidebar-title text-xl font-bold text-white hover:text-blue-300" title="Home">
|
||||
{{.app_name}}
|
||||
</a>
|
||||
<div class="flex items-center space-x-2 items-center">
|
||||
@@ -274,14 +274,14 @@
|
||||
</button>
|
||||
{{if .Authenticated}}
|
||||
{{if .IsAdmin}}
|
||||
<a href="/editor/admin" class="text-gray-400 hover:text-white transition-colors" title="Admin">
|
||||
<a href="{{url "/editor/admin"}}" class="text-gray-400 hover:text-white transition-colors" title="Admin">
|
||||
<i class="fas fa-user-shield"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
<a href="/editor/profile" class="text-gray-400 hover:text-white transition-colors" title="Profile">
|
||||
<a href="{{url "/editor/profile"}}" class="text-gray-400 hover:text-white transition-colors" title="Profile">
|
||||
<i class="fas fa-user"></i>
|
||||
</a>
|
||||
<a href="/editor/settings" class="text-gray-400 hover:text-white transition-colors" title="Settings">
|
||||
<a href="{{url "/editor/settings"}}" class="text-gray-400 hover:text-white transition-colors" title="Settings">
|
||||
<i class="fas fa-gear"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
@@ -290,7 +290,7 @@
|
||||
<i class="fas fa-right-from-bracket"></i>
|
||||
</button>
|
||||
{{else}}
|
||||
<a href="/editor/login" class="text-gray-400 hover:text-white transition-colors" title="Login">
|
||||
<a href="{{url "/editor/login"}}" class="text-gray-400 hover:text-white transition-colors" title="Login">
|
||||
<i class="fas fa-right-to-bracket"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
@@ -305,7 +305,7 @@
|
||||
<!-- Navigation -->
|
||||
<div class="sidebar-content px-4 py-4">
|
||||
{{if .Authenticated}}
|
||||
<a href="/editor/create" class="btn-primary text-sm w-full text-center">
|
||||
<a href="{{url "/editor/create"}}" class="btn-primary text-sm w-full text-center">
|
||||
<i class="fas fa-plus mr-2"></i>New Note
|
||||
</a>
|
||||
{{end}}
|
||||
@@ -328,13 +328,18 @@
|
||||
<!-- Breadcrumbs -->
|
||||
{{if .breadcrumbs}}
|
||||
<div class="bg-slate-800 border-b border-gray-700 px-6 py-3">
|
||||
<nav class="flex items-center space-x-2 text-sm">
|
||||
<nav class="flex items-center flex-wrap gap-1.5 text-sm">
|
||||
{{range $i, $crumb := .breadcrumbs}}
|
||||
{{if $i}}<i class="fas fa-chevron-right text-gray-500 text-xs"></i>{{end}}
|
||||
{{if $i}}<i class="fas fa-chevron-right text-gray-500 text-xs mx-1"></i>{{end}}
|
||||
{{if $crumb.URL}}
|
||||
<a href="{{$crumb.URL}}" class="text-blue-400 hover:text-blue-300 transition-colors">{{$crumb.Name}}</a>
|
||||
<a href="{{url $crumb.URL}}" class="inline-flex items-center px-2.5 py-1 rounded-md border border-slate-600 bg-slate-700/40 text-blue-300 hover:bg-slate-700 hover:text-blue-200 transition-colors" aria-label="Breadcrumb: {{$crumb.Name}}">
|
||||
{{if and (eq $i 0) (eq $crumb.Name "/")}}<i class="fas fa-folder-tree mr-1.5"></i>{{end}}
|
||||
<span class="leading-none">{{$crumb.Name}}</span>
|
||||
</a>
|
||||
{{else}}
|
||||
<span class="text-gray-300">{{$crumb.Name}}</span>
|
||||
<span class="inline-flex items-center px-2.5 py-1 rounded-md border border-slate-600 bg-slate-700/60 text-gray-200">
|
||||
<span class="leading-none">{{$crumb.Name}}</span>
|
||||
</span>
|
||||
{{end}}
|
||||
{{end}}
|
||||
</nav>
|
||||
@@ -401,6 +406,18 @@
|
||||
// Initialize syntax highlighting
|
||||
hljs.highlightAll();
|
||||
|
||||
// Base URL prefix from server
|
||||
window.BASE = '{{base}}';
|
||||
window.prefix = function(p) {
|
||||
var b = window.BASE || '';
|
||||
if (!b) {
|
||||
if (!p) return '';
|
||||
return p[0] === '/' ? p : '/' + p;
|
||||
}
|
||||
if (!p || p === '/') return b + '/';
|
||||
return p[0] === '/' ? (b + p) : (b + '/' + p);
|
||||
};
|
||||
|
||||
// Tree functionality
|
||||
document.addEventListener('click', function(e) {
|
||||
if (e.target.closest('.tree-toggle')) {
|
||||
@@ -423,7 +440,7 @@
|
||||
if (!toggle) return;
|
||||
e.preventDefault();
|
||||
const path = toggle.getAttribute('data-path') || '';
|
||||
const url = '/folder/' + path;
|
||||
const url = window.prefix('/folder/' + path);
|
||||
window.location.href = url;
|
||||
});
|
||||
|
||||
@@ -522,7 +539,7 @@
|
||||
if (hasTree) return; // already populated
|
||||
|
||||
// Fetch tree
|
||||
fetch('/api/tree')
|
||||
fetch(window.prefix('/api/tree'))
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (!data || !Array.isArray(data.children)) return;
|
||||
@@ -554,13 +571,13 @@
|
||||
wrapper.appendChild(toggle);
|
||||
wrapper.appendChild(children);
|
||||
} else {
|
||||
let href = '/view_text/' + (node.path || '');
|
||||
let href = window.prefix('/view_text/' + (node.path || ''));
|
||||
let icon = '📄';
|
||||
if ((node.type || '').toLowerCase() === 'md') {
|
||||
href = '/note/' + (node.path || '');
|
||||
href = window.prefix('/note/' + (node.path || ''));
|
||||
icon = '📝';
|
||||
} else if ((node.type || '').toLowerCase() === 'image') {
|
||||
href = '/serve_attached_image/' + (node.path || '');
|
||||
href = window.prefix('/serve_attached_image/' + (node.path || ''));
|
||||
icon = '🖼️';
|
||||
}
|
||||
const a = document.createElement('a');
|
||||
@@ -636,7 +653,7 @@
|
||||
title.className = 'flex items-center justify-between text-sm text-blue-300 hover:text-blue-200 cursor-pointer';
|
||||
title.innerHTML = `<span><i class="fas ${r.type === 'md' ? 'fa-file-lines' : 'fa-file'} mr-2"></i>${escapeHTML(r.path)}</span>`;
|
||||
title.addEventListener('click', () => {
|
||||
const url = r.path.endsWith('.md') ? `/note/${r.path}` : `/view_text/${r.path}`;
|
||||
const url = r.path.endsWith('.md') ? window.prefix(`/note/${r.path}`) : window.prefix(`/view_text/${r.path}`);
|
||||
// remember query
|
||||
if (searchInput) localStorage.setItem(LS_KEY_QUERY, searchInput.value.trim());
|
||||
window.location.href = url;
|
||||
@@ -661,7 +678,7 @@
|
||||
}
|
||||
try {
|
||||
searchStatus.textContent = 'Searching...';
|
||||
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
|
||||
const res = await fetch(window.prefix(`/api/search?q=${encodeURIComponent(query)}`));
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
localStorage.setItem(LS_KEY_QUERY, query);
|
||||
@@ -696,12 +713,12 @@
|
||||
try {
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
const res = await fetch('/editor/logout', {
|
||||
const res = await fetch(window.prefix('/editor/logout'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
});
|
||||
if (res.ok) {
|
||||
window.location.href = '/editor/login';
|
||||
window.location.href = window.prefix('/editor/login');
|
||||
} else {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
showNotification('Logout failed: ' + (data.error || res.statusText), 'error');
|
||||
@@ -762,17 +779,17 @@
|
||||
</div>
|
||||
{{else}}
|
||||
{{if eq .node.Type "md"}}
|
||||
<a href="/note/{{.node.Path}}" class="sidebar-item {{if eq .current_note .node.Path}}active{{end}}">
|
||||
<a href="{{url (print "/note/" .node.Path)}}" class="sidebar-item {{if eq .current_note .node.Path}}active{{end}}">
|
||||
<span class="mr-2">📝</span>
|
||||
<span>{{.node.Name}}</span>
|
||||
</a>
|
||||
{{else if eq .node.Type "image"}}
|
||||
<a href="/serve_attached_image/{{.node.Path}}" target="_blank" class="sidebar-item" title="View image in new tab">
|
||||
<a href="{{url (print "/serve_attached_image/" .node.Path)}}" target="_blank" class="sidebar-item" title="View image in new tab">
|
||||
<span class="mr-2">🖼️</span>
|
||||
<span>{{.node.Name}}</span>
|
||||
</a>
|
||||
{{else}}
|
||||
<a href="/view_text/{{.node.Path}}" class="sidebar-item">
|
||||
<a href="{{url (print "/view_text/" .node.Path)}}" class="sidebar-item">
|
||||
<span class="mr-2">📄</span>
|
||||
<span>{{.node.Name}}</span>
|
||||
</a>
|
||||
|
||||
@@ -111,7 +111,7 @@ console.log('Hello, World!');
|
||||
|
||||
function buildImageURL(filename) {
|
||||
if (imageStorageMode === 2) {
|
||||
return `/serve_stored_image/${filename}`;
|
||||
return window.prefix(`/serve_stored_image/${filename}`);
|
||||
}
|
||||
let path = filename;
|
||||
if (imageStorageMode === 3 && currentFolderPath) {
|
||||
@@ -119,7 +119,7 @@ console.log('Hello, World!');
|
||||
} else if (imageStorageMode === 4 && currentFolderPath) {
|
||||
path = `${currentFolderPath}/${imageSubfolderName}/${filename}`;
|
||||
}
|
||||
return `/serve_attached_image/${path}`;
|
||||
return window.prefix(`/serve_attached_image/${path}`);
|
||||
}
|
||||
|
||||
function transformObsidianEmbeds(md) {
|
||||
@@ -177,7 +177,7 @@ console.log('Hello, World!');
|
||||
// CSRF token from cookie
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/create', {
|
||||
fetch(window.prefix('/editor/create'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -263,7 +263,12 @@ console.log('Hello, World!');
|
||||
formData.append('path', uploadPath);
|
||||
|
||||
try {
|
||||
const resp = await fetch('/upload', { method: 'POST', body: formData });
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
const resp = await fetch(window.prefix('/editor/upload'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || !data.success) throw new Error(data.error || 'Upload failed');
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
{{if .folder_path}}
|
||||
<p class="text-gray-400">
|
||||
<i class="fas fa-folder mr-2"></i>
|
||||
<a href="/folder/{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
<a href="{{url "/folder/"}}{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
</p>
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -104,7 +104,7 @@
|
||||
function buildImageURL(filename) {
|
||||
// Map Obsidian embed to server URL
|
||||
if (imageStorageMode === 2) {
|
||||
return `/serve_stored_image/${filename}`;
|
||||
return window.prefix(`/serve_stored_image/${filename}`);
|
||||
}
|
||||
let path = filename;
|
||||
if (imageStorageMode === 3 && currentFolderPath) {
|
||||
@@ -112,7 +112,7 @@
|
||||
} else if (imageStorageMode === 4 && currentFolderPath) {
|
||||
path = `${currentFolderPath}/${imageSubfolderName}/${filename}`;
|
||||
}
|
||||
return `/serve_attached_image/${path}`;
|
||||
return window.prefix(`/serve_attached_image/${path}`);
|
||||
}
|
||||
|
||||
function transformObsidianEmbeds(md) {
|
||||
@@ -161,7 +161,7 @@
|
||||
// CSRF token from cookie
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/edit/' + notePath, {
|
||||
fetch(window.prefix('/editor/edit/' + notePath), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -300,7 +300,12 @@
|
||||
formData.append('path', uploadPath);
|
||||
|
||||
try {
|
||||
const resp = await fetch('/upload', { method: 'POST', body: formData });
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
const resp = await fetch(window.prefix('/editor/upload'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || !data.success) throw new Error(data.error || 'Upload failed');
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
{{if .folder_path}}
|
||||
<p class="text-gray-400">
|
||||
<i class="fas fa-folder mr-2"></i>
|
||||
<a href="/folder/{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
<a href="{{url "/folder/"}}{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
</p>
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -171,7 +171,7 @@
|
||||
formData.append('content', cm ? cm.getValue() : contentEl.value);
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
fetch('/editor/edit_text/' + filePath, { method: 'POST', headers: csrf ? { 'X-CSRF-Token': csrf } : {}, body: formData })
|
||||
fetch(window.prefix('/editor/edit_text/' + filePath), { method: 'POST', headers: csrf ? { 'X-CSRF-Token': csrf } : {}, body: formData })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
{{end}}
|
||||
|
||||
<div class="space-y-3">
|
||||
<a href="/" class="block btn-primary">
|
||||
<a href="{{url "/"}}" class="block btn-primary">
|
||||
<i class="fas fa-home mr-2"></i>Go Home
|
||||
</a>
|
||||
<button onclick="history.back()" class="block btn-secondary w-full">
|
||||
|
||||
@@ -22,14 +22,16 @@
|
||||
{{end}}
|
||||
</p>
|
||||
</div>
|
||||
{{if .Authenticated}}
|
||||
<div class="flex items-center space-x-3">
|
||||
<button id="upload-btn" class="btn-primary">
|
||||
<i class="fas fa-upload mr-2"></i>Upload File
|
||||
</button>
|
||||
<a href="/editor/create?folder={{.folder_path}}" class="btn-secondary">
|
||||
<a href="{{url (print "/editor/create?folder=" .folder_path)}}" class="btn-secondary">
|
||||
<i class="fas fa-plus mr-2"></i>New Note
|
||||
</a>
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<!-- Upload Area (hidden by default) -->
|
||||
@@ -69,29 +71,33 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
{{if eq .Type "md"}}
|
||||
<a href="/editor/edit/{{.Path}}" class="text-blue-400 hover:text-blue-300 p-2" title="Edit">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
{{if eq .Type "text"}}
|
||||
<a href="/editor/edit_text/{{.Path}}" class="text-blue-400 hover:text-blue-300 p-2" title="Edit">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
{{if $.Authenticated}}
|
||||
{{if eq .Type "md"}}
|
||||
<a href="{{url (print "/editor/edit/" .Path)}}" class="text-blue-400 hover:text-blue-300 p-2" title="Edit">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
{{if eq .Type "text"}}
|
||||
<a href="{{url (print "/editor/edit_text/" .Path)}}" class="text-blue-400 hover:text-blue-300 p-2" title="Edit">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{if eq .Type "image"}}
|
||||
<a href="/serve_attached_image/{{.Path}}" target="_blank" class="text-yellow-400 hover:text-yellow-300 p-2" title="View">
|
||||
<a href="{{url (print "/serve_attached_image/" .Path)}}" target="_blank" class="text-yellow-400 hover:text-yellow-300 p-2" title="View">
|
||||
<i class="fas fa-eye"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
{{if ne .Type "dir"}}
|
||||
<a href="/download/{{.Path}}" class="text-green-400 hover:text-green-300 p-2" title="Download">
|
||||
<a href="{{url (print "/download/" .Path)}}" class="text-green-400 hover:text-green-300 p-2" title="Download">
|
||||
<i class="fas fa-download"></i>
|
||||
</a>
|
||||
{{end}}
|
||||
<button class="text-red-400 hover:text-red-300 p-2 delete-btn" data-path="{{.Path}}" title="Delete">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
{{if $.Authenticated}}
|
||||
<button class="text-red-400 hover:text-red-300 p-2 delete-btn" data-path="{{.Path}}" title="Delete">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
{{end}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -132,39 +138,47 @@
|
||||
let deleteTarget = null;
|
||||
|
||||
// Toggle upload area
|
||||
uploadBtn.addEventListener('click', function() {
|
||||
uploadArea.classList.toggle('hidden');
|
||||
});
|
||||
if (uploadBtn) {
|
||||
uploadBtn.addEventListener('click', function() {
|
||||
uploadArea && uploadArea.classList.toggle('hidden');
|
||||
});
|
||||
}
|
||||
|
||||
// File selection
|
||||
selectFilesBtn.addEventListener('click', function() {
|
||||
fileInput.click();
|
||||
});
|
||||
if (selectFilesBtn && fileInput) {
|
||||
selectFilesBtn.addEventListener('click', function() {
|
||||
fileInput.click();
|
||||
});
|
||||
}
|
||||
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (this.files.length > 0) {
|
||||
uploadFiles(this.files);
|
||||
}
|
||||
});
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (this.files.length > 0) {
|
||||
uploadFiles(this.files);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Drag and drop
|
||||
uploadArea.addEventListener('dragover', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.add('dragover');
|
||||
});
|
||||
if (uploadArea) {
|
||||
uploadArea.addEventListener('dragover', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.add('dragover');
|
||||
});
|
||||
|
||||
uploadArea.addEventListener('dragleave', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.remove('dragover');
|
||||
});
|
||||
uploadArea.addEventListener('dragleave', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.remove('dragover');
|
||||
});
|
||||
|
||||
uploadArea.addEventListener('drop', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.remove('dragover');
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
uploadFiles(e.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
uploadArea.addEventListener('drop', function(e) {
|
||||
e.preventDefault();
|
||||
this.classList.remove('dragover');
|
||||
if (e.dataTransfer.files.length > 0) {
|
||||
uploadFiles(e.dataTransfer.files);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Upload files function
|
||||
function uploadFiles(files) {
|
||||
@@ -181,7 +195,7 @@
|
||||
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
fetch('/editor/upload', {
|
||||
fetch(window.prefix('/editor/upload'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -213,13 +227,13 @@
|
||||
const type = itemCard.dataset.type;
|
||||
|
||||
if (type === 'dir') {
|
||||
window.location.href = '/folder/' + path;
|
||||
window.location.href = window.prefix('/folder/' + path);
|
||||
} else if (type === 'md') {
|
||||
window.location.href = '/note/' + path;
|
||||
window.location.href = window.prefix('/note/' + path);
|
||||
} else if (type === 'image') {
|
||||
window.open('/serve_attached_image/' + path, '_blank');
|
||||
window.open(window.prefix('/serve_attached_image/' + path), '_blank');
|
||||
} else {
|
||||
window.location.href = '/view_text/' + path;
|
||||
window.location.href = window.prefix('/view_text/' + path);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -242,7 +256,7 @@
|
||||
if (deleteTarget) {
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
fetch('/editor/delete/' + deleteTarget, {
|
||||
fetch(window.prefix('/editor/delete/' + deleteTarget), {
|
||||
method: 'DELETE',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {}
|
||||
})
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
{{if .error}}
|
||||
<div class="bg-red-900/50 border border-red-700 text-red-200 rounded p-3 mb-4">{{.error}}</div>
|
||||
{{end}}
|
||||
<form method="POST" action="/editor/login" class="space-y-4">
|
||||
<form method="POST" action="{{url "/editor/login"}}" class="space-y-4">
|
||||
<input type="hidden" name="csrf_token" value="{{.csrf_token}}" />
|
||||
{{if .return_to}}
|
||||
<input type="hidden" name="return_to" value="{{.return_to}}" />
|
||||
{{end}}
|
||||
<div>
|
||||
<label class="block text-sm text-gray-300 mb-1" for="username">Username or Email</label>
|
||||
<input id="username" name="username" type="text" required class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white" />
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<div class="mb-4 p-3 rounded bg-red-700 text-white">{{.error}}</div>
|
||||
{{end}}
|
||||
|
||||
<form id="mfa-form" class="space-y-4" method="POST" action="/editor/mfa">
|
||||
<form id="mfa-form" class="space-y-4" method="POST" action="{{url "/editor/mfa"}}">
|
||||
<input type="hidden" name="csrf_token" value="{{.csrf_token}}" />
|
||||
<div>
|
||||
<label for="code" class="block text-sm font-medium text-gray-300 mb-2">Authentication code</label>
|
||||
|
||||
@@ -45,11 +45,11 @@
|
||||
const fd = new FormData(form);
|
||||
const params = new URLSearchParams(Array.from(fd.entries()));
|
||||
try {
|
||||
const res = await fetch('/editor/profile/mfa/verify', { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: params });
|
||||
const res = await fetch(window.prefix('/editor/profile/mfa/verify'), { method: 'POST', headers: { 'X-CSRF-Token': getCSRF() }, body: params });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) {
|
||||
showNotification('MFA enabled', 'success');
|
||||
window.location.href = '/editor/profile';
|
||||
window.location.href = window.prefix('/editor/profile');
|
||||
} else {
|
||||
throw new Error(data.error || res.statusText);
|
||||
}
|
||||
|
||||
@@ -10,11 +10,11 @@
|
||||
<h1 class="text-3xl font-bold text-white">{{.title}}</h1>
|
||||
<div class="flex items-center space-x-3">
|
||||
{{if .Authenticated}}
|
||||
<a href="/editor/edit/{{.note_path}}" class="btn-primary">
|
||||
<a href="{{url (print "/editor/edit/" .note_path)}}" class="btn-primary">
|
||||
<i class="fas fa-edit mr-2"></i>Edit
|
||||
</a>
|
||||
{{end}}
|
||||
<a href="/download/{{.note_path}}" class="btn-secondary">
|
||||
<a href="{{url (print "/download/" .note_path)}}" class="btn-secondary">
|
||||
<i class="fas fa-download mr-2"></i>Download
|
||||
</a>
|
||||
{{if .Authenticated}}
|
||||
@@ -28,7 +28,7 @@
|
||||
{{if .folder_path}}
|
||||
<p class="text-gray-400">
|
||||
<i class="fas fa-folder mr-2"></i>
|
||||
<a href="/folder/{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
<a href="{{url (print "/folder/" .folder_path)}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
</p>
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -79,13 +79,13 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
const path = deleteBtn.dataset.path;
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
fetch(`/editor/delete/${path}`, {
|
||||
fetch(window.prefix(`/editor/delete/${path}`), {
|
||||
method: 'DELETE',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {}
|
||||
})
|
||||
.then(response => {
|
||||
if (response.ok) {
|
||||
window.location.href = '/';
|
||||
window.location.href = window.prefix('/');
|
||||
} else {
|
||||
alert('Error deleting note');
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@
|
||||
if (emailForm) emailForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const res = await fetch('/editor/profile/email', {
|
||||
const res = await fetch(window.prefix('/editor/profile/email'), {
|
||||
method: 'POST',
|
||||
headers: Object.assign({'X-CSRF-Token': getCSRF()}),
|
||||
body: formToJSON(emailForm)
|
||||
@@ -121,7 +121,7 @@
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/editor/profile/password', {
|
||||
const res = await fetch(window.prefix('/editor/profile/password'), {
|
||||
method: 'POST',
|
||||
headers: Object.assign({'X-CSRF-Token': getCSRF()}),
|
||||
body: formToJSON(passwordForm)
|
||||
@@ -141,7 +141,7 @@
|
||||
async function toggleMFA(enable) {
|
||||
try {
|
||||
const url = enable ? '/editor/profile/mfa/enable' : '/editor/profile/mfa/disable';
|
||||
const res = await fetch(url, { method: 'POST', headers: {'X-CSRF-Token': getCSRF()} });
|
||||
const res = await fetch(window.prefix(url), { method: 'POST', headers: {'X-CSRF-Token': getCSRF()} });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok && data.success) {
|
||||
if (enable) {
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
<p class="text-gray-400">Access logs and security controls</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<a href="/editor/admin/logs" target="_blank" class="btn-secondary inline-flex items-center">
|
||||
<a href="{{url "/editor/admin/logs"}}" target="_blank" class="btn-secondary inline-flex items-center">
|
||||
<i class="fas fa-list mr-2"></i>View Logs
|
||||
</a>
|
||||
</div>
|
||||
@@ -247,7 +247,7 @@
|
||||
// Load current settings
|
||||
function loadSettings() {
|
||||
// Load image storage settings
|
||||
fetch('/editor/settings/image_storage')
|
||||
fetch(window.prefix('/editor/settings/image_storage'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.querySelector(`input[name="storage_mode"][value="${data.mode}"]`).checked = true;
|
||||
@@ -258,7 +258,7 @@
|
||||
.catch(error => console.error('Error loading image storage settings:', error));
|
||||
|
||||
// Load notes directory settings
|
||||
fetch('/editor/settings/notes_dir')
|
||||
fetch(window.prefix('/editor/settings/notes_dir'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('notes_dir').value = data.notes_dir || '';
|
||||
@@ -266,7 +266,7 @@
|
||||
.catch(error => console.error('Error loading notes directory settings:', error));
|
||||
|
||||
// Load file extensions settings
|
||||
fetch('/editor/settings/file_extensions')
|
||||
fetch(window.prefix('/editor/settings/file_extensions'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('allowed_image_extensions').value = data.allowed_image_extensions || '';
|
||||
@@ -283,7 +283,7 @@
|
||||
.catch(error => console.error('Error loading file extensions settings:', error));
|
||||
|
||||
// Load security settings
|
||||
fetch('/editor/settings/security')
|
||||
fetch(window.prefix('/editor/settings/security'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
document.getElementById('pwd_failures_threshold').value = data.pwd_failures_threshold ?? '';
|
||||
@@ -322,7 +322,7 @@
|
||||
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/settings/security', {
|
||||
fetch(window.prefix('/editor/settings/security'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -348,7 +348,7 @@
|
||||
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/settings/image_storage', {
|
||||
fetch(window.prefix('/editor/settings/image_storage'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -377,7 +377,7 @@
|
||||
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/settings/notes_dir', {
|
||||
fetch(window.prefix('/editor/settings/notes_dir'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
@@ -406,7 +406,7 @@
|
||||
|
||||
const csrf = (document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1] ? decodeURIComponent((document.cookie.match(/(?:^|; )csrf_token=([^;]+)/)||[])[1]) : '';
|
||||
|
||||
fetch('/editor/settings/file_extensions', {
|
||||
fetch(window.prefix('/editor/settings/file_extensions'), {
|
||||
method: 'POST',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {},
|
||||
body: formData
|
||||
|
||||
@@ -10,11 +10,11 @@
|
||||
<h1 class="text-3xl font-bold text-white">{{.file_name}}</h1>
|
||||
<div class="flex items-center space-x-3">
|
||||
{{if and .Authenticated .is_editable}}
|
||||
<a href="/edit_text/{{.file_path}}" class="btn-primary">
|
||||
<a href="{{url (print "/editor/edit_text/" .file_path)}}" class="btn-primary">
|
||||
<i class="fas fa-edit mr-2"></i>Edit
|
||||
</a>
|
||||
{{end}}
|
||||
<a href="/download/{{.file_path}}" class="btn-secondary">
|
||||
<a href="{{url (print "/download/" .file_path)}}" class="btn-secondary">
|
||||
<i class="fas fa-download mr-2"></i>Download
|
||||
</a>
|
||||
{{if .Authenticated}}
|
||||
@@ -28,7 +28,7 @@
|
||||
{{if .folder_path}}
|
||||
<p class="text-gray-400">
|
||||
<i class="fas fa-folder mr-2"></i>
|
||||
<a href="/folder/{{.folder_path}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
<a href="{{url (print "/folder/" .folder_path)}}" class="text-blue-400 hover:text-blue-300">{{.folder_path}}</a>
|
||||
</p>
|
||||
{{end}}
|
||||
</div>
|
||||
@@ -72,8 +72,11 @@
|
||||
|
||||
document.getElementById('confirm-delete').addEventListener('click', function() {
|
||||
if (deleteTarget) {
|
||||
fetch('/delete/' + deleteTarget, {
|
||||
method: 'DELETE'
|
||||
const m = document.cookie.match(/(?:^|; )csrf_token=([^;]+)/);
|
||||
const csrf = m && m[1] ? decodeURIComponent(m[1]) : '';
|
||||
fetch(window.prefix('/editor/delete/' + deleteTarget), {
|
||||
method: 'DELETE',
|
||||
headers: csrf ? { 'X-CSRF-Token': csrf } : {}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
@@ -82,9 +85,9 @@
|
||||
// Redirect to folder or root
|
||||
const folderPath = '{{.folder_path}}';
|
||||
if (folderPath) {
|
||||
window.location.href = '/folder/' + folderPath;
|
||||
window.location.href = window.prefix('/folder/' + folderPath);
|
||||
} else {
|
||||
window.location.href = '/';
|
||||
window.location.href = window.prefix('/');
|
||||
}
|
||||
} else {
|
||||
throw new Error(data.error || 'Delete failed');
|
||||
|
||||
Reference in New Issue
Block a user