package handler import ( "crypto/subtle" "embed" "fmt" "html/template" "log" "net/http" "strings" "git.sr.ht/~kisom/goutils/config" "git.wntrmute.dev/kyle/quick-note/note" ) type Page struct { Message string } //go:embed templates/*.html var templateFiles embed.FS var templates = template.Must(template.ParseFS(templateFiles, "templates/*.html")) func BasicAuth(handler http.HandlerFunc, username, password, realm string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) {} } func Index(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() username := config.Get("HTTP_USER") password := config.Get("HTTP_PASS") if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 { w.Header().Set("WWW-Authenticate", `Basic realm="quicknote"`) w.WriteHeader(401) w.Write([]byte("Unauthorised.\n")) return } if r.Method == http.MethodPost { QuickNote(w, r) return } err := templates.ExecuteTemplate(w, "index.html", Page{}) if err != nil { log.Printf("error executing template: %s", err) http.Error(w, fmt.Sprintf("template execution failed: %s", err.Error()), http.StatusInternalServerError) return } } func QuickNote(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() username := config.Get("HTTP_USER") password := config.Get("HTTP_PASS") if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 { w.Header().Set("WWW-Authenticate", `Basic realm="quicknote"`) w.WriteHeader(401) w.Write([]byte("Unauthorised.\n")) return } log.Println("receiving note") s := r.FormValue("note") s = strings.TrimSpace(s) s = strings.Replace(s, "\r\n", "\n", -1) page := Page{} if len(s) != 0 { n := note.NewNote(s) err := n.Write() if err != nil { log.Printf("error writing note: %s", err) page.Message = err.Error() } else { log.Println("note created") page.Message = fmt.Sprintf("Created note %s", n.Header.Title()) } } else { log.Println("empty note received") } err := templates.ExecuteTemplate(w, "index.html", page) if err != nil { http.Error(w, fmt.Sprintf("template execution failed: %s", err.Error()), http.StatusInternalServerError) return } }